关于python使用支付宝当面付报错的解决方案

支付宝当面付的示例代码中,没有python的接口联调。因此,将统一收单线下交易预创建(alipay.trade.precreate,即生成商家及时收款二维码)相关python代码记录如下:

import logging
import traceback
from alipay.aop.api.AlipayClientConfig import AlipayClientConfig
from alipay.aop.api.DefaultAlipayClient import DefaultAlipayClient
from alipay.aop.api.domain.AlipayTradeCreateModel import AlipayTradeCreateModel
from alipay.aop.api.response.AlipayTradeCreateResponse import AlipayTradeCreateResponse
from alipay.aop.api.request.AlipayTradePrecreateRequest import (
    AlipayTradePrecreateRequest,
)

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 = "2021003126644838"
    alipay_client_config.app_private_key = "***"
    alipay_client_config.alipay_public_key = "***"
    client = DefaultAlipayClient(alipay_client_config, logger)

    # 构造请求参数对象
    model = AlipayTradeCreateModel()
    model.out_trade_no = "2115821010101001"
    model.total_amount = "88"
    model.subject = "Iphone6 16G"
    request = AlipayTradePrecreateRequest(biz_model=model)

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

    if not response_content:
        print("failed execute")
    else:
        # 解析响应结果
        response = AlipayTradeCreateResponse()
        response.parse_response_content(response_content)

        # 响应成功的业务处理
        if response.is_success():
            # 如果业务成功,可以通过response属性获取需要的值
            result_code = response.code
            if not result_code:
                result_code = 0
            if int(result_code) == 10000:
                print("成功")
            else:
                print("失败")
        # 响应失败的业务处理
        else:
            # 如果业务失败,可以从错误码中可以得知错误情况,具体错误码信息可以查看接口文档
            print(
                f"{response.code}, {response.msg}, {response.sub_code}, {response.sub_msg}"
            )

运行上述代码报错如下:

Traceback (most recent call last):
  File "/usr/local/lib/python3.10/dist-packages/alipay/aop/api/DefaultAlipayClient.py", line 125, in __prepare_request_params
    sign = sign_with_rsa2(self.__config.app_private_key, sign_content, self.__config.charset)
  File "/usr/local/lib/python3.10/dist-packages/alipay/aop/api/util/SignatureUtils.py", line 49, in sign_with_rsa2
    signature = rsa.sign(sign_content, rsa.PrivateKey.load_pkcs1(private_key, format='PEM'), 'SHA-256')
  File "/usr/local/lib/python3.10/dist-packages/rsa/key.py", line 125, in load_pkcs1
    return method(keyfile)
  File "/usr/local/lib/python3.10/dist-packages/rsa/key.py", line 613, in _load_pkcs1_pem
    return cls._load_pkcs1_der(der)
  File "/usr/local/lib/python3.10/dist-packages/rsa/key.py", line 548, in _load_pkcs1_der
    key = cls(*as_ints)
TypeError: int() argument must be a string, a bytes-like object or a real number, not 'Sequence'

支付宝开放平台-接口报错排查中,请求报文biz_content字段全部都不是预定字段。

此问题发生原因为,开放平台密钥工具生成的密码默认是PKCS8,而python的RSA库只能识别PKCS1版本。因此,把生成应用公钥并上传至支付宝后,还需要使用格式转换PKCS1,如下:

在上述程序的alipay_client_config.app_private_key字段使用输出部分内容即可。

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注