1.下載相關的庫
微信官方已經提供了方便開發者的SDK,可是使用pip方式下載:
1
|
pip install wechatpy |
2. 在項目的settings.py文件添加相關配置
1
2
3
4
5
6
7
8
9
10
11
|
WECHAT = { 'APPID' : 'appid' , # 小程序ID 'APPSECRET' : 'appsecret' , # 小程序SECRET 'MCH_ID' : 'mch_id' , # 商戶號 'TOTAL_FEE' : '1' , # 總金額, 單位為“分” 'SPBILL_CREATE_IP' : '127.0.0.1' , # 終端IP 'NOTIFY_URL' : 'http://127.0.0.1:8000/wechat/payNotify/' , # 通知地址 'TRADE_TYPE' : 'JSAPI' , # 交易類型 'MERCHANT_KEY' : 'merchant_key' , # 商戶KEY 'BODY' : '商品描述' , # 商品描述 } |
3. 給Django項目新建app
-
例如我新建的app為:
Pay
-
在settings.py文件的
INSTALLED_APPS
添加剛才新建的app
4. 編寫app/views.py:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
|
from django.http import HttpResponse import requests import json from django.conf import settings from wechatpy.pay import WeChatPay from app_base.base_viewset import BaseAPIView from rest_framework import permissions from lxml import etree as et from rest_framework import status class WeChatPayViewSet(BaseAPIView): """ 通過小程序前端 wx.login() 接口獲取臨時登錄憑證 code 將 code 作為參數傳入,調用 get_user_info() 方法獲取 openid """ def get_user_info( self , js_code): """ 使用 臨時登錄憑證code 獲取 session_key 和 openid 等 支付部分僅需 openid,如需其他用戶信息請按微信官方開發文檔自行解密 """ req_params = { 'appid' : settings.WECHAT[ 'APPID' ], 'secret' : settings.WECHAT[ 'APPSECRET' ], 'js_code' : js_code, 'grant_type' : 'authorization_code' , } user_info = requests.get( 'https://api.weixin.qq.com/sns/jscode2session' , params = req_params, timeout = 3 , verify = False ) return user_info.json() def get( self , request): code = request.GET.get( "code" , None ) openid = self .get_user_info(code)[ 'openid' ] pay = WeChatPay(settings.WECHAT[ 'APPID' ], settings.WECHAT[ 'MERCHANT_KEY' ], settings.WECHAT[ 'MCH_ID' ]) order = pay.order.create( trade_type = settings.WECHAT[ 'TRADE_TYPE' ], # 交易類型,小程序取值:JSAPI body = settings.WECHAT[ 'BODY' ], # 商品描述,商品簡單描述 total_fee = settings.WECHAT[ 'TOTAL_FEE' ], # 標價金額,訂單總金額,單位為分 notify_url = settings.WECHAT[ 'NOTIFY_URL' ], # 通知地址,異步接收微信支付結果通知的回調地址,通知url必須為外網可訪問的url,不能攜帶參數。 user_id = openid # 用戶標識,trade_type=JSAPI,此參數必傳,用戶在商戶appid下的唯一標識。 ) wxpay_params = pay.jsapi.get_jsapi_params(order[ 'prepay_id' ]) return HttpResponse(json.dumps(wxpay_params)) class WeChatPayNotifyViewSet(BaseAPIView): permission_classes = (permissions.AllowAny, ) def get( self , request): _xml = request.body # 拿到微信發送的xml請求 即微信支付后的回調內容 xml = str (_xml, encoding = "utf-8" ) print ( "xml" , xml) return_dict = {} tree = et.fromstring(xml) # xml 解析 return_code = tree.find( "return_code" ).text try : if return_code = = 'FAIL' : # 官方發出錯誤 return_dict[ 'message' ] = '支付失敗' # return Response(return_dict, status=status.HTTP_400_BAD_REQUEST) elif return_code = = 'SUCCESS' : # 拿到自己這次支付的 out_trade_no _out_trade_no = tree.find( "out_trade_no" ).text # TODO 這里省略了 拿到訂單號后的操作 看自己的業務需求 except Exception as e: pass finally : return HttpResponse(return_dict, status = status.HTTP_200_OK) |
補充一些繼承的類:
1
2
3
4
5
6
7
8
9
10
11
|
# -*- coding: utf-8 -*- from rest_framework.authentication import TokenAuthentication from rest_framework.views import APIView from rest_framework import permissions __author__ = 'JayChen' class BaseAPIView(APIView): permission_classes = (permissions.IsAuthenticated,) # authentication_classes = (TokenAuthentication,) |
5. 給Pay app添加urls.py并編寫:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
# -*- coding: utf-8 -*- __author__ = 'JayChen' from django.conf.urls import url from rest_framework.urlpatterns import format_suffix_patterns from pay import views app_name = 'pay' urlpatterns = [ # 微信小程序支付 url(r '^pay/' , views.WeChatPayViewSet.as_view(), name = 'pay' ), # 支付結果回調 url(r '^payNotify/' , views.WeChatPayNotifyViewSet.as_view(), name = 'pay_notify' ), ] |
6.在項目的urls.py添加上面新增的urls.py
1
2
3
4
5
6
7
8
9
10
11
|
from django.contrib import admin from django.urls import path, include from rest_framework_jwt.views import obtain_jwt_token urlpatterns = [ path( 'admin/' , admin.site.urls), path( 'token_auth/' , obtain_jwt_token, name = 'jwt_token' ), path( 'user/' , include( 'auth_jwt.urls' )), path( 'wechat/' , include( 'pay.urls' )), # 微信支付相關 ] |
7.調試
微信小程序登陸后會得到一個code,把這個code作為參數發送給Django項目的后端:
例如:http://0.0.0.0:8000/wechat/pay/?code=033h0P0w3ANPRU2ntl0w36HHyy1h0P08
注意:這個code每次登錄都會返回,并且只能使用一次,然后就失效。
返回的數據:
1
2
3
4
5
6
7
8
|
{ "appId" : "wx14b75285dfe1" , "timeStamp" : "1595228" , "nonceStr" : "1Wtu5lKb6T3fJLiNzc09ay2Z" , "signType" : "MD5" , "package" : "prepay_id=wx02158826854686197390000" , "paySign" : "89599A11E051D3B20FF57" } |
小程序拿到這些數據就能調起支付。
到此這篇關于Django實現微信小程序支付的文章就介紹到這了,更多相關Django實現微信小程序支付內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/weixin_42935779/article/details/108360863