django中支付宝(沙箱)简单使用
python=3.6.8
django=2.1.8
python-alipay-sdk=2.0.1
非官方支付宝 Python SDK: https://github.com/fzlee/alipay/blob/master/README.zh-hans.md#alipay.trade.page.pay
沙箱环境配置
1、在支付宝开放平台---->开发者中心—>开发服务---->沙箱
2、RSA2密钥生成并上传
参考官方地址:https://opendocs.alipay.com/open/291/105971
新版的生成密钥工具为.exe文件,下载完成以后,请自行安装,安装好以后,桌面自动生成图标
运行支付宝开放平台开发助手
获取支付宝公钥
django中使用alipay
alipay公钥和app私钥在django中存放行式
alipay公钥
app私钥
models.py
from django.db import models
# Create your models here.
class Goods(models.Model):
goods_name = models.CharField(max_length=32)
goods_price = models.FloatField()
class Order(models.Model):
order_number = models.CharField(max_length=64)
status_choices = ((0, '未支付'), (1, '已支付'))
order_status = models.IntegerField(choices=status_choices, default=0)
goods = models.ForeignKey(to='Goods', on_delete=models.CASCADE)
views.py
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.views import View
from django.conf import settings
from .models import *
import uuid
from alipay import AliPay
# Create your views here.
class GoodsView(View):
def get(self, request):
goods_list = Goods.objects.all()
return render(request, 'day03/goods.html', {'goods_list': goods_list})
# 读取支付宝沙箱私钥
with open(settings.BASE_DIR + '\\day03\\keys\\private_key.txt') as f:
app_private_key_string = f.read()
# 读取支付宝沙箱公钥
with open(settings.BASE_DIR + '\\day03\\keys\\alipy_public_key.txt') as ff:
alipay_public_key_string = ff.read()
# 实例化对象
alipay_pay = AliPay(
appid="2016101000652297",
app_notify_url=None, # 默认回调url
app_private_key_string=app_private_key_string,
# 支付宝的公钥,验证支付宝回传消息使用,不是你自己的公钥,
alipay_public_key_string=alipay_public_key_string,
sign_type="RSA2", # RSA 或者 RSA2
debug=True, # 默认False
)
class PaymentView(View):
def get(self, request, goods_id):
# 获取商品信息,因为向支付宝接口发送请求的时候需要携带该商品相关信息
obj_goods = Goods.objects.get(pk=goods_id) # pk就是商品的标识,等价于使用id
# 生成订单
order_number = str(uuid.uuid4())
# 把生成的订单号关联商品,并写入数据库
Order.objects.create(order_number=order_number, goods=obj_goods)
# 定义请求地址传入的参数
print(alipay_pay)
query_params = alipay_pay.api_alipay_trade_page_pay(
subject=obj_goods.goods_name, # 商品的简单描述
out_trade_no=order_number, # 商品订单号
total_amount=obj_goods.goods_price, # 交易金额(单位是元,保留两位小数)
return_url="http://127.0.01:8000/day03/check_order/", # 支付成功后回调地址
)
# 需要跳转到支付宝的支付页面,所以需要生成跳转的url
pay_url = 'https://openapi.alipaydev.com/gateway.do?{}'.format(query_params)
return redirect(pay_url)
class CheckPayView(View):
def get(self, request):
print(request.GET.dict())
data = request.GET.dict()
signtrue = data.pop('sign')
print(signtrue)
success = alipay_pay.verify(data, signtrue)
print(success)
if success:
print("支付成功")
else:
print("支付失败")
return HttpResponse("OK")
urls.py
from django.urls import path
from . import views
app_name = 'day03'
urlpatterns = [
path('goods/', views.GoodsView.as_view(), name='goods'), # 展示商品
path('purchase/<goods_id>', views.PaymentView.as_view(), name='purchase'), # 展示商品
path('check_order/', views.CheckPayView.as_view(), name='check_order'), # 展示商品
]
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>商品信息</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row" style="margin-top: 10px">
<h4 style="text-align: center;font-weight: bold">Django支付宝支付案例</h4>
</div>
<div class="row" style="margin-top: 10px">
<div class="col-md-4 col-md-offset-4">
<table class="table table-bordered">
{% for row in goods_list %}
<tr style="text-align: center">
<td>{{ row.id }}</td>
<td>{{ row.goods_name }}</td>
<td>{{ row.goods_price }}</td>
<td><a href="{% url 'day03:purchase' row.id %}">购买</a></td>
</tr>
{% endfor %}
</table>
</div>
</div>
</div>
</body>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
crossorigin="anonymous"></script>
</html>