def get_user_fund_balance(appid, access_token): #获取用户资金余额 access_url = "http://gw.open.ppdai.com/balance/balanceService/QueryBalance" data = {} sort_data = rsa.sort(data) sign = rsa.sign(sort_data) list_result = client.send(access_url,json.dumps(data) , appid, sign,access_token)
def getBalance(self): access_url = "https://openapi.ppdai.com/balance/balanceService/QueryBalance" data = {} sort_data = rsa.sort(data) sign = rsa.sign(sort_data) list_result = client.send(access_url, json.dumps(data), appid, sign, self.token) self.balance = list_result["Balance"][0]["Balance"] log("balance end",self.balance) return self.balance
def get_batch_listing_infos(appid, data): #新版散标详情批量接口(请求列表不大于10) utctime = datetime.datetime.utcnow() #data = {"timestamp":utctime.strftime('%Y-%m-%d %H:%M:%S')}#time.strftime('%Y-%m-%d %H:%M:%S',) access_url = "http://gw.open.ppdai.com/invest/LLoanInfoService/BatchListingInfos" sort_data = rsa.sort(data) sign = rsa.sign(sort_data) list_result = client.send(access_url, json.dumps(data) , appid, sign)
def get_listingids(appid, access_token): #获得投标标的 access_url = "http://gw.open.ppdai.com/invest/LLoanInfoService/LoanList" data = { "PageIndex": 3, "StartDateTime": "2015-11-11 12:00:00.000" } sort_data = rsa.sort(data) sign = rsa.sign(sort_data) list_result = client.send(access_url,json.dumps(data) , appid, sign)
def getListingIdInfo(ListingIds): access_url = "https://openapi.ppdai.com/listing/openapiNoAuth/batchListingInfo" data = { "ListingIds": ListingIds } sort_data = rsa.sort(data) sign = rsa.sign(sort_data) list_result = client.send(access_url, json.dumps(data) , appid, sign) if (list_result["Result"] != 1): log("error getListingIdInfo") return list_result["LoanInfos"]
def get_loan_detail_list(listing_ids): access_url = "http://gw.open.ppdai.com/invest/LLoanInfoService/BatchListingInfos" data = {"ListingIds": listing_ids} sort_data = rsa.sort(data) sign = rsa.sign(sort_data) list_result = client.send(access_url, json.dumps(data), appid, sign) # check result list_result_obj = json.loads(list_result.decode('utf-8')) if list_result_obj["Result"] == 1: return list_result_obj else: logging.error("Fail to get detail loan list.") return None
def bid(self,ListingId): access_url = "https://openapi.ppdai.com/listing/openapi/bid" access_token = self.token data = { "ListingId": ListingId, "Amount": 50, "UseCoupon":"true" } sort_data = rsa.sort(data) sign = rsa.sign(sort_data) list_result = client.send(access_url,json.dumps(data) , appid, sign,access_token) if list_result["Result"] != 0: log("bid faild",list_result) else: log("bid success",list_result)
def get_loan_list(index, date=None): # date "2015-11-11 12:00:00.000" access_url = "http://gw.open.ppdai.com/invest/LLoanInfoService/LoanList" if date is None: data = {"PageIndex": index} else: data = {"PageIndex": index, "StartDateTime": date} sort_data = rsa.sort(data) sign = rsa.sign(sort_data) list_result = client.send(access_url, json.dumps(data), appid, sign) # check result list_result_obj = json.loads(list_result) if list_result_obj["Result"] == 1: return list_result_obj else: logging.error("Fail to get loan list.") return None
def getListingIdList(): access_url = "https://openapi.ppdai.com/listing/openapiNoAuth/loanList" data = { "PageIndex": 1, "StartDateTime": "2015-11-11 12:00:00.000" } sort_data = rsa.sort(data) sign = rsa.sign(sort_data) list_result = client.send(access_url, json.dumps(data) , appid, sign) if (list_result["Result"] != 1): log("error getListingIdList") return [] ListingIds = [] for LoanInfo in list_result["LoanInfos"]: if LoanInfo["CreditCode"] != "AA": ListingIds.append(LoanInfo["ListingId"]) return ListingIds
def make_bid(listing_id, amount): access_url = "http://gw.open.ppdai.com/invest/BidService/Bidding" access_token = "1ff70da4-909e-4ce0-ab17-0f75debd5c1d" data = {"ListingId": listing_id, "Amount": amount, "UseCoupon": "true"} sort_data = rsa.sort(data) sign = rsa.sign(sort_data) list_result = client.send(access_url, json.dumps(data), appid, sign, access_token) # check result list_result_obj = json.loads(list_result) if list_result_obj["Result"] == 0: logging.info("Success to bid %s", listing_id) return list_result_obj else: logging.warning("Warning: fail to make bid %s. Reason: %s", listing_id, list_result_obj["ResultMessage"]) return None
"StartTime": time.strftime('%Y-%m-%d', time.localtime(float(StartTime))), "EndTime": time.strftime('%Y-%m-%d', time.localtime(float(current))), "PageIndex": 1, "PageSize": 500 } while True: time.sleep(0.5) sort_data = rsa.sort(data) sign = rsa.sign(sort_data) list_result = client.send(access_url, json.dumps(data), APPID, sign, AccessToken) if list_result == '': continue else: list_result = json.loads(list_result) break for item in list_result['BidList']: if int(item['ListingId']) == 0: continue total += 1 listings.append([ item['ListingId'], str(item['Title']), item['Months'], item['Rate'], item['Amount'], OpenID
code = "5ae2ee0d135b47ac806fb822fe5477bd" #step 1 授权 #authorizeStr = client.authorize(appid=appid,code=code) #获得授权 #authorizeObj = pickle.loads(authorizeStr) # 将返回的authorize对象反序列化成对象,成功得到 OpenID、AccessToken、RefreshToken、ExpiresIn #{"OpenID":"xx","AccessToken":"xxx","RefreshToken":"xxx","ExpiresIn":604800} #{"OpenID":"cecef9dee01d430484342f5d45cf4b1b","AccessToken":"bdfbfc75-ca6e-4ccd-8304-b37e79ff795f","RefreshToken":"aaeca9c2-5d27-4dea-ac03-1a1fa84b136f","ExpiresIn":604800} #step 1 刷新令牌 #openid="cecef9dee01d430484342f5d45cf4b1b" #refreshtoken= "aaeca9c2-5d27-4dea-ac03-1a1fa84b136f" #new_token_info = client.refresh_token(appid, openid, refreshtoken) #step 2 发送数据(可投标列表接口) access_url = "https://openapi.ppdai.com/invest/LLoanInfoService/BatchListingInfos" #"https://openapi.ppdai.com/auth/registerservice/accountexist" #"https://openapi.ppdai.com/invest/LLoanInfoService/BatchListingInfos" #"https://openapi.ppdai.com/invest/BidproductlistService/LoanList" access_token = "bdfbfc75-ca6e-4ccd-8304-b37e79ff795f" #access_token="" utctime = datetime.datetime.utcnow() #data = {"timestamp":utctime.strftime('%Y-%m-%d %H:%M:%S')}#time.strftime('%Y-%m-%d %H:%M:%S',) data = {"Listingids": [27450479, 27450480]} #data = { "AccountName": "15200000001"} sort_data = rsa.sort(data) sign = rsa.sign(sort_data) #data = {"listingids": [27450479,27450480]} list_result = client.send(access_url, json.dumps(data), appid, sign, access_token)
def invest(): if not 'OpenID' in session: return redirect(url_for('index')) refresh() # report() dataset = {} (db, cursor) = connectdb() cursor.execute("select * from json_data where page=%s", ['invest']) json_data = cursor.fetchall() dataset['json'] = { item['keyword']: json.loads(item['json']) for item in json_data } tmp = [] for key, value in dataset['json']['strategy_stat'].items(): value['name'] = key value[u'平均金额'] = int(value[u'总金额'] / value[u'数量']) for k, v in value.items(): if k in ['平均利率', '平均期限']: value[k] = '%.2f' % value[k] elif k in ['10日坏标逾期率', '30日坏标逾期率', '90日坏标逾期率']: value[k] = '%.3f' % value[k] tmp.append(value) dataset['json']['strategy_stat'] = tmp cursor.execute("select * from strategy where OpenID=%s", ['0']) dataset['sys'] = cursor.fetchall() cursor.execute("select * from strategy where OpenID=%s", [session['OpenID']]) dataset['my'] = cursor.fetchall() cursor.execute("select strategy from user where OpenID=%s", [session['OpenID']]) if len(dataset['my']) < 4: dataset['add'] = True else: dataset['add'] = False dataset['strategy_count'] = 0 dataset['strategy_weight'] = {u'初始评级': 0, u'借款利率': 0, u'借款期限': 0} sys_strategy = cursor.fetchone()['strategy'] if not sys_strategy == '': sys_strategy = sys_strategy.split('-') for s in sys_strategy: for x in xrange(0, len(dataset['sys'])): if int(dataset['sys'][x]['id']) == int(s): dataset['sys'][x]['active'] = 1 dataset['strategy_count'] += 1 content = json.loads(dataset['sys'][x]['content']) for key in content.keys(): if dataset['strategy_weight'].has_key(key): dataset['strategy_weight'][key] += 1 break for item in dataset['my']: if int(item['active']) == 1: content = json.loads(item['content']) for key in content.keys(): if dataset['strategy_weight'].has_key(key): dataset['strategy_weight'][key] += 1 dataset['strategy_weight'] = { 'x': [key for key in dataset['strategy_weight'].keys()], 'data': [value for value in dataset['strategy_weight'].values()] } cursor.execute( "select balance, balanceBid, balanceWithdraw from user where OpenID=%s", [session['OpenID']]) dataset['balance'] = cursor.fetchone() cursor.execute("select count(*) as count from bidding where OpenID=%s", [session['OpenID']]) dataset['bidding_count'] = cursor.fetchone()['count'] cursor.execute( "select count(*) as count from strategy where OpenID=%s and active=%s", [session['OpenID'], 1]) dataset['strategy_count'] += cursor.fetchone()['count'] dates = [] start = 1483200000 while True: b = time2str(start, '%Y-%m-%d') if b[:4] == '2017': dates.append(b) start += 3600 * 24 else: break dataset['calendar'] = { 'count': {d: 0 for d in dates}, 'amount': {d: 0 for d in dates} } cursor.execute( "select * from bidding where OpenID=%s order by timestamp asc", [session['OpenID']]) biddings = cursor.fetchall() for item in biddings: d = time2str(float(item['timestamp']), '%Y-%m-%d') dataset['calendar']['count'][d] += 1 dataset['calendar']['amount'][d] += item['amount'] dataset['calendar']['max_count'] = np.max( [v for v in dataset['calendar']['count'].values()]) dataset['calendar']['count'] = [[ d, dataset['calendar']['count'][d], dataset['calendar']['amount'][d] ] for d in dates] if len(biddings) > 0: cursor.execute( "select ListingId, CreditCode, Months, CurrentRate, Title from listing where ListingId in %s", [[x['ListingId'] for x in biddings]]) tmp = cursor.fetchall() tmp = {str(t['ListingId']): t for t in tmp} d = [] for x in range(0, len(biddings)): lid = str(biddings[x]['ListingId']) if tmp.has_key(lid): biddings[x]['CreditCode'] = tmp[lid]['CreditCode'] biddings[x]['Months'] = tmp[lid]['Months'] biddings[x]['CurrentRate'] = tmp[lid]['CurrentRate'] biddings[x]['Title'] = tmp[lid]['Title'] biddings[x]['timestamp'] = time2str( float(biddings[x]['timestamp']), "%Y-%m-%d %H:%M:%S") d.append(biddings[x]) biddings = d cursor.execute( "select id, name from strategy where OpenID=%s or OpenID=%s", ['0', session['OpenID']]) tmp = cursor.fetchall() tmp = {str(t['id']): t['name'] for t in tmp} for x in range(0, len(biddings)): biddings[x]['strategy'] = tmp[str(biddings[x]['strategyId'])] dataset['biddings'] = biddings while True: access_url = "http://gw.open.ppdai.com/invest/LLoanInfoService/LoanList" data = { "PageIndex": 1, } sort_data = rsa.sort(data) sign = rsa.sign(sort_data) list_result = client.send(access_url, json.dumps(data), APPID, sign) if list_result == '': continue else: list_result = json.loads(list_result) break mapping = {} mapping['AAA'] = 15 mapping['AA'] = 10 mapping['A'] = 5 mapping['B'] = 3 mapping['C'] = 1 mapping['D'] = 0 mapping['E'] = 0 mapping['F'] = 0 colorset = {} colorset['AAA'] = 'rgba(243, 230, 162, 0.9)' colorset['AA'] = 'rgba(234, 126, 83, 0.9)' colorset['A'] = 'rgba(221, 107, 102, 0.9)' colorset['B'] = 'rgba(230, 157, 135, 0.9)' colorset['C'] = 'rgba(215, 135, 230, 0.9)' colorset['D'] = 'rgba(110, 113, 199, 0.9)' colorset['E'] = 'rgba(109, 188, 191, 0.9)' colorset['F'] = 'rgba(117, 179, 117, 0.9)' for x in range(0, len(list_result['LoanInfos'])): item = list_result['LoanInfos'][x] list_result['LoanInfos'][x]['score'] = mapping[item['CreditCode']] * ( int(item['Rate']) - 9) * (6 / float(item['Months'])) list_result['LoanInfos'][x][ 'ratio'] = 95 - 95 * item['RemainFunding'] / item['Amount'] list_result['LoanInfos'][x]['color'] = colorset[item['CreditCode']] list_result['LoanInfos'].sort(key=lambda x: x['score'], reverse=True) dataset['listings'] = list_result['LoanInfos'][:10] if len(dataset['listings']) == 0: data['listing_max'] = 0.0000001 else: dataset['listing_max'] = np.max( [float(x['score']) for x in dataset['listings']]) for x in xrange(0, len(dataset['listings'])): dataset['listings'][x]['score'] = '%.2f' % ( 0.98 * dataset['listings'][x]['score'] / dataset['listing_max']) dataset['listings'][x]['Amount'] = int( dataset['listings'][x]['Amount']) dataset['listings'][x]['RemainFunding'] = int( dataset['listings'][x]['RemainFunding']) closedb(db, cursor) return render_template('invest.html', auth=is_auth(), datasetJson=json.dumps(dataset), dataset=dataset)