SoFunction
Updated on 2024-11-21

Three minutes python build paypal three-way payment

Why use three-party payments?

  Before there is no three-party payment platform, when the user initiates a payment request, the user has to go and sign with the bank (transfer), which is particularly inconvenient. In order to solve these problems, there is a three-party payment, and the three-party platform goes to complete the signing, which saves time for the user.

Flow of Alipay Payment

  Merchants get Alipay's public key, their own private key (private key encryption, public key decryption), use the private key to request Alipay, Alipay decrypts, checks the signature, and carries out the payment processing, Alipay passes the return value of the processing to the merchant, and when the payment is successful, returns to the merchant the order number, the amount, the timestamp, and other messages, and after the failure of the payment, the same to the merchant to give feedback on the results.

Configuration process

1、Get APPID

Alipay Open Platform:/

Log in to Alipay Open Platform ->Click on Console

在这里插入图片描述

Click on the sandbox (copy APPID)

在这里插入图片描述

2、Online key generation

Click Documentation, find Development Assistant, and click Online Encryption.

在这里插入图片描述

Get Private Key

在这里插入图片描述

3. Obtaining the public key

Click Apply Public Key

在这里插入图片描述

Generate public key

在这里插入图片描述

Now have the public key needed.

Alipay integration in python projects

Build Payment Classes

from datetime import datetime
from  import RSA
from  import PKCS1_v1_5
from  import SHA256
from  import quote_plus
from base64 import decodebytes, encodebytes
import json

class AliPay:
    """
    Alipay payment interface(PCend-to-end payment interface)
    """

    def __init__(self, appid, app_notify_url, app_private_key_path,
                 alipay_public_key_path, return_url, debug=False):
         = 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 = (())
        self.alipay_public_key_path = alipay_public_key_path
        with open(self.alipay_public_key_path) as fp:
            self.alipay_public_key = (())

        if debug is True:
            self.__gateway = "/"
        else:
            self.__gateway = "/"

    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",
        }

        biz_content.update(kwargs)
        data = self.build_body("", biz_content, self.return_url)
        return self.sign_data(data)

    def build_body(self, method, biz_content, return_url=None):
        data = {
            "app_id": ,
            "method": method,
            "charset": "utf-8",
            "sign_type": "RSA2",
            "timestamp": ().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):
        ("sign", None)
        unsigned_items = self.ordered_data(data)
        unsigned_string = "&".join("{0}={1}".format(k, v) for k, v in unsigned_items)
        sign = (unsigned_string.encode("utf-8"))
        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 ():
            if isinstance(value, dict):
                complex_keys.append(key)

        for key in complex_keys:
            data[key] = (data[key], separators=(',', ':'))

        return sorted([(k, v) for k, v in ()])

    def sign(self, unsigned_string):
        key = self.app_private_key
        signer = PKCS1_v1_5.new(key)
        signature = ((unsigned_string))
        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 = ()
        (raw_content.encode("utf8"))
        if (digest, decodebytes(("utf8"))):
            return True
        return False

    def verify(self, data, signature):
        if "sign_type" in data:
            ("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)

Instantiated Classes

def init_alipay():
    # Initialize Alipay
    alipay = AliPay(
        app,
        app_notify_url="Callback address",
        return_url="Callback address",
        app_private_key_path="Private key relative path",
        alipay_public_key_path="Public Key Relative Path",
        debug=True  # Payment environment
    )
    return alipay

API

async def get(self):
  
    alipay = init_alipay()
    # Pass a title # # Order number # # Order price #
    params = alipay.direct_pay("Three-way advertising platform", order_no, money)
    url = f"/?{params}"
    return (ret_json(url))

# Build a callback address for successful payment callback , in the callback address you can get the order number (out_trade_no), the amount (total_amount), timestamp (timestamp), and then process business logic.

summarize

The payment package has its own interface documentation, the above is my configuration in the python environment, you can directly use the

To this article on this three-minute python build Alipay three-way payment article is introduced to this, more related python Alipay payment content please search for my previous articles or continue to browse the following related articles I hope that you will support me in the future more!