• 支付宝简单使用


    支付宝沙箱测试使用

    调用alipay接口

    复制代码
                # 4 调用alipay接口
                import time
                alipay = self.get_alipay()
                # 生成支付的url
                query_params = alipay.direct_pay(
                    subject="xxxx",  # 商品简单描述
                    out_trade_no="x345" + str(time.time()),  # 商户订单号
                    total_amount=pay_money,  # 交易金额(单位: 元 保留俩位小数)
                )
    
                pay_url = "https://openapi.alipaydev.com/gateway.do?{}".format(query_params)
    
                res.data={
                    "url":pay_url
                }
    复制代码

    self.get_alipay.py

    复制代码
        def get_alipay(self):
            # 沙箱环境地址:https://openhome.alipay.com/platform/appDaily.htm?tab=info
            app_id = "2016091100486897"
            # POST请求,用于最后的检测
            notify_url = "http://47.94.172.250:8804/page2/"
            # notify_url = "http://www.wupeiqi.com:8804/page2/"
            # GET请求,用于页面的跳转展示
            return_url = "http://47.94.172.250:8804/page2/"
            # return_url = "http://www.wupeiqi.com:8804/page2/"
            merchant_private_key_path = "keys/app_private_2048.txt"
            alipay_public_key_path = "keys/alipay_public_2048.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
    复制代码

    引用的from api.utils.pay import AliPay

      1 from datetime import datetime
      2 from Crypto.PublicKey import RSA
      3 from Crypto.Signature import PKCS1_v1_5
      4 from Crypto.Hash import SHA256
      5 from urllib.parse import quote_plus
      6 from urllib.parse import urlparse, parse_qs
      7 from base64 import decodebytes, encodebytes
      8 import json
      9 
     10 
     11 class AliPay(object):
     12     """
     13     支付宝支付接口(PC端支付接口)
     14     """
     15 
     16     def __init__(self, appid, app_notify_url, app_private_key_path,
     17                  alipay_public_key_path, return_url, debug=False):
     18         self.appid = appid
     19         self.app_notify_url = app_notify_url
     20         self.app_private_key_path = app_private_key_path
     21         self.app_private_key = None
     22         self.return_url = return_url
     23         with open(self.app_private_key_path) as fp:
     24             self.app_private_key = RSA.importKey(fp.read())
     25         self.alipay_public_key_path = alipay_public_key_path
     26         with open(self.alipay_public_key_path) as fp:
     27             self.alipay_public_key = RSA.importKey(fp.read())
     28 
     29         if debug is True:
     30             self.__gateway = "https://openapi.alipaydev.com/gateway.do"
     31         else:
     32             self.__gateway = "https://openapi.alipay.com/gateway.do"
     33 
     34     def direct_pay(self, subject, out_trade_no, total_amount, return_url=None, **kwargs):
     35         biz_content = {
     36             "subject": subject,
     37             "out_trade_no": out_trade_no,
     38             "total_amount": total_amount,
     39             "product_code": "FAST_INSTANT_TRADE_PAY",
     40             # "qr_pay_mode":4
     41         }
     42 
     43         biz_content.update(kwargs)
     44         data = self.build_body("alipay.trade.page.pay", biz_content, self.return_url)
     45         return self.sign_data(data)
     46 
     47     def build_body(self, method, biz_content, return_url=None):
     48         data = {
     49             "app_id": self.appid,
     50             "method": method,
     51             "charset": "utf-8",
     52             "sign_type": "RSA2",
     53             "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
     54             "version": "1.0",
     55             "biz_content": biz_content
     56         }
     57 
     58         if return_url is not None:
     59             data["notify_url"] = self.app_notify_url
     60             data["return_url"] = self.return_url
     61 
     62         return data
     63 
     64     def sign_data(self, data):
     65         data.pop("sign", None)
     66         # 排序后的字符串
     67         unsigned_items = self.ordered_data(data)
     68         unsigned_string = "&".join("{0}={1}".format(k, v) for k, v in unsigned_items)
     69         sign = self.sign(unsigned_string.encode("utf-8"))
     70         # ordered_items = self.ordered_data(data)
     71         quoted_string = "&".join("{0}={1}".format(k, quote_plus(v)) for k, v in unsigned_items)
     72 
     73         # 获得最终的订单信息字符串
     74         signed_string = quoted_string + "&sign=" + quote_plus(sign)
     75         return signed_string
     76 
     77     def ordered_data(self, data):
     78         complex_keys = []
     79         for key, value in data.items():
     80             if isinstance(value, dict):
     81                 complex_keys.append(key)
     82 
     83         # 将字典类型的数据dump出来
     84         for key in complex_keys:
     85             data[key] = json.dumps(data[key], separators=(',', ':'))
     86 
     87         return sorted([(k, v) for k, v in data.items()])
     88 
     89     def sign(self, unsigned_string):
     90         # 开始计算签名
     91         key = self.app_private_key
     92         signer = PKCS1_v1_5.new(key)
     93         signature = signer.sign(SHA256.new(unsigned_string))
     94         # base64 编码,转换为unicode表示并移除回车
     95         sign = encodebytes(signature).decode("utf8").replace("
    ", "")
     96         return sign
     97 
     98     def _verify(self, raw_content, signature):
     99         # 开始计算签名
    100         key = self.alipay_public_key
    101         signer = PKCS1_v1_5.new(key)
    102         digest = SHA256.new()
    103         digest.update(raw_content.encode("utf8"))
    104         if signer.verify(digest, decodebytes(signature.encode("utf8"))):
    105             return True
    106         return False
    107 
    108     def verify(self, data, signature):
    109         if "sign_type" in data:
    110             sign_type = data.pop("sign_type")
    111         # 排序后的字符串
    112         unsigned_items = self.ordered_data(data)
    113         message = "&".join(u"{}={}".format(k, v) for k, v in unsigned_items)
    114         return self._verify(message, signature)
    115 
    116 pay.py
    pay.py

    最后下载模块

    pip3 install pycryptodome

  • 相关阅读:
    三地气温的典型相关分析
    android 使用 BroadcastReceiver 总结
    发布网站问题笔记
    Android 两个Activity 实现数据的来回传递
    input 标签屏蔽谷歌浏览器高亮显示
    javascript 获取当前html 标签的位置
    c# 四舍五入
    利用SQL的charindex实现字符串数组和Split函数
    ExtJs 一些常用的控件
    C#中return、break、continue的用法
  • 原文地址:https://www.cnblogs.com/qq849784670/p/10178684.html
Copyright © 2020-2023  润新知