Django支付寶(沙箱)後端介面
阿新 • • 發佈:2020-11-20
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/
```