首页 > 编程语言 >python支付宝支付

python支付宝支付

时间:2023-01-12 12:34:51浏览次数:65  
标签:alipay 支付宝 return python self url key 支付 data

支付宝开放平台: https://open.alipay.com/platform/home.htm
支付宝沙箱环境: https://openhome.alipay.com/platform/appDaily.htm?tab=info
支付宝开发者文档:https://openhome.alipay.com/developmentDocument.htm
电脑网站支付流程:https://docs.open.alipay.com/270
生成签名:https://docs.open.alipay.com/291/106103/python-alipay-adk : https://github.com/fzlee/alipay/blob/master/README.zh-hans.md

文档地址:https://docs.open.alipay.com/api

pay.py

from datetime import datetime
from Cryptodome.PublicKey import RSA
from Cryptodome.Signature import PKCS1_v1_5
from Cryptodome.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("\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)

view.py

#导入支付基类
from .pay import AliPay

#初始化阿里支付对象
def get_ali_object():
    # 沙箱环境地址:https://openhome.alipay.com/platform/appDaily.htm?tab=info
    app_id = "2016101200671995"  #  APPID (沙箱应用)

    # 支付完成后,支付偷偷向这里地址发送一个post请求,识别公网IP,如果是 192.168.20.13局域网IP ,支付宝找不到,def page2() 接收不到这个请求
    notify_url = "http://localhost:8000/api/alipayreturn"

    # 支付完成后,跳转的地址。
    return_url = "http://localhost:8000/api/alipayreturn"


    merchant_private_key_path = r"C:\Users\dujiale\Desktop\Jiale\web\keys\app_private_key.txt" # 应用私钥
    alipay_public_key_path = r"C:\Users\dujiale\Desktop\Jiale\web\keys\alipay_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



def page1(request):

    if request.method == "POST":

        # 根据当前用户的配置,生成URL,并跳转。
        money = float(request.POST.get('money'))


        alipay = get_ali_object()

        # 生成支付的url
        query_params = alipay.direct_pay(
            subject="抄的代码",  # 商品简单描述
            out_trade_no="myorder" + str(time.time()),  # 用户购买的商品订单号(每次不一样) 20180301073422891
            total_amount=money,  # 交易金额(单位: 元 保留俩位小数)
        )

        pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址(沙箱应用)

        return redirect(pay_url)
    else:
        return render(request,'page3.html')


def alipay_return(request):
    alipay = get_ali_object()
    params = request.GET.dict()
    sign = params.pop('sign', None)
    status = alipay.verify(params, sign)
    print('==================开始==================')
    print('GET验证', status)
    print('==================结束==================')
    return HttpResponse('支付成功')

标签:alipay,支付宝,return,python,self,url,key,支付,data
From: https://www.cnblogs.com/djl-0628/p/17046281.html

相关文章

  • python:海量数据集分页优化
    学过Django框架的同学,一定都使用过Django框架的Paginator分页功能,今天我们要讨论的是关于使用Paginator进行大数据集分页时,它性能的优化问题。Paginator分页下面步入正题,首......
  • python:栈的理解与应用
    如何理解“栈”?关于“栈”,我有一个非常贴切的例子,就是一摞叠在一起的盘子。我们平时放盘子的时候,都是从下往上一个一个放;取的时候,我们也是从上往下一个一个地依次取,不能从中......
  • Python:类
    太久没写Python的程序了类的内容忘记了,这里写下回忆一下1Python-类属性类有一个特殊的方法叫做构造函数,用作定义实例对象的属性,其必须被命名为__innit__()(注意其前后......
  • Python-wxauto自动发送消息或文件
    1、安装wxauto和pyautogui库,pip安装即可。pipinstallwxautopipinstallpyautogui2、登录微信 3、编写代码importtimefromwxautoimportWeChatimportpya......
  • 用python虚拟环境安装jupyter notebook
    一、安装python虚拟环境以及在虚拟环境中安装jupyter1、创建python虚拟环境,命名为py_venv-onepython-m-venvpy_venv-one2、进入并激活虚拟环境进入Scripts文件夹ac......
  • Python 包离线使用
    导出本地依赖的所有包,并下载到packages目录下piplistpipfreeze>requirements.txtpipdownload-dpackages-rrequirements.txt将packages文件夹和requireme......
  • python--操作excel表格,openpyxl模块
    简介openpyxl是一个非常强大的读写Excel2010xlsx/xlsm/xltx/xltm的Python库,简单易用,功能广泛,单元格格式/图片/表格/公式/筛选/批注/文件保护等等功能应有尽有官方......
  • python false和False
    true=Falsedefwazzup():"""假亦真时真亦假"""false=TrueorFalsedeftrue():nonlocalfals......
  • 全面了解Python的变量与基本数据类型
    (全面了解Python的变量与基本数据类型)1保留字和标识符1.1保留字保留字是Python语言中已经被赋予了特定意义的单词,写代码或开发过程中不能使用这些单词作为用户的变......
  • ubuntu下配置django+apache+mysql+mod_python+Python
    网上有N种安装方法,我都试过,没有一个最后能成功,浪费了一下午的时间,终于搞定,1.installPython最新的Ubuntu操作系统是含有Python的,可以通过Python--version查看的:lab@lab:~......