您好,登錄后才能下訂單哦!
本篇文章為大家展示了使用Django怎么調用支付寶接口,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
支付寶支付
正式環境:用營業執照,申請商戶號,appid
測試環境:沙箱環境:https://openhome.alipay.com/platform/appDaily.htm?tab=info
支付寶提供接口:給商戶使用,收錢
-Java,php,C#的demo,沒有python的demo
-git有人封裝了
-需要安裝模塊:pip3 install
-應用私鑰---自己保存,一定不能丟
-應用公鑰---給別人用
-支付寶公鑰---支付寶用的
-生成公鑰私鑰:https://docs.open.alipay.com/291/105971
-把應用公鑰配置在支付寶上:應用公鑰,配置完成以后,支付寶自動生成一個支付寶公鑰
-在程序中:配置應用私鑰,支付寶公鑰
-如果支付成功,支付寶會回調,但是如果你的服務器掛掉了怎么辦?
-支付寶24小時以內不定時再給你發,你修改掉訂單狀態即可
-支付成功,支付寶會有一個get回調,一個post回調:修改訂單狀態
支付寶接口
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.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)
視圖函數
from django.shortcuts import render, redirect, HttpResponse from utils.pay import AliPay import json import time def ali(): # 沙箱環境地址:https://openhome.alipay.com/platform/appDaily.htm?tab=info app_id = "2016092000554611" # 支付寶收到用戶的支付,會向商戶發兩個請求,一個get請求,一個post請求 # POST請求,用于最后的檢測 notify_url = "http://42.56.89.12:80/page2/" # GET請求,用于頁面的跳轉展示 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" # 生成一個AliPay的對象 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 == "GET": return render(request, 'page1.html') else: money = float(request.POST.get('money')) # 生成一個對象 alipay = ali() # 生成支付的url # 對象調用direct_pay query_params = alipay.direct_pay( subject="充氣娃娃", # 商品簡單描述 out_trade_no="x2" + str(time.time()), # 商戶訂單號 total_amount=money, # 交易金額(單位: 元 保留倆位小數) ) pay_url = "https://openapi.alipaydev.com/gateway.do?{}".format(query_params) print(pay_url) # 朝這個地址發get請求 return redirect(pay_url) def page2(request): alipay = ali() if request.method == "POST": # 檢測是否支付成功 # 去請求體中獲取所有返回的數據:狀態/訂單號 from urllib.parse import parse_qs body_str = request.body.decode('utf-8') print(body_str) post_data = parse_qs(body_str) print('支付寶給我的數據:::---------',post_data) post_dict = {} for k, v in post_data.items(): post_dict[k] = v[0] print('轉完之后的字典',post_dict) sign = post_dict.pop('sign', None) status = alipay.verify(post_dict, sign) print('POST驗證', status) return HttpResponse('POST返回') else: params = request.GET.dict() sign = params.pop('sign', None) status = alipay.verify(params, sign) print('GET驗證', status) return HttpResponse('支付成功')
上述內容就是使用Django怎么調用支付寶接口,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。