django實現(xiàn)支付寶支付實例講解
更新時間:2019年10月17日 15:58:12 作者:BZ易風(fēng)
在本篇文章里小編給大家整理的是一篇關(guān)于django支付寶支付的代碼實例內(nèi)容,需要的朋友們可以學(xué)習(xí)下。
安裝python-alipay-sdk
pip install python-alipay-sdk --upgrade
配置
視圖函數(shù)orders/views.py
# 訂單支付 # /order/pay from alipay import AliPay, ISVAliPay import os from django.conf import settings class OrderPayView(View): def post(self, request): '''支付頁面''' # 判斷用戶是否登錄 user = request.user if not user.is_authenticated(): return JsonResponse({'res':0, 'errmsg':'用戶尚未登錄'}) # 接收訂單id order_id = request.POST.get('order_id') # 校驗訂單id if not order_id: return JsonResponse({'res':1, 'errmsg':'無效的訂單id'}) # 查詢訂單信息 try: order = OrderInfo.objects.get(order_id=order_id, user=user, pay_method=3, order_status=1) except OrderInfo.DoesNotExist: return JsonResponse({'res':2, 'errmsg':'訂單錯誤'}) # 業(yè)務(wù)處理 使用python sdk調(diào)用支付寶的支付接口 # 支付寶信息 不能放在settings里 會報錯 alipay = AliPay( appid="2016101200665304", app_notify_url=None, # 默認(rèn)回調(diào)url 如果為空的話不能用'' 要用None # 個人私鑰 app_private_key_string=os.path.join(settings.BASE_DIR, 'apps/orders/app_private_key.pem'), # 支付寶的公鑰,驗證支付寶回傳消息使用,不是你自己的公鑰, alipay_public_key_string=os.path.join(settings.BASE_DIR, 'apps/orders/alipay_public_key.pem'), # 加密方式 sign_type="RSA2", # RSA 或者 RSA2 # 沙箱是True 正式環(huán)境是False debug=True # 默認(rèn)False ) # 調(diào)用支付接口 # 電腦網(wǎng)站支付,需要跳轉(zhuǎn)到https://openapi.alipay.com/gateway.do? + order_string 實際地址 # 沙箱地址 https://openapi.alipaydev.com/gateway.do? + order_string 沙箱地址在alipay后面加上dev total_price = order.total_price + order.transit_price # Decimal order_string = alipay.api_alipay_trade_page_pay( out_trade_no=order_id, # 訂單id total_amount=str(total_price), # 支付總金額 因為Decimal格式不能序列化 所以先轉(zhuǎn)成字符串 subject='天天生鮮%s'%order_id, return_url=None, notify_url=None # 可選, 不填則使用默認(rèn)notify url ) # 返回應(yīng)答 pay_url = 'https://openapi.alipaydev.com/gateway.do?' + order_string return JsonResponse({'res':3, 'pay_url':pay_url})
配置路由urls.py
from django.conf.urls import url from orders.views import OrderPlaceView, OrderCommitView, OrderPayView urlpatterns = [ url(r'^place$', OrderPlaceView.as_view(), name='place'), # 提交訂單頁面 url(r'^commit$', OrderCommitView.as_view(), name='commit'), # 提交訂單處理 url(r'^pay$', OrderPayView.as_view(), name='pay'), # 訂單支付 ]
以上就是本次介紹的相關(guān)知識點以及實例代碼,更多內(nèi)容可以參考腳本之家相關(guān)欄目。
相關(guān)文章
Python HTTP下載文件并顯示下載進(jìn)度條功能的實現(xiàn)
這篇文章主要介紹了Python HTTP下載文件并顯示下載進(jìn)度條功能,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-04-04樹莓派(python)與arduino串口通信的詳細(xì)步驟
這篇文章主要介紹了樹莓派(python)與arduino串口通信的詳細(xì)步驟,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-11-11Python批量寫入ES索引數(shù)據(jù)的示例代碼
這篇文章主要為大家詳細(xì)介紹了如何使用python腳本批量寫ES數(shù)據(jù)(需要使用pip提前下載安裝es依賴庫),感興趣的小伙伴可以學(xué)習(xí)一下2024-02-02