准备工作:
1.银联技术开放平台注册:https://open.unionpay.com/tjweb/acproduct/list?apiservId=448
2.点击网关支付 --> 我要测试 (按照提示下载密钥)
3.安装需要的模块 pip install pyOpenSSL
代码实现:
目录结构
pay.py 文件
import xxx # 自行导入
class UnionPay:
"""
银联支付接口(PC端)
"""
def __init__(
self,
version,
mer_id,
front_url,
back_url,
backend_url,
cert_path,
debug=False
):
self.version = version
self.mer_id = mer_id
self.front_url = front_url
self.back_url = back_url
self.backend_url = backend_url
self.cert = {
}
self.cert_id = self.__get_cert_id(cert_path)
if debug is True:
# 支付网关
self.gateway = "https://gateway.test.95516.com/gateway/api/frontTransReq.do"
# 查询网关
self.query_gateway = "https://gateway.test.95516.com/gateway/api/queryTrans.do"
else:
self.gateway = "https://gateway.95516.com/gateway/api/frontTransReq.do"
self.query_gateway = "https://gateway.95516.com/gateway/api/queryTrans.do"
def build_request_data(self, order_id, txn_amt, **kwargs):
"""
构建请求数据
:param order_id: 商户订单号
:param txn_amt: 交易金额(单位: 分)
:return:
"""
request_data = {
"version": self.version, # 版本
"encoding": "utf-8", # 编码
"txnType": "01", # 交易类型 01:消费
"txnSubType": "01", # 交易子类 01:自助消费
"bizType": "000201", # 产品类型 000201:B2C网关支付
"frontUrl": self.front_url, # 前台通知地址
"backUrl": self.back_url, # 后台通知地址 需外网
"signMethod": "01", # 签名方法 01:RSA签名
"channelType": "07", # 渠道类型 07:互联网
"accessType": "0", # 接入类型 0:普通商户直连接入
"currencyCode": "156", # 交易币种 156:人民币
"merId": self.mer_id, # 商户代码
"txnAmt": txn_amt, # 订单金额(单位: 分)
"txnTime": datetime.now().strftime("%Y%m%d%H%M%S"), # 订单发送时间
"certId": self.cert_id,
"orderId": order_id,
"signature": ""
}
request_data.update(**kwargs)
self.get_sign(request_data)
return request_data
def pay_url(self, request_data):
payment_url = "{}?{}".format(self.backend_url, parse.urlencode<