欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 高考 > python实现支付宝异步回调验签

python实现支付宝异步回调验签

2024/10/24 16:31:44 来源:https://blog.csdn.net/qq_27169365/article/details/140161688  浏览:    关键词:python实现支付宝异步回调验签

说明

python实现支付宝异步回调验签,示例中使用Django框架。
此方案使用了支付宝的pythonSDK,请一定装最新版本的,支付宝官网文档不知道多久没更新了,之前的版本pip安装会报一些c++库不存在的错误;

	pip install alipay-sdk-python==3.7.156

验签核心代码

from alipay.aop.api.util.SignatureUtils import verify_with_rsa#支付宝公钥
publicKey = ''def check_alipay_sign(request):"""验签:param request::return:"""sign = request.get('sign')  # 取出传过来的签#待签名字符串org_message = get_dic_sorted_params(request)# 转换成字节串message = bytes(org_message, encoding='utf-8')print(message)try:# 调用验签函数status = verify_with_rsa(publicKey, message, sign)return statusexcept Exception as e:print(f"Exception during signature verification: {e}")return False# 接收字典类型参数,去除sign、sign_type字段,转换成升序字符串
def get_dic_sorted_params(org_dic_params):content = ''org_dic_params.pop('sign')org_dic_params.pop('sign_type')                      # 去除sign、sigh_typenew_list = sorted(org_dic_params, reverse=False)     # 待验签参数进行排序for i in new_list:p = i+'='+ org_dic_params.get(i)+'&'content += psorted_params = content.strip('&')                   # 重组字符串,将{k:v}形式的字典类型原始响应值--》转换成'k1=v1&k2=v2'形式的字符串格式return sorted_params

djgano 调用

验签成功返回 SUCCESS,支付宝将将停止此订单的异步推送否则将会一共推送8次。

class alipayCallback(APIView):authentication_classes = []def post(self, request):"""支付宝支付回调- 内部订单号: request.POST.get('out_trade_no')- 交易状态: request.POST.get('trade_status') [TRADE_FINISHED:交易完结;TRADE_CLOSED:交易关闭;TRADE_SUCCESS:支付成功;WAIT_BUYER_PAY:交易创建]- 产品名称: request.POST.get('subject')- 总金额: request.POST.get('total_amount')- 实付金额: request.POST.get('buyer_pay_amount'):param request::return:"""orderId = str(request.POST.get('out_trade_no'))userId = orderId[orderId.index("#")+1:]print("内部订单号" + request.POST.get('out_trade_no'))print("订单号" + request.POST.get('trade_no'))  # 平台生成的订单号print("交易状态" + request.POST.get('trade_status'))print("产品名称" + request.POST.get('subject'))print("总金额" + request.POST.get('total_amount'))print("实付金额" + request.POST.get('buyer_pay_amount'))print(request.POST.dict())#验签 防止伪造请求if check_alipay_sign(request.POST.dict()):print("验签成功")"""# TODO 判断支付状态,订单状态修改                """return HttpResponse("SUCCESS")else:print("未支付成功!")return HttpResponse("未支付成功")else:print("验签失败")return HttpResponse("验签失败")

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com