Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to build Alipay Tripartite payment in python

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article will explain in detail how to build Alipay tripartite payment in python. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

Why use tripartite payment?

Before there is no tripartite payment platform in   , when a user initiates a payment request, the user has to sign a contract with the bank (transfer money), which is particularly inconvenient. In order to solve these problems, there is a tripartite payment platform to complete the contract, which saves users time.

The process of Alipay payment

   merchants get Alipay's public key and their own private key (private key encryption, public key decryption) and request Alipay with the private key. Alipay decrypts, verifies signatures, and carries out payment processing. Alipay sends the returned value to the merchant. When the payment is successful, it returns the merchant's order number, amount, time stamp and other information. After the payment fails, it also gives the merchant feedback results.

Configuration process 1. Get APPID

Alipay open platform: https://open.alipay.com/

Log in to Alipay Open platform-> Click the console

Click on the sandbox (copy APPID)

2. Generate keys online

Click on the document, find the development assistant, and click online encryption.

Get the private key

3. Obtain the public key

Click apply Public key

Generate public key

Now we have the required public key.

Integration of Alipay in python Project

Build payment class

From datetime import datetimefrom Crypto.PublicKey import RSAfrom Crypto.Signature import PKCS1_v1_5from Crypto.Hash import SHA256from urllib.parse import quote_plusfrom base64 import decodebytes, encodebytesimport jsonclass AliPay: "" Alipay init__ (PC side payment API) "" 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" } 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")) 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) 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)) 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: 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)

Instantiated class

Def init_alipay (): # initialization Alipay alipay = AliPay (appid= "appid", 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 () # send a title order number order price params = alipay.direct_pay ("Tripartite Advertising platform", order_no, money) url = f "https://openapi.alipaydev.com/gateway.do?{params}" return self.write (ret_json (url)) # build a callback address for callback after successful payment You can get the order number (out_trade_no), amount (total_amount) and time stamp (timestamp) in the callback address, and then process the business logic. This is the end of this article on "how to build Alipay tripartite payment in python". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it out for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report