Alipay payment
Formal environment: business license, apply for a merchant number, appid
Test environment: Sandbox environment./platform/?tab=info
Alipay provides interface: for merchants to use, collect money
- -Java, php, C# demos, no python demos.
- -git Someone wrapped the
- -Required to install the module:pip3 install
- -Apply the private key - keep it for yourself, don't lose it!
- -Apply the public key - for others to use
- -Paypal public key - for paypal
- -Generate public key private key:/291/105971
- -application public key configuration in Alipay: application public key, after the completion of the configuration, Alipay automatically generate an Alipay public key
- -In the program: configure the application private key, paypal public key
- -If the payment is successful, Alipay will call back, but what if your server hangs?
- -Alipay within 24 hours from time to time to send you, you modify the order status can be
- -payment success, Alipay will have a get callback, a post callback: modify the status of the order
Alipay interface
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(object): """ 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", # "qr_pay_mode":4 } 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) # Sorted strings 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")) # ordered_items = self.ordered_data(data) quoted_string = "&".join("{0}={1}".format(k, quote_plus(v)) for k, v in unsigned_items) # Get the final order information string 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) # Dump out the dictionary type data for key in complex_keys: data[key] = (data[key], separators=(',', ':')) return sorted([(k, v) for k, v in ()]) def sign(self, unsigned_string): # Start counting signatures key = self.app_private_key signer = PKCS1_v1_5.new(key) signature = ((unsigned_string)) # base64 encoding, convert to unicode and remove carriage return sign = encodebytes(signature).decode("utf8").replace("\n", "") return sign def _verify(self, raw_content, signature): # Start counting signatures 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 = ("sign_type") # Sorted strings unsigned_items = self.ordered_data(data) message = "&".join(u"{}={}".format(k, v) for k, v in unsigned_items) return self._verify(message, signature)
view function
from import render, redirect, HttpResponse from import AliPay import json import time def ali(): # Sandbox environment address: /platform/?tab=info app_id = "2016092000554611" # Alipay receives the user's payment, will be sent to the merchant two requests, a get request, a post request # POST requests for final detection notify_url = "http://42.56.89.12:80/page2/" # GET requests for page jump displays return_url = "http://42.56.89.12:80/page2/" merchant_private_key_path = "keys/app_private_2048.txt" alipay_public_key_path = "keys/alipay_public_2048.txt" # Generate an AliPay object 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, # Alipay's public key, used to authenticate Alipay's return messages, not your own public key debug=True, # False by default, # ) return alipay def page1(request): if == "GET": return render(request, '') else: money = float(('money')) # Generate an object alipay = ali() # generate payment url # object calls direct_pay query_params = alipay.direct_pay( subject="Inflatables.", # A brief description of the product out_trade_no="x2" + str(()), # Merchant Order Number total_amount=money, # Transaction amount (in dollars) Retain two decimal places. ) pay_url = "/?{}".format(query_params) print(pay_url) # Send a get request to this address return redirect(pay_url) def page2(request): alipay = ali() if == "POST": # Detect if payment was successful # Go to the request body and get all the returned data: status/order number from import parse_qs body_str = ('utf-8') print(body_str) post_data = parse_qs(body_str) print('Paypal gave me the data:::---------',post_data) post_dict = {} for k, v in post_data.items(): post_dict[k] = v[0] print('Dictionary after spinning',post_dict) sign = post_dict.pop('sign', None) status = (post_dict, sign) print('POST validation', status) return HttpResponse('POST return') else: params = () sign = ('sign', None) status = (params, sign) print('GET Validation', status) return HttpResponse('Payment successful')
This is the whole content of this article.