Django支付宝(沙箱)后端接口
Django支付宝(沙箱)后端接口
点击查看初始化沙箱配置(https://blog.csdn.net/weixin_45954124/article/details/109583431)
-
创建app 仅供参考 你需要自己创建相应的表(model)
-
app\model
-
# Create your models here. from django.db import models from utils.MyBaseModel import Base class Goods(Base): GOODS_TYPE = ( ('1', 'Vip'), ('2', 'Course') ) CHANNEL_TYPE = ( ('1', '普通'), ('2', '促销') ) course = models.ForeignKey('course.Course', on_delete=models.PROTECT) goods_type = models.CharField('商品种类', choices=GOODS_TYPE, max_length=8) product_id = models.CharField('产品id', max_length=8) title = models.CharField('商品名称', max_length=24) price = models.DecimalField('商品价格', max_digits=8, decimal_places=2) channel_type = models.CharField('购买渠道', choices=CHANNEL_TYPE, max_length=8) period = models.IntegerField('有效期', default=365) is_launched = models.BooleanField('是否上架', default=True) class Meta: db_table = 'tb_goods' def __str__(self): return self.title class Orders(Base): PAY_METHOD = ( (1, "支付宝"), ) ORDER_STATUS = ( (1, "待支付"), (2, "已支付"), (3, "已取消"), ) user = models.ForeignKey('user.User', on_delete=models.PROTECT, verbose_name="下单用户") goods = models.ForeignKey(Goods, on_delete=models.PROTECT) order_id = models.CharField('订单号', max_length=24) trade_no = models.CharField('支付宝订单号', max_length=32, null=True) # 28位 pay_time = models.DateTimeField('支付时间', null=True) pay_method = models.CharField('支付方式', choices=PAY_METHOD, default=1, max_length=8) status = models.CharField('支付状态', choices=ORDER_STATUS, default=1, max_length=8) total_amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="商品总金额") class Meta: db_table = 'tb_orders' def __str__(self): return self.order_id
-
-
app\view
-
# Create your views here. from decimal import Decimal import redis from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView from .models import Goods, Orders from syl import settings from .utils import out_trade_no # 绝对路径打开文件 {}代表从这里往前 # 支付 from syl.settings import alipay from course.models import UserCourse class PayUrlView(APIView): permission_classes = (IsAuthenticated,) def post(self, request): print(request.data) goods_obj = Goods.objects.get(pk=request.data.get("goods_id")) user = request.user out_trade = out_trade_no() print(out_trade_no) if user.vip.vip_type == '1': price = goods_obj.price * Decimal('0.80').quantize(Decimal('0.00')) elif user.vip.vip_type == '2': price = goods_obj.price * Decimal('0.60').quantize(Decimal('0.00')) else: price = goods_obj.price price = Decimal(price).quantize(Decimal('0.00')) order = Orders.objects.create( user_id=user.id, goods_id=goods_obj.pk, order_id=out_trade, total_amount=price ) order.save() # 主题 subject = "实验楼" # 电脑网站支付,需要跳转到https://openapi.alipay.com/gateway.do? + order_string order_string = alipay.api_alipay_trade_page_pay( out_trade_no=out_trade, total_amount=int(price), subject='subject', return_url=settings.RETURN_URL, # notify_url="http://127.0.0.1:8000/app02/callback_alipay" # 可选, 不填则使用默认notify url ) pay_url = 'https://openapi.alipaydev.com/gateway.do?' + order_string return Response({'data': {'pay_url': pay_url, 'msg': 'OK', "code": 200}}) class PeyMentView(APIView): def post(self, request): data = request.data data.pop("sign") print(data) orders_obj = Orders.objects.get(order_id=data['out_trade_no']) orders_obj.trade_no = data['trade_no'] orders_obj.status = 2 orders_obj.save() user = orders_obj.user course = orders_obj.goods.course print(user, course) usercourse = UserCourse.objects.create(user=user, course=course) usercourse.save() return Response({"code": 200})
-
-
app\urls
-
""" author:翔翔 date: use: """ from django.urls import path, re_path from . import views urlpatterns = [ path('getpayurl/', views.PayUrlView.as_view()), path('peyment/', views.PeyMentView.as_view()), ]
-
-
app\utils
-
""" author:翔翔 date: use: """ import datetime import random # 生成随机字符串为订单号 def out_trade_no(): base = "SYL" d = datetime.datetime.now() time_str = '%04d%02d%02d%02d%02d%02d' % (d.year, d.month, d.day, d.hour, d.minute, d.second) rand_num = str(random.randint(10000, 99999)) return base + time_str + rand_num print(out_trade_no())
-
-
项目/settings
-
# 支付宝配置 from alipay import AliPay # 回调地址 RETURN_URL = 'http://127.0.0.1:8888/payment/callback/' app_private_key_string = open('{}/apps/goods/alipay_key/app_private_key'.format(BASE_DIR)).read() alipay_public_key_string = open('{}/apps/goods/alipay_key/alipay_public'.format(BASE_DIR)).read() alipay = AliPay( appid="2016102500759596", 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 )
-
-
app/admin
-
from django.contrib import admin from . import models # Register your models here. admin.site.register(models.Goods) admin.site.register(models.Orders)
-
-
测试接口
-
post请求 拼接路由 http://192.168.56.100:8888/goods/getpayurl/
-
回调后发送post请求
http://192.168.56.100:8888/goods/peyment/
```