• 支付宝支付示例


    加密:RAS 

    秘钥:商户私钥+支付宝公钥

    宕机:重发

    精度:小数点后两位

    settings.py

    # 支付相关配置
    APPID = "2016082500309412"
    NOTIFY_URL = "http://47.98.134.86:80/update_order/"
    RETURN_URL = "http://47.98.134.86:80/pay_result/"
    PRI_KEY_PATH = "keys/app_private_2048.txt"
    PUB_KEY_PATH = "keys/alipay_public_2048.txt"
    -----BEGIN PUBLIC KEY-----
    MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwAKqBWxQfVsWwphI6avNRd3cCRNsQrgfIW1WuOM2A0ZU2mH9oJwbZkE7rN1mveJsI6R96vO27wZ6ewHljDgT/HKTw3Y7lYyKdezJYm7rFqBey0n8s5qnjuPYaO2l+E9v9VxfyEGyviTOY9mgzPmjplmfr3GGyVMVaWoIwVLB4atNobxt6TelgCGlF8wcbQmmVIrvWVTyCLqNjl8mBOtyeWCQ7mLsFeGzV7R+ifjpXceMOzUkEjU6XNor+AgUGYuHhOdb04tLAl4Hq/nicQveTBWnrqBO5NbUGZP5l5LKNA0nDptvBrmC14rLIbCaflA4OVzq7Q2QWI+czaA1VOMwcwIDAQAB
    -----END PUBLIC KEY-----
    keys/alipay_public_2048.txt
    -----BEGIN RSA PRIVATE KEY-----
    MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDXQe0EbqDzgrnyr6thNguaKVzz6STzpUPVfKfCz4E6eNlsq4P/0mHuBsPnbRFy1TNI+JXuIp7WFOjd/5zyP0ClGxxGntZTEd8qOSems0SfwZbuznGm0PoCzKHf7bYKq5qj+5abrl2q/42JmVep2sPGKZ2OZuESttQYEcAQlxLarm9Wv+8Njfo9/JKRQj8e5J15QvTVlaMQpbnn8zQk8M294RHkH7aGlB2b7ITG56PFXmffwjeZcVSsoMzmuKBb5JUOYrIwCu6W+Phvk/GHihID+K8q/UcMfgeZ3HvHOavbLvrkEu44BKHz2q5azChtc8QNA1xQBVchhdy+/4DEBQ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r12Y1T2crrqJVY47Gf3PfSfLqwYEUEe7NewuFATiZ8udZdWZRxIGXowFF8BehLcZyABP3ZrkC2Ognc3kSvg93kng5rClprvn/a6NbkGqws8P6ndnzahy7Tn6WixItZtUZcOETW9QHkbhMHJduLTZ1/mA==
    -----END RSA PRIVATE KEY-----
    keys/app_private_2048.txt
    from datetime import datetime
    from Crypto.PublicKey import RSA               #RSA加密
    from Crypto.Signature import PKCS1_v1_5
    from Crypto.Hash import SHA256
    from urllib.parse import quote_plus
    from urllib.parse import urlparse, parse_qs
    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("
    ", "")
            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)
    utils/pay.py

    pay.py中有一些算法,依赖于Crypto

    使用cmd进行安装

    pip3 install pycryptodome

    app01/views.py

    from django.shortcuts import render,redirect,HttpResponse
    from django.views.decorators.csrf import csrf_exempt
    from utils.pay import AliPay
    import time
    from django.conf import settings
    
    
    def aliPay():
        obj = AliPay(
            appid=settings.APPID,
            app_notify_url=settings.NOTIFY_URL,  # 如果支付成功,支付宝会向这个地址发送POST请求(校验是否支付已经完成)
            return_url=settings.RETURN_URL,  # 如果支付成功,重定向回到你的网站的地址。
            alipay_public_key_path=settings.PUB_KEY_PATH,  # 支付宝公钥
            app_private_key_path=settings.PRI_KEY_PATH,  # 应用私钥   商户
            debug=True,  # 默认False,
        )
        return obj
    
    def index(request):
        if request.method == 'GET':
            return render(request,'index.html')
    
        # 实例化,用于对数据进行加密,并生成url
        alipay = aliPay()
    
        # 对购买的数据进行加密
        money = float(request.POST.get('price'))
        out_trade_no = "x2" + str(time.time())     #订单号
        # 1. 在数据库创建一条数据:状态(待支付)
    
        query_params = alipay.direct_pay(
            subject="充气式mm",  # 商品简单描述
            out_trade_no= out_trade_no,  # 商户订单号
            total_amount=money,  # 交易金额(单位: 元 保留俩位小数)
        )
    
        pay_url = "https://openapi.alipaydev.com/gateway.do?{}".format(query_params)
    
        return redirect(pay_url)
    
    
    def pay_result(request):
        """
        支付完成后,跳转回的地址
        :param request:
        :return:
        """
        params = request.GET.dict()
        sign = params.pop('sign', None)
    
        alipay = aliPay()
    
        status = alipay.verify(params, sign)  #校验
    
        if status:
            return HttpResponse('支付成功')
        return HttpResponse('支付失败')
    
    
    
    @csrf_exempt
    def update_order(request):
        """
        支付成功后,支付宝向该地址发送的POST请求(用于修改订单状态)
        :param request:
        :return:
        """
        if request.method == 'POST':
            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]
    
            alipay = aliPay()
    
            sign = post_dict.pop('sign', None)
            status = alipay.verify(post_dict, sign)
            if status:
                # 修改订单状态
                out_trade_no = post_dict.get('out_trade_no')  #拿订单号
                print(out_trade_no)
                # 2. 根据订单号将数据库中的数据进行更新
                return HttpResponse('支付成功')
            else:
                return HttpResponse('支付失败')
        return HttpResponse('')  #GET请求不处理

    templates/index.html

    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <body>
        <form method="post">
            {% csrf_token %}
            <input type="text" name="price" placeholder="请输入要支付的金额">
            <input type="submit" value="支付">
        </form>
    </body>
    </html>
    from django.db import models
    
    class Order(models.Model):
    
        title = models.CharField(max_length=32)
        order_num = models.CharField(max_length=32)
        status_choices = (
            (1,'未支付'),
            (2,'已支付'),
        )
        status = models.IntegerField(choices=status_choices,default=1)
    app01/models.py
  • 相关阅读:
    Linux组件封装(三) Thread的封装
    Linux组件封装(二) 条件变量Condition的封装
    Linux组件封装(一) 互斥锁MutexLock
    迭代器适配器(二) general inserter的简单实现
    迭代适配器(一) back_insert和front_insert的简单实现
    priority_queue的简单实现
    svm简易例子——matlab版本
    讲座 on the connection between vision and language
    svm相关理解
    为什么深度学习有效?(why deep learning works)
  • 原文地址:https://www.cnblogs.com/zh-xiaoyuan/p/13170409.html
Copyright © 2020-2023  润新知