Django调用支付宝接口代码实例详解
作者:zack_赵康 时间:2023-07-19 10:53:51
支付宝支付
正式环境:用营业执照,申请商户号,appid
测试环境:沙箱环境:https://openhome.alipay.com/platform/appDaily.htm?tab=info
支付宝提供接口:给商户使用,收钱
-Java,php,C#的demo,没有python的demo
-git有人封装了
-需要安装模块:pip3 install
-应用私钥---自己保存,一定不能丢
-应用公钥---给别人用
-支付宝公钥---支付宝用的
-生成公钥私钥:https://docs.open.alipay.com/291/105971
-把应用公钥配置在支付宝上:应用公钥,配置完成以后,支付宝自动生成一个支付宝公钥
-在程序中:配置应用私钥,支付宝公钥
-如果支付成功,支付宝会回调,但是如果你的服务器挂掉了怎么办?
-支付宝24小时以内不定时再给你发,你修改掉订单状态即可
-支付成功,支付宝会有一个get回调,一个post回调:修改订单状态
支付宝接口
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 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 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 = "2016092000554611"
# 支付宝收到用户的支付,会向商户发两个请求,一个get请求,一个post请求
# POST请求,用于最后的检测
notify_url = "http://42.56.89.12:80/page2/"
# GET请求,用于页面的跳转展示
return_url = "http://42.56.89.12:80/page2/"
merchant_private_key_path = "keys/app_private_2048.txt"
alipay_public_key_path = "keys/alipay_public_2048.txt"
# 生成一个AliPay的对象
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 page1(request):
if request.method == "GET":
return render(request, 'page1.html')
else:
money = float(request.POST.get('money'))
# 生成一个对象
alipay = ali()
# 生成支付的url
# 对象调用direct_pay
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)
print(pay_url)
# 朝这个地址发get请求
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')
print(body_str)
post_data = parse_qs(body_str)
print('支付宝给我的数据:::---------',post_data)
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('支付成功')
来源:https://www.cnblogs.com/ZKPython/p/11167710.html
标签:Django,支付宝,接口
0
投稿
猜你喜欢
Python实现句子翻译功能
2023-11-20 20:07:28
python之mock模块基本使用方法详解
2022-03-05 03:10:33
Bootstrap基本插件学习笔记之轮播幻灯片(23)
2024-04-19 10:13:30
详细解读tornado协程(coroutine)原理
2022-08-21 00:20:18
详解Mysql基础语法的使用
2024-01-28 07:50:05
Postman使用详解
2023-09-03 05:59:36
python 自动提交和抓取网页
2022-11-16 17:47:01
解析Vue2.0双向绑定实现原理
2024-06-05 15:29:32
python爬虫判断招聘信息是否存在的实例代码
2022-09-14 20:38:04
对Python3 解析html的几种操作方式小结
2021-04-07 20:13:12
golang 防缓存击穿singleflight的实现
2024-05-09 09:55:23
Python用zip函数同时遍历多个迭代器示例详解
2023-09-28 06:09:41
ASP导出Excel数据的四种办法
2007-08-26 18:32:00
教你利用pygame模块制作跳跃小球小游戏
2022-02-07 11:28:46
一篇文章掌握MySQL的索引查询优化技巧
2024-01-17 22:19:29
深入浅出SQL教程之SELECT语句的自连接
2009-08-30 15:17:00
为google量身定做的sitemap生成代码asp版
2011-04-06 10:43:00
利用 Python 实现多任务进程
2023-12-19 02:53:52
SQL Server中TRUNCATE事务回滚操作方法
2024-01-20 14:43:23
python 获取sqlite3数据库的表名和表字段名的实例
2024-01-24 13:34:22