#!/usr/bin/env python3
import requests
import json
import hashlib
import hmac
import re
from Crypto.Cipher import AES
import binascii

# 一键登录，请求获取手机号接口demo

appId = "xxxx"  # 应用APPID
appKey = "xxx"  # 应用APPKEY
url = 'https://api.253.com/open/flashsdk/mobile-query'
token = 'xxxx'  # SDK返回token
# 加密方式 0 - 默认
encryptType = 0


def sign_params(data):
    message = ''
    if 'appId' in data:
        message += 'appId' + data['appId']
    if 'clientIp' in data:
        message += 'clientIp' + data['clientIp']
    if 'encryptType' in data:
        message += 'encryptType' + str(data['encryptType'])
    if 'token' in data:
        message += 'token' + data['token']
    signature = hmac.new(appKey.encode(), msg=message.encode(
    ), digestmod=hashlib.sha256).hexdigest()
    data['sign'] = signature


def decrpt_phone(data):
    md5 = hashlib.md5()
    md5.update(appKey.encode())
    keyHash = md5.hexdigest()
    cipher = AES.new(keyHash[:16], AES.MODE_CBC, keyHash[-16:])
    msg = cipher.decrypt(binascii.a2b_hex(data))
    return unpad(msg).decode()


def unpad(s):
    return s[0:-ord(s[-1:])]


if __name__ == "__main__":
    formData = {
        'appId': appId,
        # 'encryptType': encryptType,
        'token': token,
        # 'clientIp': '127.0.0.1',
        'sign': ''
    }
    sign_params(formData)
    r = requests.post(url, data=formData)
    print("置换手机号响应: %s" % r.json())
    resp = r.json()
    if resp["code"] == "200000":
        if encryptType == 0:  # 默认为AES加密
            data = resp['data']
            tradeNo = data['tradeNo']  # 交易流水号
            mobileName = data['mobileName']  # 手机号密文
            mobile = decrpt_phone(mobileName)
            print('手机号: %s' % mobile)
    else:
        print('获取手机号失败')
