首页 > 基础资料 博客日记

python支付宝支付和回调

2024-10-27 15:00:10基础资料围观89

Java资料网推荐python支付宝支付和回调这篇文章给大家,欢迎收藏Java资料网享受知识的乐趣

创建支付订单

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


if __name__ == '__main__':
    """
    设置配置,包括支付宝网关地址、app_id、应用私钥、支付宝公钥等,其他配置值可以查看AlipayClientConfig的定义。
    """
    alipay_client_config = AlipayClientConfig()
    alipay_client_config.server_url = 'https://openapi.alipay.com/gateway.do'
    alipay_client_config.app_id = '[your app_id]'
    alipay_client_config.app_private_key = '[your app private key]'
    alipay_client_config.alipay_public_key = '[alipay public key]'

    """
    得到客户端对象。
    注意,一个alipay_client_config对象对应一个DefaultAlipayClient,定义DefaultAlipayClient对象后,alipay_client_config不得修改,如果想使用不同的配置,请定义不同的DefaultAlipayClient。
    logger参数用于打印日志,不传则不打印,建议传递。
    """
    client = DefaultAlipayClient(alipay_client_config=alipay_client_config, logger=logger)

    """
    系统接口示例:alipay.trade.pay
    """
    # 对照接口文档,构造请求对象
    model = AlipayTradePayModel()
    model.auth_code = "282877775259787048"
    model.body = "Iphone6 16G"
    goods_list = list()
    goods1 = GoodsDetail()
    goods1.goods_id = "apple-01"
    goods1.goods_name = "ipad"
    goods1.price = 10
    goods1.quantity = 1
    goods_list.append(goods1)
    model.goods_detail = goods_list
    model.operator_id = "yx_001"
    model.out_trade_no = "20180510AB014"
    model.product_code = "FACE_TO_FACE_PAYMENT"
    model.scene = "bar_code"
    model.store_id = ""
    model.subject = "huabeitest"
    model.timeout_express = "90m"
    model.total_amount = 1
    request = AlipayTradePayRequest(biz_model=model)
    # 如果有auth_token、app_auth_token等其他公共参数,放在udf_params中
    # udf_params = dict()
    # from alipay.aop.api.constant.ParamConstants import *
    # udf_params[P_APP_AUTH_TOKEN] = "xxxxxxx"
    # request.udf_params = udf_params
    # 执行请求,执行过程中如果发生异常,会抛出,请打印异常栈
    response_content = None
    try:
        response_content = client.execute(request)
    except Exception as e:
        print(traceback.format_exc())
    if not response_content:
        print("failed execute")
    else:
        response = AlipayTradePayResponse()
        # 解析响应结果
        response.parse_response_content(response_content)
        print(response.body)
        if response.is_success():
            # 如果业务成功,则通过respnse属性获取需要的值
            print("get response trade_no:" + response.trade_no)
        else:
            # 如果业务失败,则从错误码中可以得知错误情况,具体错误码信息可以查看接口文档
            print(response.code + "," + response.msg + "," + response.sub_code + "," + response.sub_msg)

回调验证签名

from alipay.aop.api.util.SignatureUtils import verify_with_rsa

# 支付宝公钥
alipay_public_key = '你的支付公钥'

# 待签名字符串需要做升序处理,且去除sign和sign_type
org_message = '返回的body'

# 转换成字节串
message = bytes(org_message, encoding='utf-8')

# 返回的sign值(需要base64解码,python中sign解码封装在了verify_with_rsa方法中)
sign = 'body中截取的sign'

# 签名方法
data= verify_with_rsa(alipay_public_key, message, sign)

# 输出验签结果
print(data)

        try:
            # 处理支付成功的逻辑
            if data.get('trade_status') == 'TRADE_SUCCESS':
                order_no = data.get('out_trade_no')

                # 查询订单 对订单进行更新等操作
      			return JSONResponse(status_code=200,
                                    content={'code': 1, 'msg': '支付成功'})

            # 处理支付失败的逻辑
            elif data.get('trade_status') in ['TRADE_CLOSED', 'TRADE_FINISHED']:
                order_no = data.get('out_trade_no')
                # 支付失败的对订单更新操作
                return JSONResponse(status_code=200,
                                    content={'code': 1, 'msg': '支付失败'})




文章来源:https://blog.csdn.net/qq_15596445/article/details/143113328
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!

标签:

相关文章

本站推荐

标签云