支付宝小程序授权登录(python SDK)

python SDK做授权登录,网上找不到python的例子,现写一个记录下来:

import logging
import traceback

from alipay.aop.api.AlipayClientConfig import AlipayClientConfig
from alipay.aop.api.DefaultAlipayClient import DefaultAlipayClient
from alipay.aop.api.constant.ParamConstants import *

from alipay.aop.api.request.AlipaySystemOauthTokenRequest import AlipaySystemOauthTokenRequest
from alipay.aop.api.response.AlipaySystemOauthTokenResponse import AlipaySystemOauthTokenResponse

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s %(levelname)s %(message)s',
    filemode='a',)
logger = logging.getLogger('')

if __name__ == '__main__':
    # 实例化客户端
    alipay_client_config = AlipayClientConfig()
    alipay_client_config.server_url = 'https://openapi.alipay.com/gateway.do'
    alipay_client_config.app_id = ''  #填appid
    alipay_client_config.app_private_key = ''  #应用私钥
    alipay_client_config.alipay_public_key = ''  #支付宝公钥
    client = DefaultAlipayClient(alipay_client_config, logger)

    request = AlipaySystemOauthTokenRequest()

    request.code = ""  #auth_code小程序上传的
    request.grant_type = "authorization_code"

    # 执行API调用
    try:
        response_content = client.execute(request)
    except Exception as e:
        print(traceback.format_exc())

    if not response_content:
        print("failed execute")
    else:
        # 解析响应结果
        response = AlipaySystemOauthTokenResponse()
        response.parse_response_content(response_content)
        if response.is_success():
            # 如果业务成功,可以通过response属性获取需要的值
            auth_token = response.access_token
            print("get auth_token:" + response.access_token)
        # 响应失败的业务处理
        else:
            # 如果业务失败,可以从错误码中可以得知错误情况,具体错误码信息可以查看接口文档
            print(response.code + "," + response.msg + "," + response.sub_code + "," + response.sub_msg)

 

你可能感兴趣的:(支付宝小程序授权登录(python SDK))