支付宝支付
入门
""" 1)支付宝API:六大接口 https://docs.open.alipay.com/270/105900/ 2)支付宝工作流程(见下图): https://docs.open.alipay.com/270/105898/ 3)支付宝8次异步通知机制(支付宝对我们服务器发送POST请求,索要 success 7个字符) https://docs.open.alipay.com/270/105902/ """
流程
# 1、在沙箱环境下实名认证:https://openhome.alipay.com/platform/appDaily.htm?tab=info # 2、电脑网站支付API:https://docs.open.alipay.com/270/105900/ # 3、完成RSA密钥生成:https://docs.open.alipay.com/291/105971 # 4、在开发中心的沙箱应用下设置应用公钥:填入生成的公钥文件中的内容 # 5、Python支付宝开源框架:https://github.com/fzlee/alipay # >: pip install python-alipay-sdk --upgrade # 7、公钥私钥设置 """ # alipay_public_key.pem -----BEGIN PUBLIC KEY----- 支付宝公钥 -----END PUBLIC KEY----- # app_private_key.pem -----BEGIN RSA PRIVATE KEY----- 用户私钥 -----END RSA PRIVATE KEY----- """ # 8、支付宝链接 """ 开发:https://openapi.alipay.com/gateway.do 沙箱:https://openapi.alipaydev.com/gateway.do """
后端使用测试代码示例:
t_alipay.py
from alipay import AliPay # app_private_key_string = open("/path/to/your/private/key.pem").read() # alipay_public_key_string = open("/path/to/alipay/public/key.pem").read() app_private_key_string = """-----BEGIN RSA PRIVATE KEY----- MIIEpAIBAAKCAQEAq+PKAWg9R8ms8FPJROUsWoPxoPjzOihvqqAmcLoAPb/69e6sYt0SJGtz16aYz5EUkRsSaxEwObepnb58ziYg7dOblrrFbp46FPe4FeQb17s0xSSJHWbZT+3eu+kiaCznEvuQNdfjIxyyv63RbZth1+lblXj7TLMsHd4cggUvSn8aylqgfqF6mFezXfBheB/ZZ1F+uRh3/1UaOm7hlBt3cxQGN20PmZB1kYa8Lzv33F4/2Vt3drOeIpjWtdzICD/opcuIToNhlGVvMOybIWEWT3CrdRal9RLoukNcTm3UTIOF4X9FsBaHvtAGRCMWs5GU/sx83qKYW1YNEg9oa3awZQIDAQABAoIBAQCQ+jOrNCxbnDKNEV41CcZ7IcZvKwqbBvg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hToE70V4KhLNleoLUAXlNDGTK+pW365F4UXSu/UkHmZpjHgqyFX0J83vBVp+QfRJUlyD4Q7mjo2FsQPcpXgFFjnYw== -----END RSA PRIVATE KEY----- """ alipay_public_key_string = """-----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmiCxllecv79tYxmLKbW7VhgS5RvdrBHf/2RwwDH/72Lnhw/qLAtRrGXqhJWfZLMELGeI+WKoYUOTHwcEYdM0gdaX5PlgWZMGjtW2D6cRWsJtaJBCTBHB/Kf6aT3gVaBONd0SNc4tZ74szJm5o58RhiASvgeaA96NX3jzp/Q5ubACCVJV/bCg4uuYi+O9QV7pDcMOCjNm6Vk1TZ25fA5Bwx3lBi3hFjoEC69+WnmxWwm3RhkcaCAEWfagMgN+YlFsC3zuEUbpi+YQ3XycuCtQypMZmpauvWT1s5AbrY45yWFNUBLvaB2WQvRmLMwFBRIW3B35iw2ntHtLHeEmgvIqOQIDAQAB -----END PUBLIC KEY----- """ alipay = AliPay( appid="2021000116697102", app_notify_url='http://127.0.0.1:8000/free/course', # the default notify path app_private_key_string=app_private_key_string, # alipay public key, do not use your own public key! alipay_public_key_string=alipay_public_key_string, sign_type="RSA2", # RSA or RSA2 debug=True # False by default ) alipay_url='https://openapi.alipaydev.com/gateway.do?' order_string = alipay.api_alipay_trade_page_pay ( out_trade_no="20161112jc", total_amount=9999, subject='Dell外星人', return_url="https://www.luffycity.com/free-course", notify_url="https://www.luffycity.com/free-course" ) print(alipay_url+order_string)
支付流程
aliapy二次封装包
GitHub开源框架
# https://github.com/fzlee/alipay
依赖
>: pip install python-alipay-sdk --upgrade # 如果抛ssl相关错误,代表缺失该包 >: pip install pyopenssl
结构
libs ├── iPay # aliapy二次封装包 │ ├── __init__.py # 包文件 │ ├── pem # 公钥私钥文件夹 │ │ ├── alipay_public_key.pem # 支付宝公钥文件 │ │ ├── app_private_key.pem # 应用私钥文件 │ ├── pay.py # 支付文件 └── └── settings.py # 应用配置
alipay_public_key.pem
-----BEGIN PUBLIC KEY-----
拿应用公钥跟支付宝换来的支付宝公钥
-----END PUBLIC KEY-----
app_private_key.pem
-----BEGIN RSA PRIVATE KEY-----
通过支付宝公钥私钥签发软件签发的应用私钥
-----END RSA PRIVATE KEY-----
setting.py
import os # 应用私钥 APP_PRIVATE_KEY_STRING = open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'pem', 'app_private_key.pem')).read() # 支付宝公钥 ALIPAY_PUBLIC_KEY_STRING = open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'pem', 'alipay_public_key.pem')).read() # 应用ID APP_ID = '2016093000631831' # 加密方式 SIGN = 'RSA2' # 是否是支付宝测试环境(沙箱环境),如果采用真是支付宝环境,配置False DEBUG = True # 支付网关 GATEWAY = 'https://openapi.alipaydev.com/gateway.do' if DEBUG else 'https://openapi.alipay.com/gateway.do'
pay.py
from alipay import AliPay from . import settings # 支付对象 alipay = AliPay( appid=settings.APP_ID, app_notify_url=None, app_private_key_string=settings.APP_PRIVATE_KEY_STRING, alipay_public_key_string=settings.ALIPAY_PUBLIC_KEY_STRING, sign_type=settings.SIGN, debug=settings.DEBUG ) # 支付网关 gateway = settings.GATEWAY
_init_.py
# 包对外提供的变量 from .pay import gateway, alipay
补充:在自己项目的配置文件中配置支付宝回调接口:settings.py | dev.py
# 上线后必须换成公网地址 # 后台基URL BASE_URL = 'http://127.0.0.1:8000' # 前台基URL LUFFY_URL = 'http://127.0.0.1:8080' # 支付宝同步异步回调接口配置 # 后台异步回调接口 NOTIFY_URL = BASE_URL + "/order/success/" # 前台同步回调接口,没有 / 结尾 RETURN_URL = LUFFY_URL + "/pay/success"
后台支付接口
模型表:order/models.py
# 订单表分析 -订单表 -订单详情 # 代码 from django.db import models 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='order_user', on_delete=models.DO_NOTHING, db_constraint=False, verbose_name="下单用户") created_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间') updated_time = models.DateTimeField(auto_now=True, 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(models.Model): """订单详情""" 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.SET_NULL, db_constraint=False, verbose_name="课程", null=True) 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): try: return "%s的订单:%s" % (self.course.name, self.order.out_trade_no) except: return super().__str__()
数据迁移
# python manage.py makemigrations # python manage.py migrate
# 1 支付接口(生成订单,,生成支付连接,返回支付连接) -order表和orderdetail表插入数据,重写create方法 -生成订单号(uuid) -登录后才能做(jwt认证) -当前登录用户就是下单用户,存到order表中 -下了三个课程,总价格100,前端提交的价格是99,异常处理 ''' #1)订单总价校验 # 2)生成订单号 # 3)支付用户:request.user # 4)支付链接生成 # 5)入库(两个表)的信息准备 ''' # 2 支付宝异步回调的post接口(验证签名,修改订单状态) # 3 当支付宝get回调前端,vue组件一创建,立马向后端发一个请求(get)
支付接口
分析:
# 1 前端传什么格式数据 -{course:[1,2,3],total_amount:100,subject:xx商品,pay_type:1,} # 2 后端接到数据要校验 -course:[1,2,3]===》course:[obj1,obj2,obj3] -在序列化类中:course=serializers.PrimaryKeyRelatedField(queryset=Course.objects.all(), write_only=True, many=True)
order/urls.py
from django.urls import path,re_path,include from rest_framework.routers import SimpleRouter from . import views router = SimpleRouter() router.register('pay', views.PayView, 'pay') urlpatterns = [ path('', include(router.urls)) ]
serializers.py
from rest_framework import serializers from rest_framework.exceptions import ValidationError from django.conf import settings from . import models from course.models import Course class OrderSerializer(serializers.ModelSerializer): # 前端传什么格式数据 # -{course:[1,2,3],total_amount:100,subject:xx商品,pay_type:1,} # user字段需要,但是不是传的,使用了jwt # 2 后端接到数据要校验 # course: [1, 2, 3] == =》course: [obj1,obj2,obj3] # 在序列化类中: # 方法1:用局部钩子自己处理 # course = serializers.CharField() # 方法2: # course = serializers.PrimaryKeyRelatedField(queryset=Course.objects.all(), write_only=True, many=True) course = serializers.PrimaryKeyRelatedField(queryset=Course.objects.all(), write_only=True, many=True) class Meta: model = models.Order fields = ['total_amount', 'subject', 'pay_type', 'course'] extra_kwargs = { "total_amount": {'required': True}, "pay_type": {'required': True}, } # 订单总价校验 def _check_price(self, attrs): course_list = attrs.get('course') total_amount = attrs.get('total_amount') total_price = 0 for course in course_list: total_price += course.price if total_price != total_amount: raise ValidationError('价格不合法') return total_amount # 生成订单号 def _gen_out_trade_no(self): import uuid code = '%s' % uuid.uuid4() return code.replace('-', '') # 获取支付用户 # 需要request对象(需要视图通过context把request对象传过来,重写create方法) def _get_user(self): return self.context.get('request').user def _gen_pay_url(self, out_trade_no, total_amount, subject): from luffyapi.libs.al_pay import alipay, gate_way order_string = alipay.api_alipay_trade_page_pay( out_trade_no=out_trade_no, total_amount=float(total_amount), # 只有生成支付宝链接时,不能用Decimal,因为支付宝识别不了,需要转换成float类型 subject=subject, return_url=settings.RETURN_URL, # get回调,前台地址 notify_url=settings.NOTIFY_URL, # post回调,后台地址 ) return gate_way + order_string # 入库(两个表)的信息准备 def _before_create(self, attrs, user, pay_url, out_trade_no): attrs['user'] = user attrs['out_trade_no'] = out_trade_no self.context['pay_url'] = pay_url # 校验 def validate(self, attrs): """ # 1)订单总价校验 # 2)生成订单号 # 3)支付用户:request.user # 4)支付链接生成 # 5)入库(两个表)的信息准备 """ # 1)订单总价校验 total_amount = self._check_price(attrs) # 2)生成订单号 out_trade_no = self._gen_out_trade_no() # 3)支付用户:request.user user = self._get_user() # 4)支付链接生成 pay_url = self._gen_pay_url(out_trade_no, total_amount, attrs.get('subject')) # 5)入库(两个表)的信息准备 self._before_create(attrs, user, pay_url, out_trade_no) # 代表该校验方法通过,进入入库操作 return attrs # 重写入库方法的目的:完成订单与订单详情两个表入库操作 def create(self, validated_data): course_list = validated_data.pop('course') # 订单表入库,不需要course order = models.Order.objects.create(**validated_data) # 订单详情表入库:只需要订单对象,课程对象(courses要拆成一个个course) for course in course_list: models.OrderDetail.objects.create(order=order, course=course, price=course.price, real_price=course.price) # 先循环制造数据列表[{}, ..., {}],用群增完成入库 bulk_create(),效率高 return order
views.py
from django.shortcuts import render from rest_framework.viewsets import GenericViewSet from rest_framework.mixins import CreateModelMixin from rest_framework.response import Response from rest_framework_jwt.authentication import JSONWebTokenAuthentication from rest_framework.permissions import IsAuthenticated from . import models from . import serializers class PayView(GenericViewSet, CreateModelMixin): authentication_classes = [JSONWebTokenAuthentication, ] permission_classes = [IsAuthenticated, ] queryset = models.Order.objects.all() serializer_class = serializers.OrderSerializer # 重写create方法,传request对象 def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) self.perform_create(serializer) return Response(serializer.context.get('pay_url'))