项目演示:

1、输入金额

2、扫码支付:

3、支付完成:

4.跳转回商户

一、注册账号

https://openhome.alipay.com/platform/appDaily.htm?tab=info

二、设置应用公钥

三、代码实现

1、项目结构:

2、把生成的     应用私钥     和    支付宝的公钥       放入keys目录下:

注意:
支付宝公钥
商户私钥

但是要做修改:

alipay_public_2048.txt
-----BEGIN PUBLIC KEY----- # 加上这行
支付宝的公钥
-----END PUBLIC KEY----- # 同上 app_private_2048.txt
-----BEGIN PUBLIC KEY----- #同上
应用的私钥
-----END PUBLIC KEY----- # 同上

3、pay.py 这是从git上找到的支付宝支付接口(PC端支付接口)

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)
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)

3、路由设置

from django.conf.urls import url
from django.contrib import admin
from app01 import views urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^page1/', views.page1),
url(r'^index/', views.index),
url(r'^page2/', views.page2),
]
from django.conf.urls import url
from django.contrib import admin
from app01 import views urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^page1/', views.page1),
url(r'^index/', views.index),
url(r'^page2/', views.page2),
]

4、视图设置

from django.shortcuts import render, redirect, HttpResponse
from utils.pay import AliPay
import json
import time def ali():
# 沙箱环境地址:https://openhome.alipay.com/platform/appDaily.htm?tab=info
app_id = "2016091100487127"
# POST请求,用于最后的检测
notify_url = "http://127.0.0.1:8002/page2"
# notify_url = "http://www.wupeiqi.com:8804/page2/" # GET请求,用于页面的跳转展示
return_url ="http://127.0.0.1:8002/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,
)
return alipay def index(request):
return render(request,'index.html')
def page1(request):
if request.method == "GET":
return render(request, 'page1.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?{0}".format(query_params) return redirect(pay_url) def page2(request):
alipay = ali()
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]
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('支付成功')
from django.shortcuts import render, redirect, HttpResponse
from utils.pay import AliPay
import json
import time def ali():
# 沙箱环境地址:https://openhome.alipay.com/platform/appDaily.htm?tab=info
app_id = "2016091100487127"
# POST请求,用于最后的检测
notify_url = "http://127.0.0.1:8002/page2"
# notify_url = "http://www.wupeiqi.com:8804/page2/" # GET请求,用于页面的跳转展示
return_url ="http://127.0.0.1:8002/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,
)
return alipay def index(request):
return render(request,'index.html')
def page1(request):
if request.method == "GET":
return render(request, 'page1.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?{0}".format(query_params) return redirect(pay_url) def page2(request):
alipay = ali()
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]
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('支付成功')

5、模板

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="dist/css/bootstrap.css">
</head>
<body>
<form action="/page1/" method="POST">
{% csrf_token %}
<input type="text" name="money">
<input type="submit" value="去支付" />
</form>
<script></script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="dist/css/bootstrap.css">
</head>
<body>
<form action="/page1/" method="POST">
{% csrf_token %}
<input type="text" name="money">
<input type="submit" value="去支付" />
</form>
<script></script>
</body>
</html>

6.  Crypto 模块 的处理

python-支付宝支付示例的更多相关文章

  1. 支付宝支付示例-python

    项目演示: 1.输入金额 ​ 2.扫码支付: ​ 3.支付完成: ​ ​ 具体操作步骤: 第一步:注册账号 https://openhome.alipay.com/platform/appDaily. ...

  2. python调用支付宝支付接口详细示例—附带Django demo代码

    项目演示: 一.输入金额 二.跳转到支付宝付款 三.支付成功 四.跳转回自己网站 在使用支付宝接口的前期准备: 1.支付宝公钥 2.应用公钥 3.应用私钥 4.APPID 5.Django 1.11. ...

  3. python调用支付宝支付接口

    python调用支付宝支付接口详细示例—附带Django demo代码   项目演示: 一.输入金额 二.跳转到支付宝付款 三.支付成功 四.跳转回自己网站 在使用支付宝接口的前期准备: 1.支付宝公 ...

  4. Python支付宝在线支付API

    一.蚂蚁金服开发平台申请测试账号 a. 登陆蚂蚁金服开放平台https://open.alipay.com/platform/manageHome.htm,在“开发中心”—“研发服务”下拉处选择沙箱作 ...

  5. python 全栈开发,Day102(支付宝支付)

    昨日内容回顾 1. django请求生命周期? - 当用户在浏览器中输入url时,浏览器会生成请求头和请求体发给服务端 请求头和请求体中会包含浏览器的动作(action),这个动作通常为get或者po ...

  6. Python对接支付宝支付自实现

    Python对接支付宝支付自实现 # -*- coding: utf-8 -*- import base64 import json import urllib.parse from datetime ...

  7. python支付宝页面扫码支付

    一.介绍 基于网上一个支付宝pay.py封装了支付宝API的文件进行的,以下代码只支持网页扫码支付,手机端会提示调用支付宝支付 #pay文件代码 from datetime import dateti ...

  8. 前后端分离djangorestframework—— 接入支付宝支付平台

    支付宝 简介 支付宝是什么不用多说了,本次教程适合初学者 前提准备 话不多说,干就完了 1.注册开发者账号,设置公钥私钥 首先进入支付宝开发者平台:传送门 ,有账号直接登录,没账号用你平时用来付款收钱 ...

  9. iOS - AliPay 支付宝支付

    1.支付宝支付申请 支付宝支付官方签约集成指引 支付宝APP支付官方集成指引 蚂蚁金服开放平台 1.1 支付宝 APP 支付申请步骤 APP 支付:APP 支付是商户通过在移动端应用 APP 中集成开 ...

  10. 李洪强iOS开发支付集成之支付宝支付

    iOS开发支付集成之支付宝支付 下载支付宝SDK 首先是开发包下载,还是比较难发现的,网上以前文章中的链接都打不开,我找了好久才找到的.最新的地址在这里(注意的是下载出来的SDK包里面并没有传说中的开 ...

随机推荐

  1. __x__(20)0907第四天__列表ul,ol,dl

    列表分为: 有序列表 ul: <ul type="disc"> <li>张三</li> <li>李四</li> < ...

  2. react_app 项目开发 (6)_后台服务器端-node

    后台服务器端 负责处理前台应用提交的请求,并向前台返回 json 数据 前台应用 负责 展现数据与用户交互 发 ajax 请求与后台应用交互 yarn add axios /src/api/ajax. ...

  3. [Codeforces Round #438][Codeforces 868D. Huge Strings]

    题目链接:868D - Huge Strings 题目大意:有\(n\)个字符串,\(m\)次操作,每次操作把两个字符串拼在一起,并询问这个新串的价值.定义一个新串的价值\(k\)为:最大的\(k\) ...

  4. cmd 命令 net start mongodb 启动不了,提示 net 不是内部命令或者外部命令

    1.要管理员的身份进入 cmd 2.右击我的电脑-->属性-->高级系统设置 3.选择高级-->环境变量 4.找到系统变量-->Path-->编辑 5.把 C:\wind ...

  5. 日期求星期(java)-蓝桥杯

    日期求星期问题(java)-蓝桥杯 1:基姆拉尔森计算公式(计算星期) 公式: int week = (d+2*m+3*(m+1)/5+y+y/4-y/100+y/400)%7; 此处y,m,d指代年 ...

  6. jquery 实现tab切换

    大家都知道 使用QQ的时候需要输入账号和密码 这个时候一个TAB键盘就可以实现切换到下一个输入框里 具体是怎么实现的呢 请看代码 <!DOCTYPE html> <html lang ...

  7. ST表 || RMQ问题 || BZOJ 1699: [Usaco2007 Jan]Balanced Lineup排队 || Luogu P2880 [USACO07JAN]平衡的阵容Balanced Lineup

    题面:P2880 [USACO07JAN]平衡的阵容Balanced Lineup 题解: ST表板子 代码: #include<cstdio> #include<cstring&g ...

  8. 数据结构day1:排序

    1,冒泡排序算法的python实现 def bubble_sort(alist): pass count = len(alist)-1 for index in range(count,0,-1): ...

  9. nodejs 使用superagent+cheerio+eventproxy爬取豆瓣帖子

    //cnpm install superagent cheerio eventproxy fs pathvar superagent = require('superagent'); var chee ...

  10. oracle根据某个字段的值进行排序

    需求:按照颜色为蓝色.红色.黄色进行排序: order by  case                  when color = '蓝色' then                   1     ...