微擎支付返回商户单号_微信app支付对接总结
生活随笔
收集整理的這篇文章主要介紹了
微擎支付返回商户单号_微信app支付对接总结
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
最近對接了安卓開發,涉及到了微信支付,需要調取微信app支付相關的接口,目前我們項目中使用的是微信普通商戶版的。我們開發的安卓APP調用微信提供的SDK調用微信支付模塊,安卓APP會跳轉到微信中完成支付,支付完后跳回到安卓APP內,最后展示支付結果。我們后端涉及到的接口主要是統一下單接口、調起支付接口,支付結果通知接口。
首先按照統微信統一下單接口文檔,把所有必填參數發送給統一下單接口在微信支付服務后臺生成預支付交易單,如果成功統一下單接口會返回給你一個prepayid(這個很重要),然后再按照微信支付接口文檔要求,把必填的字段以及之前返回給你的prepay_id發送給安卓app端,安卓app會調取微信支付接口。微信會根據你之前在統一下單接口中傳遞的notify_url字段,回調你的接口(這個接口必須是線上環境,外界可以訪問的),通知你支付是否成功,參考支付結果通知。微信app支付的流程大體是這樣的。需要注意的是簽名的生成,必須要把參數按照ASCII 碼進行排序。
下面附代碼
import datetime import logging import time import uuid from decimal import Decimalimport requests from django.db import transaction from wechatpy.pay.utils import calculate_signaturedef order_wx_app_pay(main_order):"""訂單微信APP支付:param main_order::return:"""unpaid_amount = main_order.get_unpaid_amount()if unpaid_amount <= 0:return False, ErrorCode.NOT_TO_PAY_ORDER# company = main_order.company# account = company.wx_account# sub_mch_id = account.mchid# if not sub_mch_id:# return False, ErrorCode.NOT_COMPANY_MCH_ID# ip = self.request.headers.get('X-Real-Ip', 0) or self.request.remote_ipip = "127.0.0.1"nonce_str = uuid.uuid1().hex.upper()notify_url = WxConfig.NOTIFY_URLbody = "商品名稱"req_args = {"appid": WxConfig.WX_PAY_APP_ID_OFFICAL, # 商戶的APPID"mch_id": WxConfig.MCH_ID, # 商戶號"nonce_str": nonce_str, # 隨機字符串"body": body.encode("utf-8"), # 商品描述"out_trade_no": main_order.order_number, # 商戶訂單號"total_fee": int(unpaid_amount * 100), # 總金額"spbill_create_ip": ip, # 終端IP"notify_url": notify_url, # 通知地址"trade_type": "APP" # 交易類型}# 生成簽名req_sign = calculate_signature(req_args, WxConfig.WX_PAY_API_KEY)req_args['sign'] = req_signreq_xml = trans_dict_to_xml(req_args)# 定義返回信息return_code, return_msg, result_code = None, None, Noneprepay_id = None# 調用微信統一下單接口,正常返回prepay_idtry:response = requests.post(url=WxConfig.URL_PAY_WX_MP, data=req_xml)response.encoding = "utf8"result = response.textresult = trans_xml_to_dict(result)return_code = result['return_code']return_msg = result['return_msg']if return_code == "SUCCESS":result_code = result['result_code']if result_code == 'SUCCESS':prepay_id = result.get('prepay_id')else:err_code_des = result.get("err_code_des", ErrorCode.NOT_PREPAY_ID[1])return False, (99999, err_code_des)else:return False, (99999, return_msg)except Exception as e:log_service.exception(e)log_service.info('PayResult ReturnCode:%s ReturnMSG:%s ResultCode:%s PrePayID:%s',return_code, return_msg, result_code, prepay_id)if not prepay_id:return False, ErrorCode.NOT_PREPAY_IDts_str = str(int(time.time()))_nonce_str = uuid.uuid1().hex.upper()app_sign_args = {'appid': WxConfig.WX_PAY_APP_ID_OFFICAL, # 子商戶在微信開放平臺上申請的APPID'noncestr': _nonce_str, # 隨機字符串'package': 'Sign=WXPay', # 擴展字段'partnerid': WxConfig.MCH_ID, # 子商戶的商戶號"prepayid": prepay_id, # 微信返回的支付交易會話ID'timestamp': ts_str, # 時間戳}app_sign = calculate_signature(app_sign_args, WxConfig.WX_PAY_API_KEY)app_sign_args['sign'] = app_signreturn True, app_sign_argsdef wx_pay_notify(request):"""訂單微信支付回調"""return_code = "FAIL"log_service.info(request.data)try:notify_data = trans_xml_to_dict(request.data)except:return_msg = ErrorCode.FORMAT_ERROR_PAY_NOTIFYreturn trans_dict_to_xml({"return_code": return_code, "return_msg": return_msg})wx_sign = notify_data.pop("sign", "")app_sign = calculate_signature(notify_data, WxConfig.WX_PAY_API_KEY)if wx_sign != app_sign:return_msg = ErrorCode.BAD_SIGNreturn trans_dict_to_xml({"return_code": return_code, "return_msg": return_msg})if notify_data["return_code"] != "SUCCESS":return_msg = notify_data["err_code_des"]return trans_dict_to_xml({"return_code": return_code, "return_msg": return_msg})transaction_id = notify_data.get("transaction_id", "") # 微信支付訂單號out_trade_no = notify_data.get("out_trade_no", "") # 商戶訂單號total_fee = notify_data.get("total_fee", "") # 訂單總金額,單位為分pay_time_str = notify_data.get("pay_time", "") # 支付完成時間try:pay_time = datetime.datetime.strptime(pay_time_str, "%Y%m%d%H%M%S")except:pay_time = datetime.datetime.now()if not OrderPay.objects.filter(transaction_id=transaction_id).exists():main_order = MainOrder.objects.get(orderno=out_trade_no)data = {"main_order": main_order,"amount": Decimal(total_fee) / 100,"pay_time": pay_time,"pay_method": MainOrderPayMethod.wx,"confirm_time": datetime.datetime.now(),"status": OrderPayLogStatus.had_pay,}with transaction.atomic():order_pay = OrderPay.objects.create(**data)order_pay.gene_order_number()flow_main_order.update_main_order_paid_amount_status(main_order=main_order) # 更新訂單的支付金額和支付狀態return_code = "SUCCESS"return_msg = "ok"return trans_dict_to_xml({"return_code": return_code, "return_msg": return_msg})參考
【微信支付】APP支付開發者文檔?pay.weixin.qq.com總結
以上是生活随笔為你收集整理的微擎支付返回商户单号_微信app支付对接总结的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2021-01-15 记一次微信支付订单
- 下一篇: 微信支付交易查询案例