本篇文章為大家展示了使用Django怎么調(diào)用支付寶接口,內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過(guò)這篇文章的詳細(xì)介紹希望你能有所收獲。
成都創(chuàng)新互聯(lián)是專(zhuān)業(yè)的都江堰網(wǎng)站建設(shè)公司,都江堰接單;提供成都網(wǎng)站設(shè)計(jì)、做網(wǎng)站,網(wǎng)頁(yè)設(shè)計(jì),網(wǎng)站設(shè)計(jì),建網(wǎng)站,PHP網(wǎng)站建設(shè)等專(zhuān)業(yè)做網(wǎng)站服務(wù);采用PHP框架,可快速的進(jìn)行都江堰網(wǎng)站開(kāi)發(fā)網(wǎng)頁(yè)制作和功能擴(kuò)展;專(zhuān)業(yè)做搜索引擎喜愛(ài)的網(wǎng)站,專(zhuān)業(yè)的做網(wǎng)站團(tuán)隊(duì),希望更多企業(yè)前來(lái)合作!支付寶支付
正式環(huán)境:用營(yíng)業(yè)執(zhí)照,申請(qǐng)商戶(hù)號(hào),appid
測(cè)試環(huán)境:沙箱環(huán)境:https://openhome.alipay.com/platform/appDaily.htm?tab=info
支付寶提供接口:給商戶(hù)使用,收錢(qián)
-Java,php,C#的demo,沒(méi)有python的demo
-git有人封裝了
-需要安裝模塊:pip3 install
-應(yīng)用私鑰---自己保存,一定不能丟
-應(yīng)用公鑰---給別人用
-支付寶公鑰---支付寶用的
-生成公鑰私鑰:https://docs.open.alipay.com/291/105971
-把應(yīng)用公鑰配置在支付寶上:應(yīng)用公鑰,配置完成以后,支付寶自動(dòng)生成一個(gè)支付寶公鑰
-在程序中:配置應(yīng)用私鑰,支付寶公鑰
-如果支付成功,支付寶會(huì)回調(diào),但是如果你的服務(wù)器掛掉了怎么辦?
-支付寶24小時(shí)以?xún)?nèi)不定時(shí)再給你發(fā),你修改掉訂單狀態(tài)即可
-支付成功,支付寶會(huì)有一個(gè)get回調(diào),一個(gè)post回調(diào):修改訂單狀態(tài)
支付寶接口
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) # 將字典類(lèi)型的數(shù)據(jù)dump出來(lái) 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): # 開(kāi)始計(jì)算簽名 key = self.app_private_key signer = PKCS1_v1_5.new(key) signature = signer.sign(SHA256.new(unsigned_string)) # base64 編碼,轉(zhuǎn)換為unicode表示并移除回車(chē) sign = encodebytes(signature).decode("utf8").replace("\n", "") return sign def _verify(self, raw_content, signature): # 開(kāi)始計(jì)算簽名 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)
視圖函數(shù)
from django.shortcuts import render, redirect, HttpResponse from utils.pay import AliPay import json import time def ali(): # 沙箱環(huán)境地址:https://openhome.alipay.com/platform/appDaily.htm?tab=info app_id = "2016092000554611" # 支付寶收到用戶(hù)的支付,會(huì)向商戶(hù)發(fā)兩個(gè)請(qǐng)求,一個(gè)get請(qǐng)求,一個(gè)post請(qǐng)求 # POST請(qǐng)求,用于最后的檢測(cè) notify_url = "http://42.56.89.12:80/page2/" # GET請(qǐng)求,用于頁(yè)面的跳轉(zhuǎn)展示 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" # 生成一個(gè)AliPay的對(duì)象 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, # 支付寶的公鑰,驗(yàn)證支付寶回傳消息使用,不是你自己的公鑰 debug=True, # 默認(rèn)False, ) return alipay def page1(request): if request.method == "GET": return render(request, 'page1.html') else: money = float(request.POST.get('money')) # 生成一個(gè)對(duì)象 alipay = ali() # 生成支付的url # 對(duì)象調(diào)用direct_pay query_params = alipay.direct_pay( subject="充氣娃娃", # 商品簡(jiǎn)單描述 out_trade_no="x2" + str(time.time()), # 商戶(hù)訂單號(hào) total_amount=money, # 交易金額(單位: 元 保留倆位小數(shù)) ) pay_url = "https://openapi.alipaydev.com/gateway.do?{}".format(query_params) print(pay_url) # 朝這個(gè)地址發(fā)get請(qǐng)求 return redirect(pay_url) def page2(request): alipay = ali() if request.method == "POST": # 檢測(cè)是否支付成功 # 去請(qǐng)求體中獲取所有返回的數(shù)據(jù):狀態(tài)/訂單號(hào) from urllib.parse import parse_qs body_str = request.body.decode('utf-8') print(body_str) post_data = parse_qs(body_str) print('支付寶給我的數(shù)據(jù):::---------',post_data) post_dict = {} for k, v in post_data.items(): post_dict[k] = v[0] print('轉(zhuǎn)完之后的字典',post_dict) sign = post_dict.pop('sign', None) status = alipay.verify(post_dict, sign) print('POST驗(yàn)證', status) return HttpResponse('POST返回') else: params = request.GET.dict() sign = params.pop('sign', None) status = alipay.verify(params, sign) print('GET驗(yàn)證', status) return HttpResponse('支付成功')
上述內(nèi)容就是使用Django怎么調(diào)用支付寶接口,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。