一、介紹
基於網上一個支付寶pay.py封裝了支付寶API的文件進行的,以下代碼只支持網頁掃碼支付,手機端會提示調用支付寶支付
#pay文件代碼 from datetime import datetime from Crypto.PublicKey import RSA from Crypto.Signature import PKCS1_v1_5 from Crypto.Hash import SHA256 from urllib.parse import quote_plus 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.AlipayAPI.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)
二、自己封裝的調用代碼
import time from pay import AliPay class AlipayApi(object): def __init__(self, app_id, notify_url, return_url, merchant_private_key_path, alipay_public_key_path,debug): """ :param app_id: :param notify_url:支付寶post回調地址,用來修改訂單信息 :param return_url:支付寶get回調地址,用來給用戶展示 :param merchant_private_key_path:商戶的私鑰 :param alipay_public_key_path:支付寶的公鑰 """ self.app_id = app_id self.notify_url = notify_url self.return_url = return_url self.merchant_private_key_path = merchant_private_key_path self.alipay_public_key_path = alipay_public_key_path self.debug=debug self.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=debug, # 默認False, ) def getAlipayPage(self,subject,total_amount,out_trade_no,): """ :param subject: 商品簡單描述 :param total_amount: 交易總金額(單位: 元 保留倆位小數) :param out_trade_no: 商戶訂單號 :return: 支付寶支付頁面 """ query_params = self.alipay.direct_pay( subject=subject, out_trade_no=out_trade_no, total_amount=total_amount, ) if self.debug: pay_url = "https://openapi.alipaydev.com/gateway.do?{}".format(query_params) else: pay_url = "https://openapi.alipay.com/gateway.do?{}".format(query_params) return pay_url def alipayCallbackPost(self,body_str): """ :param body_str: post回調的數據 :return: """ from urllib.parse import parse_qs post_data = parse_qs(body_str) post_dict = {} for k, v in post_data.items(): post_dict[k] = v[0] # 做二次驗證 sign = post_dict.pop('sign', None) # 通過調用alipay的verify方法去認證 status = self.alipay.verify(post_dict, sign) if status: # 修改自己訂單狀態 return True else: return False def alipayCallbackGet(self,params): """ :param params: get回調的數據 :return: """ dic_params = {k: v for k, v in params.items()} sign = dic_params.pop('sign', None) status = self.alipay.verify(dic_params, sign) if status: return True else: return False if __name__ == '__main__': app_id = "填寫自己的" notify_url = "填寫自己的" return_url = "填寫自己的" merchant_private_key_path = "app_private_2048.txt" alipay_public_key_path = "alipay_public_2048.txt" ali=AlipayApi(app_id=app_id, notify_url=notify_url, return_url=return_url, merchant_private_key_path=merchant_private_key_path, alipay_public_key_path=alipay_public_key_path, debug=True) subject="充氣娃娃" out_trade_no="OFG"+str(time.time()) total_amount=1000 url=ali.getAlipayPage(subject=subject,out_trade_no=out_trade_no,total_amount=total_amount) print(url)
key文件的格式
效果圖