原版代码在git–hub上,是基于flask的,django项目下会报ASE错误,原因是字返回额字典里面是列表类型的数据,修改和摘抄修改部分如下:
地址:https://github.com/fzlee/alipay/blob/master/README.zh-hans.md
原版通知验证
这里有一个简单的基于flask的验证:
from flask import Flask
from flask import request
app = Flask(__name__)
@app.route('/', methods=["GET", "POST"])
def hello_world():
data = request.form.to_dict()
# sign 不能参与签名验证
signature = data.pop("sign")
print(json.dumps(data))
print(signature)
# verify
success = alipay.verify(data, signature)
if success and data["trade_status"] in ("TRADE_SUCCESS", "TRADE_FINISHED" ):
print("trade succeed")
修改如下:
项目地址(还没做完) :https://gitee.com/muzhe1024/meiduo_mall/commits/muzhe
class AlipayValidView(APIView):
def put(self, request):
# 1.接收支付宝返回的数据,转字典
dict1 = dict(request.query_params)
dict2 = {}
for key, value in dict1.items():
dict2[key] = value[0]
# 2.弹出sign
signature = dict2.pop('sign')
# 3.创建alipay对象
alipay = AliPay(
appid=settings.ALIPAY_APPID,
app_notify_url=None,
app_private_key_path=os.path.join(settings.ALIPAY_KEY_PATH, 'app_private_key.pem'),
alipay_public_key_path=os.path.join(settings.ALIPAY_KEY_PATH, 'alipay_public_key.pem'),
debug=settings.ALIPAY_DEBUG
)
# 4.调用verify方法,进行验证
sign_type = dict1.pop("sign_type")
# print(sign_type)
# return Response('ok')
success = alipay.verify(dict2, signature)
# 5.判断是否支付成功
if success:
# 6.如果支付成功则
# 6.1修改订单状态
order = OrderInfo.objects.get(pk=dict2.get('out_trade_no'))
order.status = 2
order.save()
# 6.2保存流水号
payment = Payment.objects.create(
order=order,
trade_id=dict2.get('trade_no')
)
# 6.3返回流水号
return Response({
'trade_id': dict2.get('trade_no')
})
else:
return Response({'message': '支付失败'})