• flask 支付宝的使用


    1. 需要去官方网页里面登录自己的账号

    https://open.alipay.com/

    2. 登录后需要保存一些数据

    1. 进入网址之后进行登录=》控制台=》沙箱
    2. 保存APPID
      在这里插入图片描述
    3. 保存公钥&密钥
      在这里插入图片描述

    3. 安装支付宝模块

    pip install python-alipay-sdk --upgrade
    pip uninstall PyCrypto
    pip uninstall PyCryptodome
    pip install PyCryptodome
    
    • 1
    • 2
    • 3
    • 4

    4. 封装支付宝支付方法

    1. 创建一个keys/private_key.txt写入私钥
    -----BEGIN RSA PRIVATE KEY-----
    写入保存到的私钥
    -----END RSA PRIVATE KEY-----
    
    • 1
    • 2
    • 3
    1. 创建一个keys/public_key.txt写入公钥
    -----BEGIN PUBLIC KEY-----
    写入保存到的公钥
    -----END PUBLIC KEY-----
    
    • 1
    • 2
    • 3
    1. 创建一个utlis/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 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 query_pay(self, out_trade_no,return_url=None, **kwargs):
            biz_content = {
                "out_trade_no": out_trade_no,
               
                # "product_code": "FAST_INSTANT_TRADE_PAY",
                # "qr_pay_mode":4
            }
    
            biz_content.update(kwargs)
            data = self.build_body("alipay.trade.query", 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)
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    1. 封装调用支付方法,下面的app_id需要写入自己保存的APPID
    #导入支付基类
    from utils.pay import AliPay
    
    #初始化阿里支付对象
    def get_ali_object():
        # 沙箱环境地址:https://openhome.alipay.com/platform/appDaily.htm?tab=info
        app_id = "2021000120615296"  #  APPID (沙箱应用)
    
        # 支付完成后,支付偷偷向这里地址发送一个post请求,识别公网IP,如果是 192.168.20.13局域网IP ,支付宝找不到,def page2() 接收不到这个请求
        notify_url = "http://127.0.0.1:5000/callback"
    
        # 支付完成后,跳转的地址。
        return_url = "http://localhost:8080/"
    
        merchant_private_key_path = "./keys/private_key.txt" # 应用私钥
        alipay_public_key_path = "./keys/public_key.txt"  # 支付宝公钥
    
        alipay = AliPay(
            appid=app_id,
            app_notify_url=notify_url,
            return_url=return_url,
            app_private_key_path=merchant_private_key_path,
            alipay_public_key_path=alipay_public_key_path,  # 支付宝的公钥,验证支付宝回传消息使用,不是你自己的公钥
            debug=True,  # 默认False,
        )
        return alipay
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    1. 去蓝图调用
    # 支付宝平台
    from utils.procom import get_ali_object
    
    
    @shops_bp.route('/alipay')
    def getalipay():
    	alipay = get_ali_object()
    	res = alipay.direct_pay(subject='订单:123456',  # 商品描述
    	                        out_trade_no='66666'),  # 用户购买的商品订单号
    							total_amount = 66.6)  # 交易金额
    
    	pay_url = f"https://openapi.alipaydev.com/gateway.do?{res}"
    
    	# return redirect(pay_url)    # 访问是跳转到pay_url页面
    	return jsonify({'code': 200, 'url': pay_url})
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    1. 前端使用window跳转
    window.location.href = url
    
    • 1
  • 相关阅读:
    gittee启动器
    深度学习记录
    STM32_3(GPIO)
    CBOE and others
    CrossOver22试用期到了如何免费使用?
    实时更新进度条:JavaScript中的定时器和异步编程技巧
    《SpringBoot篇》19.SpringBoot整合Quart
    程序员面试金典 - 面试题 17.13. 恢复空格
    防御安全第五次作业
    MongoDB第二话 -- MongoDB高可用集群实现
  • 原文地址:https://blog.csdn.net/m0_70015578/article/details/126630637