准备
由于正式环境需要商户信息,所以这里使用支付宝提供的沙箱环境。切换到正式环境后只需稍改配置。
1、点击进入蚂蚁金服平台官网。
2、如下图选择:开发者中心->开发服务下的研发服务->沙箱。
生成RSA秘钥
下载秘钥生成工具:
解压后目录如下:
双击验签工具,打开后直接点击生成秘钥:
此时验签工具目录下会生成 RSA秘钥
文件夹:
目录如下:
设置应用公钥
直接将上一步生成的 公钥2048
内容贴入保存:
设置完之后会生成 查看支付宝公钥
按钮:
支付宝公钥会在设置应用公钥后自动生成,无需手动设置:
使用
安装依赖
$ pip install pycryptodome
引入帮助类 AliPay
// /utils/pay.py
from datetime import datetime
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA256
from urllib.parse import quote_plus
from urllib.parse import urlparse, parse_qs
from base64 import decodebytes, encodebytes
import json
class AliPay(object):
"""
支付宝支付接口(PC端支付接口)
"""
def __init__(self, appid, app_notify_url, app_private_key_path,
alipay_public_key_path, return_url, debug=False):
self.appid = appid
self.app_notify_url = app_notify_url
self.app_private_key_path = app_private_key_path
self.app_private_key = None
self.return_url = return_url
with open(self.app_private_key_path) as fp:
self.app_private_key = RSA.importKey(fp.read())
self.alipay_public_key_path = alipay_public_key_path
with open(self.alipay_public_key_path) as fp:
self.alipay_public_key = RSA.importKey(fp.read())
if debug is True:
self.__gateway = "https://openapi.alipaydev.com/gateway.do"
else:
self.__gateway = "https://openapi.alipay.com/gateway.do"
def direct_pay(self, subject, out_trade_no, total_amount, return_url=None, **kwargs):
biz_content = {
"subject": subject,
"out_trade_no": out_trade_no,
"total_amount": total_amount,
"product_code": "FAST_INSTANT_TRADE_PAY",
# "qr_pay_mode":4
}
biz_content.update(kwargs)
data = self.build_body("alipay.trade.page.pay", biz_content, self.return_url)
return self.sign_data(data)
def build_body(self, method, biz_content, return_url=None):
data = {
"app_id": self.appid,
"method": method,
"charset": "utf-8",
"sign_type": "RSA2",
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"version": "1.0",
"biz_content": biz_content
}
if return_url is not None:
data["notify_url"] = self.app_notify_url
data["return_url"] = self.return_url
return data
def sign_data(self, data):
data.pop("sign", None)
# 排序后的字符串
unsigned_items = self.ordered_data(data)
unsigned_string = "&".join("{0}={1}".format(k, v) for k, v in unsigned_items)
sign = self.sign(unsigned_string.encode("utf-8"))
# ordered_items = self.ordered_data(data)
quoted_string = "&".join("{0}={1}".format(k, quote_plus(v)) for k, v in unsigned_items)
# 获得最终的订单信息字符串
signed_string = quoted_string + "&sign=" + quote_plus(sign)
return signed_string
def ordered_data(self, data):
complex_keys = []
for key, value in data.items():
if isinstance(value, dict):
complex_keys.append(key)
# 将字典类型的数据dump出来
for key in complex_keys:
data[key] = json.dumps(data[key], separators=(',', ':'))
return sorted([(k, v) for k, v in data.items()])
def sign(self, unsigned_string):
# 开始计算签名
key = self.app_private_key
signer = PKCS1_v1_5.new(key)
signature = signer.sign(SHA256.new(unsigned_string))
# base64 编码,转换为unicode表示并移除回车
sign = encodebytes(signature).decode("utf8").replace("\n", "")
return sign
def _verify(self, raw_content, signature):
# 开始计算签名
key = self.alipay_public_key
signer = PKCS1_v1_5.new(key)
digest = SHA256.new()
digest.update(raw_content.encode("utf8"))
if signer.verify(digest, decodebytes(signature.encode("utf8"))):
return True
return False
def verify(self, data, signature):
if "sign_type" in data:
sign_type = data.pop("sign_type")
# 排序后的字符串
unsigned_items = self.ordered_data(data)
message = "&".join(u"{}={}".format(k, v) for k, v in unsigned_items)
return self._verify(message, signature)
配置秘钥
/keys/app_private_2048.txt
:
-----BEGIN RSA PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCln7XrQxciEcJiLSgBQYiLLmDo8ES6osoZg6/o67JnsRutyxPVDvdmlSRh4+BKisdUuj54uHUYKH99oXnv7P+OMQu6oNbyo82UdJSOT2wSh+jjSPUqpZrHZEmABs380xD3okD6L312IZDMP4GcjA1b06kug2m6uFi4Dh2VVvts/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g2uu1JJtsnLnvbF5gJJixVg53rbtKHtL/gXm5RE5xcBk36g4HeJ5aG64P2nyvFSvtpZuBZJvqLksRVgocHjxcJvCq4Jj+SAA8ybpWc+0A6YnQerpkW/AHkpVQlLBJzknjwH51yPyk2L425LAoGBAIYel91QaxEXcVZ7dqZ0+wGixocB2p0Tj2RYqOH3tEdNjqHBAZWTGPlSaPzhlNdNdqYUZAvNe+NbpTVUzr/EVBEb6iLK6lylJDgPVXh20wPKFaZhG4cEjdeMlYXrvzif0lDnGPz4ynRqyqsVBzq8rJazH+2G01p8awuHLzJpJnlv
-----END RSA PRIVATE KEY-----
/keys/alipay_public_2048.txt
:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwrww6DyKMamYkFEH+KWoMmXW9UOmFB63XZuYlENz3ijgIeA1eGV4t7NhTb7gtwcRWXG1octr2xaAtOLaaS9cBuRm6Esd5JYVp7+k6bt4oWO88ghLs2rNyQstW7OXqtrflCAUrqXYdEWpcXOZZALDIgLW/xFfXTYI2PvKZlUaKYCNVMoM1Ed0TqakJ7B1ZhLfQWy++Z8ZJ0MrFEpEv2XQ8NO2GuAD7KHVj6HaQ+1Mbvq9D4VhVrWNvgKSftom1VjsaxSkdWZr6AqVq/GOyZw/Dov24ggyMHIZ7aQKlVN52MYIiD57E55D1UJ66edMdofTivdlsqFUZ8Q9ylRTAMJJhwIDAQAB
-----END PUBLIC KEY-----
注意:这两个文件中的头和尾标识符不可缺少,中间是生成的 key。
// settings.py
APPID = "2016092300580728"
NOTIFY_URL = "http://.../update_order/"
# 上面这个地址应该是在公网能够访问到的地址,否则接收不到支付宝的回调。
RETURN_URL = "http://.../pay_result/"
PRI_KEY_PATH = "keys/app_private_2048.txt"
PUB_KEY_PATH = "keys/alipay_public_2048.txt"
AliPay 的实例化参数
def aliPay():
obj = AliPay(
appid=settings.APPID, # 沙箱环境->沙箱应用 提供的APPID 我这里是 2016092300580728
app_notify_url=settings.NOTIFY_URL, # 如果支付成功,支付宝会向这个地址发送POST请求(校验是否支付已经完成)
return_url=settings.RETURN_URL, # 如果支付成功,重定向回到你的网站的地址。
alipay_public_key_path=settings.PUB_KEY_PATH, # 支付宝公钥
app_private_key_path=settings.PRI_KEY_PATH, # 应用私钥
debug=True, # 默认False,
)
return obj
加密并生成 URL
def index(request):
if request.method == 'GET':
return render(request, 'index.html')
alipay = aliPay()
# 对购买的数据进行加密
money = float(request.POST.get('price'))
out_trade_no = "x2" + str(time.time())
# 1. 在数据库创建一条数据:状态(待支付)
query_params = alipay.direct_pay(
subject="充气式娃娃", # 商品简单描述
out_trade_no=out_trade_no, # 商户订单号
total_amount=money, # 交易金额(单位: 元 保留俩位小数)
)
pay_url = "https://openapi.alipaydev.com/gateway.do?{}".format(query_params)
return redirect(pay_url)
重定向到生成的 URL 后,支付宝方会根据 URL 携带的参数解密展示信息如下:
回调
支付成功后支付宝会向我们指定的地址发送 POST 请求,我们可以在此回调中进行逻辑处理:
@csrf_exempt
def update_order(request):
if request.method == 'POST':
from urllib.parse import parse_qs
body_str = request.body.decode('utf-8')
post_data = parse_qs(body_str)
post_dict = {}
for k, v in post_data.items():
post_dict[k] = v[0]
alipay = aliPay()
sign = post_dict.pop('sign', None)
status = alipay.verify(post_dict, sign)
if status:
# 1. 获取订单号
out_trade_no = post_dict.get('out_trade_no')
print(out_trade_no)
# 2. 根据订单号将数据库中的数据进行更新
return HttpResponse('success')
else:
return HttpResponse('fail')
return HttpResponse('')
校验是否成功
def pay_result(request):
"""
支付完成后,跳转回的地址
:param request:
:return:
"""
params = request.GET.dict()
sign = params.pop('sign', None)
alipay = aliPay()
# 校验支付是否成功
status = alipay.verify(params, sign)
if status:
return HttpResponse('支付成功')
return HttpResponse('支付失败')
评论区