1.项目展示:
2.扫码支付
3.支付完成
4.跳转成功
一、注册账号
https://openhome.alipay.com/platform/appDaily.htm?tab=info
二、设置应用公钥
私钥需要复制到程序里的:
程序里面阿里的公钥在这里获取:
、
这里放的是阿里的公钥。
代码实现:
代码结构:
1. 首先是:更改程序里面的阿里公钥和用户私钥以及app_id
2.pay.py 这是从git上找到的支付宝支付接口(PC端支付接口)
3、
1 from datetime importdatetime2 from Crypto.PublicKey importRSA3 from Crypto.Signature importPKCS1_v1_54 from Crypto.Hash importSHA2565 from urllib.parse importquote_plus6 from urllib.parse importurlparse, parse_qs7 from base64 importdecodebytes, encodebytes8 importjson9
10 classAliPay(object):11 """
12 支付宝支付接口(PC端支付接口)13 """
14
15 def __init__(self, appid, app_notify_url, app_private_key_path,16 alipay_public_key_path, return_url, debug=False):17 self.appid =appid18 self.app_notify_url =app_notify_url19 self.app_private_key_path =app_private_key_path20 self.app_private_key =None21 self.return_url =return_url22 with open(self.app_private_key_path) as fp:23 self.app_private_key =RSA.importKey(fp.read())24 self.alipay_public_key_path =alipay_public_key_path25 with open(self.alipay_public_key_path) as fp:26 self.alipay_public_key =RSA.importKey(fp.read())27
28 if debug isTrue:29 self.__gateway = "https://openapi.alipaydev.com/gateway.do"
30 else:31 self.__gateway = "https://openapi.alipay.com/gateway.do"
32
33 def direct_pay(self, subject, out_trade_no, total_amount, return_url=None, **kwargs):34 biz_content ={35 "subject": subject,36 "out_trade_no": out_trade_no,37 "total_amount": total_amount,38 "product_code": "FAST_INSTANT_TRADE_PAY",39 #"qr_pay_mode":4
40 }41
42 biz_content.update(kwargs)43 data = self.build_body("alipay.trade.page.pay", biz_content, self.return_url)44 returnself.sign_data(data)45
46 def build_body(self, method, biz_content, return_url=None):47 data ={48 "app_id": self.appid,49 "method": method,50 "charset": "utf-8",51 "sign_type": "RSA2",52 "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),53 "version": "1.0",54 "biz_content": biz_content55 }56
57 if return_url is notNone:58 data["notify_url"] =self.app_notify_url59 data["return_url"] =self.return_url60
61 returndata62
63 defsign_data(self, data):64 data.pop("sign", None)65 #排序后的字符串
66 unsigned_items =self.ordered_data(data)67 unsigned_string = "&".join("{0}={1}".format(k, v) for k, v inunsigned_items)68 sign = self.sign(unsigned_string.encode("utf-8"))69 #ordered_items = self.ordered_data(data)
70 quoted_string = "&".join("{0}={1}".format(k, quote_plus(v)) for k, v inunsigned_items)71
72 #获得最终的订单信息字符串
73 signed_string = quoted_string + "&sign=" +quote_plus(sign)74 returnsigned_string75
76 defordered_data(self, data):77 complex_keys =[]78 for key, value indata.items():79 ifisinstance(value, dict):80 complex_keys.append(key)81
82 #将字典类型的数据dump出来
83 for key incomplex_keys:84 data[key] = json.dumps(data[key], separators=(',', ':'))85
86 return sorted([(k, v) for k, v indata.items()])87
88 defsign(self, unsigned_string):89 #开始计算签名
90 key =self.app_private_key91 signer =PKCS1_v1_5.new(key)92 signature =signer.sign(SHA256.new(unsigned_string))93 #base64 编码,转换为unicode表示并移除回车
94 sign = encodebytes(signature).decode("utf8").replace("\n", "")95 returnsign96
97 def_verify(self, raw_content, signature):98 #开始计算签名
99 key =self.alipay_public_key100 signer =PKCS1_v1_5.new(key)101 digest =SHA256.new()102 digest.update(raw_content.encode("utf8"))103 if signer.verify(digest, decodebytes(signature.encode("utf8"))):104 returnTrue105 returnFalse106
107 defverify(self, data, signature):108 if "sign_type" indata:109 sign_type = data.pop("sign_type")110 #排序后的字符串
111 unsigned_items =self.ordered_data(data)112 message = "&".join(u"{}={}".format(k, v) for k, v inunsigned_items)113 return self._verify(message, signature)
支付函数
4.路由设置:
from django.conf.urls importurlfrom django.contrib importadminfrom app01 importviews
urlpatterns=[
url(r'^admin/', admin.site.urls),
url(r'^page1/', views.page1),
url(r'^index/', views.index),
url(r'^page2/', views.page2),
]
5.视图:
from django.shortcuts importrender, redirect, HttpResponsefrom utils.pay importAliPayimportjsonimporttimedefali():#沙箱环境地址:https://openhome.alipay.com/platform/appDaily.htm?tab=info
app_id = "2016091100483151"
#POST请求,用于最后的检测
notify_url = "http://127.0.0.1:8804/page2/"
#notify_url = "http://www.wupeiqi.com:8804/page2/"
#GET请求,用于页面的跳转展示
return_url = "http://127.0.0.1:8804/page2/"
#return_url = "http://www.wupeiqi.com:8804/page2/"
merchant_private_key_path= "keys/app_private_2048.txt"alipay_public_key_path= "keys/alipay_public_2048.txt"alipay=AliPay(
appid=app_id,
app_notify_url=notify_url,
return_url=return_url,
app_private_key_path=merchant_private_key_path,
alipay_public_key_path=alipay_public_key_path, #支付宝的公钥,验证支付宝回传消息使用,不是你自己的公钥
debug=True, #默认False,
)returnalipaydefindex(request):return render(request,'index.html')defpage1(request):if request.method == "GET":return render(request, 'index.html')else:
money= float(request.POST.get('money'))
alipay=ali()#生成支付的url
query_params =alipay.direct_pay(
subject="充气式韩红", #商品简单描述
out_trade_no="x2" + str(time.time()), #商户订单号
total_amount=money, #交易金额(单位: 元 保留俩位小数)
)
pay_url= "https://openapi.alipaydev.com/gateway.do?{}".format(query_params)returnredirect(pay_url)defpage2(request):
alipay=ali()if request.method == "POST":#检测是否支付成功
#去请求体中获取所有返回的数据:状态/订单号
from urllib.parse importparse_qs
body_str= request.body.decode('utf-8')
post_data=parse_qs(body_str)
post_dict={}for k, v inpost_data.items():
post_dict[k]=v[0]print(post_dict)
sign= post_dict.pop('sign', None)
status=alipay.verify(post_dict, sign)print('POST验证', status)return HttpResponse('POST返回')else:
params=request.GET.dict()
sign= params.pop('sign', None)
status=alipay.verify(params, sign)print('GET验证', status)return HttpResponse('支付成功')
6.模板
Title{% csrf_token %}注意:安装Crypto
把安装包放到C:\Users\frank\AppData\Local\Programs\Python\Python36\Lib\site-packages 然后解压缩就行了。
https://blog.csdn.net/sc_lilei/article/details/80450859