腾讯云人脸核身后端API——python

2021/10/13 17:14:17

本文主要是介绍腾讯云人脸核身后端API——python,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

import json, random, requests, hashlib, traceback

# 配置
FACERECOGNITION_SETTING = {
    'access_token_usl': "https://miniprogram-kyc.tencentcloudapi.com/api/oauth2/access_token",
    'SIGN_ticket_usl': "https://miniprogram-kyc.tencentcloudapi.com/api/oauth2/api_ticket",
    'getfaceid': "https://miniprogram-kyc.tencentcloudapi.com/api/server/getfaceid?orderNo=",
    'NONCE_ticket_url': 'https://miniprogram-kyc.tencentcloudapi.com/api/oauth2/api_ticket',

    'app_id': "app_id",  # 腾讯云提供
    'secret': "secret",  # 腾讯云提供

    'version': '1.0.0',
}

r = redis链接


class FacerecognitionBase:
    """
    继承Facerecognition
    调用 self.get_data(self, serId, userName, idNo)
    return: {
            "faceId": faceId,
            "webankAppId": webankAppId,
            "orderNo": orderNo,
            "nonce": nonce,
            "sign": sign
        }
    """

    access_token_usl = FACERECOGNITION_SETTING['access_token_usl']
    SIGN_ticket_usl = FACERECOGNITION_SETTING['SIGN_ticket_usl']
    getfaceid = FACERECOGNITION_SETTING['getfaceid']
    NONCE_ticket_url = FACERECOGNITION_SETTING['NONCE_ticket_url']

    app_id = FACERECOGNITION_SETTING['app_id']
    secret = FACERECOGNITION_SETTING['secret']

    version = FACERECOGNITION_SETTING['version']

    # 获取access_token
    def __get_access_token(self):
        access_token = r.get('access_token')
        if not access_token:
            data = {
                "app_id": self.app_id,
                "secret": self.secret,
                "grant_type": 'client_credential',
                "version": self.version,
            }
            msg = requests.get(self.access_token_usl, data)
            msg = json.loads(msg.text)
            # msg = {
            #     "code": "0",
            #     "msg": "请求成功",  # 请求结果描述
            #     "transactionTime": "20151022043831",  # 调用接口的时间
            #     "access_token": "accessToken_string",  # access_token 的值
            #     "expire_time": "20151022043831",  # access_token 失效的绝对时间
            #     "expire_in": "7200"  # access_token 的最大生存时间
            # }
            if msg['code'] != '0':
                print("access_token:\n", '%s\n' % data, msg)
                raise Exception(msg['msg'])
            r.set('access_token', msg['access_token'])
            r.expire('access_token', int(msg['expire_in']) - 10)
            access_token = msg['access_token']
        return access_token

    # 获取SIGN_ticket
    def __get_SIGN_ticket(self):
        SIGN_ticket = r.get('SIGN_ticket')
        if not SIGN_ticket:
            access_token = self.__get_access_token()
            data = {
                "app_id": self.app_id,
                "access_token": access_token,
                "type": 'SIGN',
                "version": self.version,
            }
            msg = requests.get(self.SIGN_ticket_usl, data)
            msg = json.loads(msg.text)
            # msg = {
            #     "code": "0",
            #     "msg": "请求成功",  # 请求结果描述
            #     "transactionTime": "20151022044027",  # 调用接口的时间
            #     "tickets": [  # ticket 返回数组
            #         {
            #             "value": "ticket_string",  # ticket 的值
            #             "expire_in": "3600",  # ticket 失效的绝对时间
            #             "expire_time": "20151022044027"  # ticket 的最大生存时间
            #         }
            #     ]
            # }
            if msg['code'] != '0':
                print("SIGN_ticket:\n", '%s\n' % data, msg)
                raise Exception(msg['msg'])
            else:
                r.set('SIGN_ticket', msg['tickets'][0]['value'])
                r.expire('SIGN_ticket', int(msg['tickets'][0]['expire_in']) - 10)
                SIGN_ticket = msg['tickets'][0]['value']
        return SIGN_ticket

    # 生成随机数
    def get_nonce(self, num=32):
        return ''.join((str(random.choice([random.randint(0, 9), chr(random.randint(65, 90)),
                                           chr(random.randint(97, 122))])) for i in range(num)))

    # 生成签名
    def __get_sign(self, userId, ticket):
        l = [self.version, self.app_id, ticket, self.nonce, userId]
        l.sort()
        info = ''.join(l)
        s1 = hashlib.sha1()
        s1.update(info.encode("utf-8"))  # 转码(字节流)
        return s1.hexdigest()  # 将字节码转成16进制

    # 获取NONCE_ticket
    def __get_NONCE_ticket(self, user_id):
        data = {
            "app_id": self.app_id,
            "access_token": self.__get_access_token(),
            "type": 'NONCE',
            "version": self.version,
            "user_id": user_id,
        }
        msg = requests.get(self.NONCE_ticket_url, data)
        msg = json.loads(msg.text)
        if msg['code'] != "0":
            print("NONCE_ticket:\n", '%s\n' % data, msg)
            raise Exception(msg['msg'])
        return msg['tickets'][0]['value']

    # nonce加密签名
    def nonce_sign(self, userId):
        return self.__get_sign(userId, self.__get_NONCE_ticket(userId))

    # 获取faceId
    def get_faceId(self, userId, name, idNo):
        self.nonce = self.get_nonce()
        self.orderNo = self.get_nonce()
        self.sign = self.__get_sign(userId, self.__get_SIGN_ticket())
        data = {
            "webankAppId": self.app_id,  # wbappid
            "orderNo": self.orderNo,  # 订单号
            "name": name,  # 姓名
            "idNo": idNo,  # 证件号码
            "userId": userId,  # 用户 ID
            "version": self.version,
            "sign": self.sign,  # 签名:使用上面生成的签名
            "nonce": self.nonce,  # 随机数
        }
        url = self.getfaceid + self.orderNo
        msg = requests.post(url, json=data)
        msg = json.loads(msg.text)

        if msg.get('code') != "0":
            raise Exception('获取faceId错误\n%s' % msg['error'])
        return msg['result']['faceId']

	# 获取信息
    def get_data(self, serId, userName, idNo):
        userId = userId  # 用户Id,自己生成
        userName = userName  # 用户身份证名字
        idNo = idNo  # 用户身份证号

        try:
            msg = self.get_faceId(userId, userName, idNo)
        except Exception as e:
            return {'e': e.__str__(), "Exception": traceback.format_exc()}
        
        return {
            "faceId": msg,
            "webankAppId": self.app_id,
            "orderNo": self.orderNo,
            "nonce": self.nonce,
            "sign": self.nonce_sign(userId)
        }



这篇关于腾讯云人脸核身后端API——python的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程