文件目录
conf.py
import os # o_你自己的应用ID app_id = "***********" # 支付宝收到用户的支付,会向商户发两个请求,一个get请求,一个post请求 # o_你自己公网服务器处理支付宝回调的POST请求,验证订单 notify_url = "http://39.100.233.226:8000/order/aliback/" # o_你自己公网服务器处理支付宝回调的GET请求,将订单结果展现给用户 return_url = "http://39.100.233.226:8000/order/aliback/" # o_你自己的私钥 alipay_private_key_path = os.path.join(os.path.dirname(__file__), 'alipay_private_2048.txt') # o_你自己的公钥 alipay_public_key_path = os.path.join(os.path.dirname(__file__), 'alipay_public_2048.txt')
pay.py
from datetime import datetime from Crypto.PublicKey import RSA from Crypto.Signature import PKCS1_v1_5 from Crypto.Hash import SHA256 from urllib.parse import quote_plus from base64 import decodebytes, encodebytes import json class AliPay(object): """ 支付宝支付接口(PC端支付接口) """ def __init__(self, appid, app_notify_url, app_private_key_path, alipay_public_key_path, return_url, debug=False): self.appid = appid self.app_notify_url = app_notify_url self.app_private_key_path = app_private_key_path self.app_private_key = None self.return_url = return_url with open(self.app_private_key_path) as fp: self.app_private_key = RSA.importKey(fp.read()) self.alipay_public_key_path = alipay_public_key_path with open(self.alipay_public_key_path) as fp: self.alipay_public_key = RSA.importKey(fp.read()) if debug is True: self.__gateway = "https://openapi.alipaydev.com/gateway.do" else: self.__gateway = "https://openapi.alipay.com/gateway.do" def direct_pay(self, subject, out_trade_no, total_amount, return_url=None, **kwargs): biz_content = { "subject": subject, "out_trade_no": out_trade_no, "total_amount": total_amount, "product_code": "FAST_INSTANT_TRADE_PAY", # "qr_pay_mode":4 } biz_content.update(kwargs) data = self.build_body("alipay.trade.page.pay", biz_content, self.return_url) return self.sign_data(data) def build_body(self, method, biz_content, return_url=None): data = { "app_id": self.appid, "method": method, "charset": "utf-8", "sign_type": "RSA2", "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "version": "1.0", "biz_content": biz_content } if return_url is not None: data["notify_url"] = self.app_notify_url data["return_url"] = self.return_url return data def sign_data(self, data): data.pop("sign", None) # 排序后的字符串 unsigned_items = self.ordered_data(data) unsigned_string = "&".join("{0}={1}".format(k, v) for k, v in unsigned_items) sign = self.sign(unsigned_string.encode("utf-8")) # ordered_items = self.ordered_data(data) quoted_string = "&".join("{0}={1}".format(k, quote_plus(v)) for k, v in unsigned_items) # 获得最终的订单信息字符串 signed_string = quoted_string + "&sign=" + quote_plus(sign) return signed_string def ordered_data(self, data): complex_keys = [] for key, value in data.items(): if isinstance(value, dict): complex_keys.append(key) # 将字典类型的数据dump出来 for key in complex_keys: data[key] = json.dumps(data[key], separators=(',', ':')) return sorted([(k, v) for k, v in data.items()]) def sign(self, unsigned_string): # 开始计算签名 key = self.app_private_key signer = PKCS1_v1_5.new(key) signature = signer.sign(SHA256.new(unsigned_string)) # base64 编码,转换为unicode表示并移除回车 sign = encodebytes(signature).decode("utf8").replace("\n", "") return sign def _verify(self, raw_content, signature): # 开始计算签名 key = self.alipay_public_key signer = PKCS1_v1_5.new(key) digest = SHA256.new() digest.update(raw_content.encode("utf8")) if signer.verify(digest, decodebytes(signature.encode("utf8"))): return True return False def verify(self, data, signature): if "sign_type" in data: sign_type = data.pop("sign_type") # 排序后的字符串 unsigned_items = self.ordered_data(data) message = "&".join(u"{}={}".format(k, v) for k, v in unsigned_items) return self._verify(message, signature)
payinit.py
from .pay import AliPay import os from . import conf def ali_init(): # o_你自己的应用ID app_id = conf.app_id # 支付宝收到用户的支付,会向商户发两个请求,一个get请求,一个post请求 # o_你自己公网服务器处理支付宝回调的POST请求,验证订单 notify_url = conf.notify_url # # o_你自己公网服务器处理支付宝回调的GET请求,将订单结果展现给用户 return_url = conf.return_url # o_你自己的私钥 alipay_private_key_path = conf.alipay_private_key_path # o_你自己的公钥 alipay_public_key_path = conf.alipay_public_key_path alipay = AliPay( appid=app_id, app_notify_url=notify_url, return_url=return_url, app_private_key_path=alipay_private_key_path, alipay_public_key_path=alipay_public_key_path, # 支付宝的公钥,验证支付宝回传消息使用,不是你自己的公钥 debug=True, # 默认False, ) return alipay
alipay_public_2048
-----BEGIN PUBLIC KEY----- # 要用自己的公钥去换ali的公钥 ... -----END PUBLIC KEY-----
alipay_private_2048
-----BEGIN RSA PRIVATE KEY----- ... -----END RSA PRIVATE KEY-----
后台接口实现
from rest_framework.views import APIView from utils.APIResponse import APIResponse from rest_framework_jwt.authentication import JSONWebTokenAuthentication from rest_framework.permissions import IsAuthenticated from libs.alipay import payinit # 根据商品信息生成订单号与支付宝链接 import time from django.core.cache import cache class OrderAPIView(APIView): authentication_classes = [JSONWebTokenAuthentication] permission_classes = [IsAuthenticated] def post(self, request, *args, **kwargs): alipay = payinit.ali_init() trade_no = str(time.time()).replace('.', '1') # 考虑信息安全性,订单最终的金额一定是前后台双方校验决定 subject = request.data.get('subject') money = request.data.get('money') # 对信息要进行校验 if not (subject and money): return APIResponse(1, '订单信息有误!') query_params = alipay.direct_pay( subject=subject, out_trade_no=trade_no, total_amount=money, ) trade_url = "https://openapi.alipaydev.com/gateway.do?{}".format(query_params) # 服务器存储订单信息:订单状态 False - 未支付 - mysql中也需要存储 order id no status user_id cache.set(trade_no, False) return APIResponse(0, 'ok', { 'trade_no': trade_no, 'trade_url': trade_url }) from rest_framework.response import Response from utils.logging import logger class AlibackAPIView(APIView): def post(self, request, *args, **kwargs): # 初始化alipay alipay = payinit.ali_init() # 检测是否支付成功 # 去请求体中获取所有返回的数据:状态/订单号 from urllib.parse import parse_qs body_str = request.body.decode('utf-8') post_data = parse_qs(body_str) post_dict = {} for k, v in post_data.items(): post_dict[k] = v[0] logger.warning("^_^: %s" % post_dict) sign = post_dict.pop('sign', None) # 通过调用alipay的verify方法去二次认证 status = alipay.verify(post_dict, sign) if status: # 订单状态在此修改 logger.warning("^_^: %s" % post_dict) pass return Response('验证成功') def get(self, request, *args, **kwargs): ''' 支付宝先给你发一个get请求测试你的服务器是否存活, 再发送post请求给你返回真实的数据 ''' # 初始化alipay alipay = payinit.ali_init() params = request.GET.dict() sign = params.pop('sign', None) status = alipay.verify(params, sign) print('GET验证', status) if status: # 获取订单状态,显示给用户 return Response('支付成功')