# 一、在沙箱環境下實名認證:https://openhome.alipay.com/platform/appDaily.htm?tab=info # 二、電腦網站支付API:https://docs.open.alipay.com/270/105898/ # 三、完成RSA密鑰生成:https://docs.open.alipay.com/291/105971 # 四、在開發中心的沙箱應用下設置應用公鑰:填入生成的公鑰文件中的內容 # 五、Python支付寶開源框架:https://github.com/fzlee/alipay # >: pip install python-alipay-sdk --upgrade # 七、公鑰私鑰設置 """ # alipay_public_key.pem -----BEGIN PUBLIC KEY----- 支付寶公鑰 -----END PUBLIC KEY----- # app_private_key.pem -----BEGIN RSA PRIVATE KEY----- 用戶私鑰 -----END RSA PRIVATE KEY----- """ # 八、支付寶連接 """ 開發:https://openapi.alipay.com/gateway.do 沙箱:https://openapi.alipaydev.com/gateway.do """
1python
2git
3github
4django
5api
>: pip install python-alipay-sdk
libs ├── iPay # aliapy二次封裝包 │ ├── __init__.py # 包文件 │ ├── keys # 密鑰文件夾 │ │ ├── alipay_public_key.pem # 支付寶公鑰 │ │ └── app_private_key.pem # 應用私鑰 └── └── settings.py # 應用配置
import os # 支付寶應用id APP_ID = '2016093000631831' # 默認異步回調的地址,一般設置None就行 APP_NOTIFY_URL = None # 應用私鑰文件路徑 APP_PRIVATE_KEY_PATH = os.path.join(os.path.dirname(__file__), 'keys', 'app_private_key.pem') # 支付寶公鑰文件路徑 ALIPAY_PUBLIC_KEY_PATH = os.path.join(os.path.dirname(__file__), 'keys', 'alipay_public_key.pem') # 簽名方式 SIGN_TYPE = 'RSA2' # 是不是測試環境 - 是不是支付寶沙箱 DEBUG = True # 支付鏈接 DEV_PAY_URL = 'https://openapi.alipaydev.com/gateway.do?' PROD_PAY_URL = 'https://openapi.alipay.com/gateway.do?'
from alipay import AliPay from .settings import * # 對外提供支付對象 alipay = AliPay( appid=APP_ID, app_notify_url=APP_NOTIFY_URL, app_private_key_path=APP_PRIVATE_KEY_PATH, alipay_public_key_path=ALIPAY_PUBLIC_KEY_PATH, sign_type=SIGN_TYPE, debug=DEBUG ) # 對外提供的支付連接前綴 pay_url = DEV_PAY_URL if DEBUG else PROD_PAY_URL
-----BEGIN PUBLIC KEY----- 支付寶公鑰 -----END PUBLIC KEY-----
# 在支付寶生成祕鑰的軟件中,經過應用公鑰換取支付寶公鑰
-----BEGIN RSA PRIVATE KEY----- 應用私鑰 -----END RSA PRIVATE KEY-----
# 先後臺base_url UP_BASE_URL = 'http://127.0.0.1:8080' END_BASE_URL = 'http://127.0.0.1:8000' # alipay回調接口配置 # 上線後必須換成官網地址 # 同步回調的接口(get),先後臺分離時通常設置前臺頁面url RETURN_URL = UP_BASE_URL + '/pay/success' # 異步回調的接口(post),必定設置爲後臺服務器接口 NOTIFY_URL = END_BASE_URL + '/order/success/'
from django.db import models # 訂單表: from django.db import models from utils.model import BaseModel from user.models import User from course.models import Course class Order(models.Model): """訂單模型""" status_choices = ( (0, '未支付'), (1, '已支付'), (2, '已取消'), (3, '超時取消'), ) pay_choices = ( (1, '支付寶'), (2, '微信支付'), ) subject = models.CharField(max_length=150, verbose_name="訂單標題") total_amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="訂單總價", default=0) out_trade_no = models.CharField(max_length=64, verbose_name="訂單號", unique=True) trade_no = models.CharField(max_length=64, null=True, verbose_name="流水號") order_status = models.SmallIntegerField(choices=status_choices, default=0, verbose_name="訂單狀態") pay_type = models.SmallIntegerField(choices=pay_choices, default=1, verbose_name="支付方式") pay_time = models.DateTimeField(null=True, verbose_name="支付時間") user = models.ForeignKey(User, related_name='user_orders', on_delete=models.DO_NOTHING, db_constraint=False, verbose_name="下單用戶") class Meta: db_table = "luffy_order" verbose_name = "訂單記錄" verbose_name_plural = "訂單記錄" def __str__(self): return "%s - ¥%s" % (self.subject, self.total_amount) @property def courses(self): data_list = [] for item in self.order_courses.all(): data_list.append({ "id": item.id, "course_name": item.course.name, "real_price": item.real_price, }) return data_list class OrderDetail(BaseModel): """訂單詳情""" order = models.ForeignKey(Order, related_name='order_courses', on_delete=models.CASCADE, db_constraint=False, verbose_name="訂單") course = models.ForeignKey(Course, related_name='course_orders', on_delete=models.CASCADE, db_constraint=False, verbose_name="課程") price = models.DecimalField(max_digits=6, decimal_places=2, verbose_name="課程原價") real_price = models.DecimalField(max_digits=6, decimal_places=2, verbose_name="課程實價") class Meta: db_table = "luffy_order_detail" verbose_name = "訂單詳情" verbose_name_plural = "訂單詳情" def __str__(self): return "%s訂單(%s)" % (self.course.name, self.order.out_trade_no)
import time from rest_framework.views import APIView from utils.response import APIResponse from libs.iPay import alipay from . import authentications, serializers from rest_framework.permissions import IsAuthenticated from django.conf import settings # 獲取前臺 商品名、價格,產生 訂單、支付連接 class PayAPIView(APIView): authentication_classes = [authentications.JWTAuthentication] permission_classes = [IsAuthenticated] def post(self, request, *args, **kwargs): # 前臺提供:商品名、總價、支付方式 request_data = request.data # 後臺產生:訂單號、用戶 out_trade_no = '%d' % time.time() * 2 request_data['out_trade_no'] = out_trade_no request_data['user'] = request.user.id # 反序列化數據,用於訂單生成前的校驗 order_ser = serializers.OrderModelSerializer(data=request_data) if order_ser.is_valid(): # 生成訂單,訂單默認狀態爲:未支付 order = order_ser.save() # 支付連接的參數 order_string = alipay.api_alipay_trade_page_pay( subject=order.subject, out_trade_no=order.out_trade_no, total_amount='%.2f' % order.total_amount, return_url=settings.RETURN_URL, notify_url=settings.NOTIFY_URL ) # 造成支付連接:alipay._gateway根據字符環境DEBUG配置信息,決定是沙箱仍是真實支付環境 pay_url = '%s?%s' % (alipay._gateway, order_string) return APIResponse(0, 'ok', pay_url=pay_url) return APIResponse(1, 'no ok', results=order_ser.errors)
from . import models from utils.logging import logger from rest_framework.response import Response class SuccessAPIView(APIView): # 不能認證,別人支付寶異步回調就進不來了 # authentication_classes = [authentications.JWTAuthentication] # permission_classes = [IsAuthenticated] def patch(self, request, *args, **kwargs): # 默認是QueryDict類型,不能使用pop方法 request_data = request.query_params.dict() # 必須將 sign、sign_type(內部有安全處理) 從數據中取出,拿sign與剩下的數據進行校驗 sign = request_data.pop('sign') result = alipay.verify(request_data, sign) if result: # 同步回調:修改訂單狀態 try: out_trade_no = request_data.get('out_trade_no') order = models.Order.objects.get(out_trade_no=out_trade_no) if order.order_status != 1: order.order_status = 1 order.save() except: pass return APIResponse(0, '支付成功') return APIResponse(1, '支付失敗') # 支付寶異步回調 def post(self, request, *args, **kwargs): # 默認是QueryDict類型,不能使用pop方法 request_data = request.data.dict() # 必須將 sign、sign_type(內部有安全處理) 從數據中取出,拿sign與剩下的數據進行校驗 sign = request_data.pop('sign') result = alipay.verify(request_data, sign) # 異步回調:修改訂單狀態 if result and request_data["trade_status"] in ("TRADE_SUCCESS", "TRADE_FINISHED" ): out_trade_no = request_data.get('out_trade_no') logger.critical('%s支付成功' % out_trade_no) try: order = models.Order.objects.get(out_trade_no=out_trade_no) if order.order_status != 1: order.order_status = 1 order.save() except: pass # 支付寶八次異步通知,訂單成功必定要返回 success return Response('success') return Response('failed')