This article mainly introduces Python to implement Alipay face-to-face payment and scan code payment functions in detail. It has a certain reference value. Interested friends can refer to it.
The examples in this article are shared with everyone. The specific code for implementing Alipay face-to-face payment in python is for your reference. The specific content is as follows
1. Configuration information preparation
Log in to the Ant Financial Open Platform: https://open.alipay.com /platform/home.htm
Read development materials: https://docs.open.alipay.com/194/106078
After creating the application and configuring the key and other information, It’s ready for development.
2. Development of Alipay payment tool class
1: Related configuration information
# ========支付相关配置信息=========== ALIPAY_INPUT_CHARSET = 'utf-8' # 商户ID,以2088开头的16位纯数字 ALIPAY_PARTNER = '2088************' # 服务商支付宝账号 ALIPAY_SELLER_EMAIL = '' # 支付结果回调地址 ALIPAY_NOTIFY_URL = "商家后台回调接口地址" # 访问模式,根据自己的服务器是否支持ssl访问,若支持请选择https;若不支持请选择http ALIPAY_TRANSPORT = 'https' #签名加密方式 SIGN_TYPE = "SHA-1" #应用id APP_ID = '************' #下单api precreate_GATEWAY=https://openapi.alipay.com/gateway.do?
2. Three auxiliary functions:
#1:生成下单请求参数字符串 def make_payment_request(self,params_dict): """ 构造支付请求参数 :param params_dict: :return: """ query_str = self.params_to_query(params_dict,) # 拼接参数字符串 sign = self.make_sign(query_str) # 生成签名 sign = urllib.quote(sign, safe='') #解决中文参数编码问题 res = "%s&sign=%s" % (query_str, sign) return res def params_to_query(self,params): """ 生成需要签名的字符串 :param params: :return: """ """ :param params: :return: """ query = "" dict_items = {} for key, value in params.items(): if isinstance(value, dict) == True: dict_items[key] = value params[key] = "%s" all_str = '' for key in sorted(params.keys()): #把参数按key值排序:这是支付宝下单请求的参数格式规定 all_str = all_str + '%s=%s&' % (key, params[key]) all_str = all_str.rstrip('&') biz_content_dict = dict_items['biz_content'] content_str = '' for key in sorted(biz_content_dict.keys()): if isinstance(biz_content_dict[key], basestring) == True: content_str = content_str + '"%s":"%s",' % (key, biz_content_dict[key]) else: content_str = content_str + '"%s":%s,' % (key, biz_content_dict[key]) content_str = content_str.rstrip(',') content_str = '{' + content_str + '}' query = all_str % content_str return query def make_sign(self,para_str): """ 生成签名 :param message: :return: """ private_key = OpenSSL.crypto.load_privatekey(OpenSSL.crypto.FILETYPE_PEM, open( './路径/private_key.txt').read()) #把私钥存到一个文件里,加载出来【尝试过用rsa模块的方法加载私钥字符串,会报格式错误。查看源码得知,需要从文件流加载】 import sys reload(sys) sys.setdefaultencoding('utf-8') #这三句:解决签名方法编码报错 sign = base64.encodestring(OpenSSL.crypto.sign(private_key, para_str, 'sha256')) return sign
3. Place an order
#获取二维码url def getAlipayUrl(self,orderid,goodsName,goodsPrice,**kwargs): # 构建公共参数 params = {} params['method'] = 'alipay.trade.precreate' params['version'] = '1.0' params['app_id'] = self.APP_ID params['timestamp'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S') params['charset'] = self.ALIPAY_INPUT_CHARSET params['notify_url'] = self.ALIPAY_NOTIFY_URL params['sign_type'] = 'RSA2' # 构建订单参数 biz_content = {} biz_content['out_trade_no'] = orderid # 订单号 biz_content['subject'] = goodsName #商品名 biz_content['total_amount'] = goodsPrice # 价格 params['biz_content'] = biz_content #由参数,生成签名,并且拼接得到下单参数字符串 encode_params = self.make_payment_request(params) #下单 url = self.precreate_GATEWAY + encode_params response = requests.get(url) #提取下单响应 body = response.text #解析下单响应json字符串 body_dict = json.loads(body) return_msg = body_dict['alipay_trade_precreate_response']['msg'] if return_msg == "Success": code_url = body_dict['alipay_trade_precreate_response']['qr_code'] return code_url else: print "fail msg=============" + return_msg
3. On the controller side, receive customers With the order number, product name, and product price passed from the client, the payment tool class is called, the QR code link is obtained, and the QR code is generated based on the link and passed to the client.
(This is the same as WeChat scan code payment mode 2)
Fourth, on the controller side, write the payment result callback function
def aliQRCodeNotify(self, request, *args,**kwargs): out_trade_no = kwargs.get("out_trade_no") trade_status = kwargs.get("trade_status") #根据trade_status,判断交易结果:交易成功 or 交易关闭 #根据out_trade_no 更新订单记录信息
5. Client polling
The same as the second client polling idea of WeChat scan code payment mode.
Related recommendations:
Python implements supermarket scanner billing
Python implements simple Taobao flash sale function
The above is the detailed content of Python implements Alipay's face-to-face payment (scan code payment) function. For more information, please follow other related articles on the PHP Chinese website!