您好,登錄后才能下訂單哦!
很多網站里都有金幣、積分之類的虛擬貨幣,獲取這些往往需要充值。那么問題來了,如何在Django中對接支付寶實現支付寶充值金幣的功能呢?網上很多資料都是電商的,那些都會帶有訂單系統之類比較復雜,而充值金幣功能不需要實現那么多功能。
效果圖如下:
現在就來實現Django對接支付寶支付功能吧!
登錄支付寶開放平臺
點擊進入螞蟻金服開放平臺https://open.alipay.com/platform/home.htm
進入支付寶沙箱環境https://openhome.alipay.com/platform/appDaily.htm?tab=info
如圖,這里是你沙箱環境的配置,左側沙箱工具有沙箱支付寶安卓版下載,沙箱賬號是你的測試賬號。
下載支付寶開放平臺開發助手
點擊打開下載鏈接
打開工具,生成密鑰,然后妥善保管好!!
保存密鑰
把剛剛那個應用公鑰2048重命名為:pub_2048.txt,把應用私鑰2048重命名為:private_2048.txt,把這兩個文件放在項目目錄下。
注意:密鑰的開始和結束一定要加上如下的字符串!!!
-----BEGIN PRIVATE KEY----- 這里粘貼里面的密鑰 -----END PRIVATE KEY-----
復制支付寶的公鑰并保存
把這段支付寶公鑰復制,重命名為alipay_key_2048.txt,保存到項目目錄中,注意加上如下字符串
-----BEGIN PRIVATE KEY----- 這里粘貼里面的密鑰 -----END PRIVATE KEY-----
設置公鑰
把剛剛的pub_2048.txt里面的字符串復制到如下:
調試支付寶支付接口
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): """ 支付寶支付接口 """ 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.import_key(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) def get_alipay_url(app_id, order_sn, order_mount): alipay = AliPay( appid=app_id, app_notify_url="http://127.0.0.1:8000/alipay/return/", app_private_key_path="../trade/keys/private_2048.txt", alipay_public_key_path="../trade/keys/alipay_key_2048.txt", # 支付寶的公鑰,驗證支付寶回傳消息使用,不是你自己的公鑰, debug=True, # 默認False, return_url="http://127.0.0.1:8000/alipay/return/" ) url = alipay.direct_pay( subject=order_sn, out_trade_no=order_sn, total_amount=order_mount, ) re_url = "https://openapi.alipaydev.com/gateway.do?{data}".format(data=url) return re_url if __name__ == "__main__": url = get_alipay_url( '2016092600597838', '201902923423436', 1.00 ) print(url)
如果輸出的url能夠打開并且使用沙箱賬號支付,說明前面的配置成功了,可以進行視圖的編寫。
設計數據庫訂單模型
from django.db import models from django.conf import settings from django.utils.encoding import python_2_unicode_compatible from questioning.utils.models import CreatedUpdatedMixin @python_2_unicode_compatible class OrderInfo(CreatedUpdatedMixin, models.Model): ''' 充值訂單詳情 ''' ORDER_STATUS = ( ('TRADE_SUCCESS', '交易支付成功'), ('TRADE_CLOSED', '未付款交易超時關閉'), ('WAIT_BUYER_PAY', '交易創建'), ('TRADE_FINISHED', '交易結束'), ('paying', '待支付'), ) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='用戶') order_sn = models.CharField(max_length=30, null=True, blank=True, unique=True, verbose_name='訂單號') trade_no = models.CharField(max_length=100, unique=True, null=True, blank=True, verbose_name='支付訂單號') pay_status = models.CharField(choices=ORDER_STATUS, max_length=40, verbose_name='訂單狀態', default='paying') order_mount = models.DecimalField(verbose_name="充值金額", max_digits=10, decimal_places=2, default=0.00) class Meta: verbose_name = "充值訂單" verbose_name_plural = verbose_name def __str__(self): return self.order_sn
注意充值的金額要設置為models.DecimalField貨幣類型
然后導入到數據庫中
視圖函數編寫
class AlipayView(LoginRequiredMixin, AuthorRequiredMixin, View): """ 支付寶支付 get方法實現支付寶return_url,如果沒有實現也無所謂,post同樣可以更新狀態 post方法實現支付寶notify_url,異步更新 支付寶返回的url如下: #http://127.0.0.1:8000/alipay/return/? # charset=utf-8& # out_trade_no=201902923423436& # method=alipay.trade.page.pay.return& # total_amount=1.00& # sign=CDBMY9NBsp4KICdQoBEVxGWobd0N8y4%2BU09stzUWwlNtLr7ZpELJdM5js20wXv%2FCPp0FGPbRW1YS9DRx0CnKJULZZMqysBUMH2FL39sS0Fgstgy1ydTs7ySXdHziJV0inI%2BDWAsebQqtjk5gQEweUstc%2B%2BnzjdgAulpvWzfJsbknS%2BqUfktSdF2ZOWGhr1CFlfsMFEDS2nzQv4K3E%2BNaeylkzUnRe9M1sjIL%2FYR0wVZ5A3OfHLPf9HzC2B8%2FLu4g7N5Vctkqp2aerDvIkN5SNmDnRGyjOt2b%2BOsLMqG4X06JSsrZT6Ln8PimsrkSOIGbj0gCqscx7BwZfmCQePlCw%3D%3D& # trade_no=2019082622001426981000041778& # auth_app_id=2016092600597838& # version=1.0&app_id=2016092600597838& # sign_type=RSA2& # seller_id=2088102177296610& # timestamp=2019-08-26+13%3A51%3A01 """ def dispatch(self, request, *args, **kwargs): self.alipay = AliPay( appid=settings.ALIPAY_APPID, app_notify_url=settings.APP_NOTIFY_URL, app_private_key_path=settings.APP_PRIVATE_KEY_PATH, alipay_public_key_path=settings.ALIPAY_PUBLIC_KEY_PATH, debug=settings.ALIPAY_DEBUG, return_url=settings.RETURN_URL ) #處理返回的url參數 callback_data = {} for key, value in request.GET.items(): callback_data[key] = value sign = callback_data.pop('sign', None) self.order_sn = callback_data.get('out_trade_no', None) #訂單號 self.trade_no = callback_data.get('trade_no', None) #支付寶訂單號 # 驗證簽名 self.verify = self.alipay.verify(callback_data, sign) return super(AlipayView, self).dispatch(request, *args, **kwargs) def get(self, request): """處理支付寶return_url返回""" if self.verify: self.deposit() #返回個人中心頁面 return redirect(reverse('users:detail', kwargs={ 'username': request.user.username })) def post(self, request): """ 處理notify_url """ if self.verify: self.deposit() return Response('success') def deposit(self): """充值操作 1.更新用戶的金幣信息 2.更新訂單狀態為交易成功 """ # 數據庫中查詢訂單記錄 order = OrderInfo.objects.get(order_sn=self.order_sn) order.trade_no = self.trade_no # 支付寶訂單號 # 把人民幣轉換成對應的金幣 rmb = order.order_mount money = convert_rmb_to_money(rmb) # 更新用戶的金幣 order.user.money += Decimal(money) order.user.save() # 訂單狀態置為交易成功 order.pay_status = 'TRADE_SUCCESS' order.save()
當用戶付款成功后,會跳轉回來,那個就是return_url,處理這個的是get方法,用來更新用戶的金幣和訂單。
以上這篇Django對接支付寶實現支付寶充值金幣功能示例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。