├── README.md
├── client
├── app.js
├── app.json
├── app.wxss
├── pages
│ ├── index
│ │ ├── index.js
│ │ ├── index.wxml
│ │ └── index.wxss
│ └── logs
│ │ ├── logs.js
│ │ ├── logs.json
│ │ ├── logs.wxml
│ │ └── logs.wxss
├── project.config.json
└── utils
│ └── util.js
└── server
└── djangoWechat
├── db.sqlite3
├── djangoWechat
├── __init__.py
├── __pycache__
│ ├── __init__.cpython-36.pyc
│ ├── settings.cpython-36.pyc
│ ├── urls.cpython-36.pyc
│ └── wsgi.cpython-36.pyc
├── settings.py
├── urls.py
└── wsgi.py
├── manage.py
├── pay
├── __init__.py
├── __pycache__
│ ├── __init__.cpython-36.pyc
│ ├── admin.cpython-36.pyc
│ ├── apps.cpython-36.pyc
│ ├── models.cpython-36.pyc
│ ├── urls.cpython-36.pyc
│ └── views.cpython-36.pyc
├── admin.py
├── apps.py
├── migrations
│ ├── __init__.py
│ └── __pycache__
│ │ └── __init__.cpython-36.pyc
├── models.py
├── tests.py
├── urls.py
└── views.py
└── requirements.txt
/README.md:
--------------------------------------------------------------------------------
1 | # django-wechat-pay
2 | 通过 Django, Django Rest Framework, [wechatpy](https://github.com/jxtech/wechatpy) 实现微信小程序端的支付功能
3 |
4 | ## 简要指南
5 |
6 | ### server 端
7 | 商户系统先调用该接口在微信支付服务后台生成预支付交易单,返回正确的预支付交易回话标识后再在APP里调起支付
8 |
9 | 克隆该项目到本地目录
10 | ```
11 | cd django-wechat-pay/server/djangoWechat/
12 | pip install -r requirements.txt
13 | python3 manage.py runserver
14 | ```
15 |
16 | #### 配置支付参数
17 | 配置文件路径:
18 | django-wechat-pay/server/djangoWechat/djangoWechat/settings.py
19 |
20 | ```
21 | # wechat config
22 | WECHAT = {
23 | 'APPID': 'appid', # 小程序ID
24 | 'APPSECRET': 'appsecret', # 小程序SECRET
25 | 'MCH_ID': 'mch_id', # 商户号
26 | 'TOTAL_FEE': '1', # 总金额
27 | 'SPBILL_CREATE_IP': '127.0.0.1', # 终端IP
28 | 'NOTIFY_URL': 'http://127.0.0.1:8000/wxpayNotify', # 通知地址
29 | 'TRADE_TYPE': 'JSAPI', # 交易类型
30 | 'MERCHANT_KEY': 'merchant_key', # 商户KEY
31 | 'BODY': '商品描述', # 商品描述
32 | }
33 | ```
34 |
35 | #### 接口地址
36 | 支付接口:http://127.0.0.1:8000/wxpay/
37 | 通知接口:http://127.0.0.1:8000/wxpayNotify
38 |
39 | ### client 端
40 | 通过微信开发者工具新建项目,将 APPID 替换成你拥有权限的 APPID 进行测试及后续开发…
41 |
42 | 暂时只提供了基本的支付演示,server 端启动成功的前提下小程序载入编译后会立即调起支付接口,使用当前开发者的微信即可支付。
43 |
44 | ## 其他
45 | 该 demo 只做了简单的支付功能,现金红包、企业付款、订单查询、退款等有空再加上…
46 |
47 | ## ONE MORE THING...
48 | 
49 |
50 |
--------------------------------------------------------------------------------
/client/app.js:
--------------------------------------------------------------------------------
1 | //app.js
2 | App({
3 | onLaunch: function () {
4 | // 展示本地存储能力
5 | var logs = wx.getStorageSync('logs') || []
6 | logs.unshift(Date.now())
7 | wx.setStorageSync('logs', logs)
8 |
9 | // 登录
10 | wx.login({
11 | success: res => {
12 | // 发送 res.code 到后台换取 openId, sessionKey, unionId
13 | console.log('临时登录凭证 code:', res)
14 | wx.request({
15 | url: 'http://127.0.0.1:8000/wxpay/',
16 | data: {
17 | code: res.code,
18 | },
19 | method: 'GET',
20 | success: function(res) {
21 | // 从后台获取支付所需的参数
22 | console.log('支付参数:', res)
23 | // 调用支付接口进行支付
24 | wx.requestPayment({
25 | timeStamp: res.data.timeStamp,
26 | nonceStr: res.data.nonceStr,
27 | package: res.data.package,
28 | signType: res.data.signType,
29 | paySign: res.data.paySign,
30 | success: function(res) {
31 | console.log('支付成功:', res)
32 | },
33 | fail: function(res) {
34 | console.log('支付失败:', res)
35 | },
36 | complete: function(res) {},
37 | })
38 | },
39 | fail: function(res) {},
40 | complete: function(res) {},
41 | })
42 | }
43 | })
44 | // 获取用户信息
45 | wx.getSetting({
46 | success: res => {
47 | if (res.authSetting['scope.userInfo']) {
48 | // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
49 | wx.getUserInfo({
50 | success: res => {
51 | // 可以将 res 发送给后台解码出 unionId
52 | this.globalData.userInfo = res.userInfo
53 |
54 | // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
55 | // 所以此处加入 callback 以防止这种情况
56 | if (this.userInfoReadyCallback) {
57 | this.userInfoReadyCallback(res)
58 | }
59 | }
60 | })
61 | }
62 | }
63 | })
64 | },
65 | globalData: {
66 | userInfo: null
67 | }
68 | })
--------------------------------------------------------------------------------
/client/app.json:
--------------------------------------------------------------------------------
1 | {
2 | "pages":[
3 | "pages/index/index",
4 | "pages/logs/logs"
5 | ],
6 | "window":{
7 | "backgroundTextStyle":"light",
8 | "navigationBarBackgroundColor": "#fff",
9 | "navigationBarTitleText": "djangoWechat",
10 | "navigationBarTextStyle":"black"
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/client/app.wxss:
--------------------------------------------------------------------------------
1 | /**app.wxss**/
2 | .container {
3 | height: 100%;
4 | display: flex;
5 | flex-direction: column;
6 | align-items: center;
7 | justify-content: space-between;
8 | padding: 200rpx 0;
9 | box-sizing: border-box;
10 | }
11 |
--------------------------------------------------------------------------------
/client/pages/index/index.js:
--------------------------------------------------------------------------------
1 | //index.js
2 | //获取应用实例
3 | const app = getApp()
4 |
5 | Page({
6 | data: {
7 | motto: 'Django wechatPay Demo',
8 | userInfo: {},
9 | hasUserInfo: false,
10 | canIUse: wx.canIUse('button.open-type.getUserInfo')
11 | },
12 | //事件处理函数
13 | bindViewTap: function() {
14 | wx.navigateTo({
15 | url: '../logs/logs'
16 | })
17 | },
18 | onLoad: function () {
19 | if (app.globalData.userInfo) {
20 | this.setData({
21 | userInfo: app.globalData.userInfo,
22 | hasUserInfo: true
23 | })
24 | } else if (this.data.canIUse){
25 | // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
26 | // 所以此处加入 callback 以防止这种情况
27 | app.userInfoReadyCallback = res => {
28 | this.setData({
29 | userInfo: res.userInfo,
30 | hasUserInfo: true
31 | })
32 | }
33 | } else {
34 | // 在没有 open-type=getUserInfo 版本的兼容处理
35 | wx.getUserInfo({
36 | success: res => {
37 | app.globalData.userInfo = res.userInfo
38 | this.setData({
39 | userInfo: res.userInfo,
40 | hasUserInfo: true
41 | })
42 | }
43 | })
44 | }
45 | },
46 | getUserInfo: function(e) {
47 | console.log(e)
48 | app.globalData.userInfo = e.detail.userInfo
49 | this.setData({
50 | userInfo: e.detail.userInfo,
51 | hasUserInfo: true
52 | })
53 | }
54 | })
55 |
--------------------------------------------------------------------------------
/client/pages/index/index.wxml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | {{userInfo.nickName}}
8 |
9 |
10 |
11 | {{motto}}
12 |
13 |
14 |
--------------------------------------------------------------------------------
/client/pages/index/index.wxss:
--------------------------------------------------------------------------------
1 | /**index.wxss**/
2 | .userinfo {
3 | display: flex;
4 | flex-direction: column;
5 | align-items: center;
6 | }
7 |
8 | .userinfo-avatar {
9 | width: 128rpx;
10 | height: 128rpx;
11 | margin: 20rpx;
12 | border-radius: 50%;
13 | }
14 |
15 | .userinfo-nickname {
16 | color: #aaa;
17 | }
18 |
19 | .usermotto {
20 | margin-top: 200px;
21 | }
--------------------------------------------------------------------------------
/client/pages/logs/logs.js:
--------------------------------------------------------------------------------
1 | //logs.js
2 | const util = require('../../utils/util.js')
3 |
4 | Page({
5 | data: {
6 | logs: []
7 | },
8 | onLoad: function () {
9 | this.setData({
10 | logs: (wx.getStorageSync('logs') || []).map(log => {
11 | return util.formatTime(new Date(log))
12 | })
13 | })
14 | }
15 | })
16 |
--------------------------------------------------------------------------------
/client/pages/logs/logs.json:
--------------------------------------------------------------------------------
1 | {
2 | "navigationBarTitleText": "查看启动日志"
3 | }
--------------------------------------------------------------------------------
/client/pages/logs/logs.wxml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | {{index + 1}}. {{log}}
5 |
6 |
7 |
--------------------------------------------------------------------------------
/client/pages/logs/logs.wxss:
--------------------------------------------------------------------------------
1 | .log-list {
2 | display: flex;
3 | flex-direction: column;
4 | padding: 40rpx;
5 | }
6 | .log-item {
7 | margin: 10rpx;
8 | }
9 |
--------------------------------------------------------------------------------
/client/project.config.json:
--------------------------------------------------------------------------------
1 | {
2 | "description": "项目配置文件。",
3 | "packOptions": {
4 | "ignore": []
5 | },
6 | "setting": {
7 | "urlCheck": false,
8 | "es6": true,
9 | "postcss": true,
10 | "minified": true,
11 | "newFeature": true
12 | },
13 | "compileType": "miniprogram",
14 | "libVersion": "2.1.1",
15 | "appid": "wxa760d6475f1bbd21",
16 | "projectname": "djangoPay",
17 | "isGameTourist": false,
18 | "condition": {
19 | "search": {
20 | "current": -1,
21 | "list": []
22 | },
23 | "conversation": {
24 | "current": -1,
25 | "list": []
26 | },
27 | "game": {
28 | "currentL": -1,
29 | "list": []
30 | },
31 | "miniprogram": {
32 | "current": -1,
33 | "list": []
34 | }
35 | }
36 | }
--------------------------------------------------------------------------------
/client/utils/util.js:
--------------------------------------------------------------------------------
1 | const formatTime = date => {
2 | const year = date.getFullYear()
3 | const month = date.getMonth() + 1
4 | const day = date.getDate()
5 | const hour = date.getHours()
6 | const minute = date.getMinutes()
7 | const second = date.getSeconds()
8 |
9 | return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
10 | }
11 |
12 | const formatNumber = n => {
13 | n = n.toString()
14 | return n[1] ? n : '0' + n
15 | }
16 |
17 | module.exports = {
18 | formatTime: formatTime
19 | }
20 |
--------------------------------------------------------------------------------
/server/djangoWechat/db.sqlite3:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mrhaoji/django-wechat-pay/0907922452f8d7783ead0be4cf190507723fe5ce/server/djangoWechat/db.sqlite3
--------------------------------------------------------------------------------
/server/djangoWechat/djangoWechat/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mrhaoji/django-wechat-pay/0907922452f8d7783ead0be4cf190507723fe5ce/server/djangoWechat/djangoWechat/__init__.py
--------------------------------------------------------------------------------
/server/djangoWechat/djangoWechat/__pycache__/__init__.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mrhaoji/django-wechat-pay/0907922452f8d7783ead0be4cf190507723fe5ce/server/djangoWechat/djangoWechat/__pycache__/__init__.cpython-36.pyc
--------------------------------------------------------------------------------
/server/djangoWechat/djangoWechat/__pycache__/settings.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mrhaoji/django-wechat-pay/0907922452f8d7783ead0be4cf190507723fe5ce/server/djangoWechat/djangoWechat/__pycache__/settings.cpython-36.pyc
--------------------------------------------------------------------------------
/server/djangoWechat/djangoWechat/__pycache__/urls.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mrhaoji/django-wechat-pay/0907922452f8d7783ead0be4cf190507723fe5ce/server/djangoWechat/djangoWechat/__pycache__/urls.cpython-36.pyc
--------------------------------------------------------------------------------
/server/djangoWechat/djangoWechat/__pycache__/wsgi.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mrhaoji/django-wechat-pay/0907922452f8d7783ead0be4cf190507723fe5ce/server/djangoWechat/djangoWechat/__pycache__/wsgi.cpython-36.pyc
--------------------------------------------------------------------------------
/server/djangoWechat/djangoWechat/settings.py:
--------------------------------------------------------------------------------
1 | """
2 | Django settings for djangoWechat project.
3 |
4 | Generated by 'django-admin startproject' using Django 2.0.5.
5 |
6 | For more information on this file, see
7 | https://docs.djangoproject.com/en/2.0/topics/settings/
8 |
9 | For the full list of settings and their values, see
10 | https://docs.djangoproject.com/en/2.0/ref/settings/
11 | """
12 |
13 | import os
14 |
15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
17 |
18 |
19 | # Quick-start development settings - unsuitable for production
20 | # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
21 |
22 | # SECURITY WARNING: keep the secret key used in production secret!
23 | SECRET_KEY = 'qi-^$le5a!_lrmfk&%2vr487pt^hqhtllm-u4cq_&z$i)zi8l!'
24 |
25 | # SECURITY WARNING: don't run with debug turned on in production!
26 | DEBUG = True
27 |
28 | ALLOWED_HOSTS = []
29 |
30 |
31 | # Application definition
32 |
33 | INSTALLED_APPS = [
34 | 'django.contrib.admin',
35 | 'django.contrib.auth',
36 | 'django.contrib.contenttypes',
37 | 'django.contrib.sessions',
38 | 'django.contrib.messages',
39 | 'django.contrib.staticfiles',
40 | 'rest_framework',
41 | 'pay.apps.PayConfig',
42 | ]
43 |
44 | MIDDLEWARE = [
45 | 'django.middleware.security.SecurityMiddleware',
46 | 'django.contrib.sessions.middleware.SessionMiddleware',
47 | 'django.middleware.common.CommonMiddleware',
48 | 'django.middleware.csrf.CsrfViewMiddleware',
49 | 'django.contrib.auth.middleware.AuthenticationMiddleware',
50 | 'django.contrib.messages.middleware.MessageMiddleware',
51 | 'django.middleware.clickjacking.XFrameOptionsMiddleware',
52 | ]
53 |
54 | ROOT_URLCONF = 'djangoWechat.urls'
55 |
56 | TEMPLATES = [
57 | {
58 | 'BACKEND': 'django.template.backends.django.DjangoTemplates',
59 | 'DIRS': [],
60 | 'APP_DIRS': True,
61 | 'OPTIONS': {
62 | 'context_processors': [
63 | 'django.template.context_processors.debug',
64 | 'django.template.context_processors.request',
65 | 'django.contrib.auth.context_processors.auth',
66 | 'django.contrib.messages.context_processors.messages',
67 | ],
68 | },
69 | },
70 | ]
71 |
72 | WSGI_APPLICATION = 'djangoWechat.wsgi.application'
73 |
74 |
75 | # Database
76 | # https://docs.djangoproject.com/en/2.0/ref/settings/#databases
77 |
78 | DATABASES = {
79 | 'default': {
80 | 'ENGINE': 'django.db.backends.sqlite3',
81 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
82 | }
83 | }
84 |
85 |
86 | # Password validation
87 | # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators
88 |
89 | AUTH_PASSWORD_VALIDATORS = [
90 | {
91 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
92 | },
93 | {
94 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
95 | },
96 | {
97 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
98 | },
99 | {
100 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
101 | },
102 | ]
103 |
104 |
105 | # Internationalization
106 | # https://docs.djangoproject.com/en/2.0/topics/i18n/
107 |
108 | LANGUAGE_CODE = 'zh-hans'
109 |
110 | TIME_ZONE = 'Asia/Shanghai'
111 |
112 | USE_I18N = True
113 |
114 | USE_L10N = True
115 |
116 | USE_TZ = True
117 |
118 |
119 | # Static files (CSS, JavaScript, Images)
120 | # https://docs.djangoproject.com/en/2.0/howto/static-files/
121 |
122 | STATIC_URL = '/static/'
123 |
124 | # wechat config
125 | WECHAT = {
126 | 'APPID': 'appid', # 小程序ID
127 | 'APPSECRET': 'appsecret', # 小程序SECRET
128 | 'MCH_ID': 'mch_id', # 商户号
129 | 'TOTAL_FEE': '1', # 总金额
130 | 'SPBILL_CREATE_IP': '127.0.0.1', # 终端IP
131 | 'NOTIFY_URL': 'http://127.0.0.1:8000/wxpayNotify', # 通知地址
132 | 'TRADE_TYPE': 'JSAPI', # 交易类型
133 | 'MERCHANT_KEY': 'merchant_key', # 商户KEY
134 | 'BODY': '商品描述', #
135 | }
--------------------------------------------------------------------------------
/server/djangoWechat/djangoWechat/urls.py:
--------------------------------------------------------------------------------
1 | """djangoWechat URL Configuration
2 |
3 | The `urlpatterns` list routes URLs to views. For more information please see:
4 | https://docs.djangoproject.com/en/2.0/topics/http/urls/
5 | Examples:
6 | Function views
7 | 1. Add an import: from my_app import views
8 | 2. Add a URL to urlpatterns: path('', views.home, name='home')
9 | Class-based views
10 | 1. Add an import: from other_app.views import Home
11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
12 | Including another URLconf
13 | 1. Import the include() function: from django.urls import include, path
14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
15 | """
16 | from django.contrib import admin
17 | from django.urls import path
18 | from django.conf.urls import url, include
19 |
20 | urlpatterns = [
21 | path('admin/', admin.site.urls),
22 | url(r'^', include('pay.urls')),
23 | ]
24 |
--------------------------------------------------------------------------------
/server/djangoWechat/djangoWechat/wsgi.py:
--------------------------------------------------------------------------------
1 | """
2 | WSGI config for djangoWechat project.
3 |
4 | It exposes the WSGI callable as a module-level variable named ``application``.
5 |
6 | For more information on this file, see
7 | https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/
8 | """
9 |
10 | import os
11 |
12 | from django.core.wsgi import get_wsgi_application
13 |
14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangoWechat.settings")
15 |
16 | application = get_wsgi_application()
17 |
--------------------------------------------------------------------------------
/server/djangoWechat/manage.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | import os
3 | import sys
4 |
5 | if __name__ == "__main__":
6 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangoWechat.settings")
7 | try:
8 | from django.core.management import execute_from_command_line
9 | except ImportError as exc:
10 | raise ImportError(
11 | "Couldn't import Django. Are you sure it's installed and "
12 | "available on your PYTHONPATH environment variable? Did you "
13 | "forget to activate a virtual environment?"
14 | ) from exc
15 | execute_from_command_line(sys.argv)
16 |
--------------------------------------------------------------------------------
/server/djangoWechat/pay/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mrhaoji/django-wechat-pay/0907922452f8d7783ead0be4cf190507723fe5ce/server/djangoWechat/pay/__init__.py
--------------------------------------------------------------------------------
/server/djangoWechat/pay/__pycache__/__init__.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mrhaoji/django-wechat-pay/0907922452f8d7783ead0be4cf190507723fe5ce/server/djangoWechat/pay/__pycache__/__init__.cpython-36.pyc
--------------------------------------------------------------------------------
/server/djangoWechat/pay/__pycache__/admin.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mrhaoji/django-wechat-pay/0907922452f8d7783ead0be4cf190507723fe5ce/server/djangoWechat/pay/__pycache__/admin.cpython-36.pyc
--------------------------------------------------------------------------------
/server/djangoWechat/pay/__pycache__/apps.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mrhaoji/django-wechat-pay/0907922452f8d7783ead0be4cf190507723fe5ce/server/djangoWechat/pay/__pycache__/apps.cpython-36.pyc
--------------------------------------------------------------------------------
/server/djangoWechat/pay/__pycache__/models.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mrhaoji/django-wechat-pay/0907922452f8d7783ead0be4cf190507723fe5ce/server/djangoWechat/pay/__pycache__/models.cpython-36.pyc
--------------------------------------------------------------------------------
/server/djangoWechat/pay/__pycache__/urls.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mrhaoji/django-wechat-pay/0907922452f8d7783ead0be4cf190507723fe5ce/server/djangoWechat/pay/__pycache__/urls.cpython-36.pyc
--------------------------------------------------------------------------------
/server/djangoWechat/pay/__pycache__/views.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mrhaoji/django-wechat-pay/0907922452f8d7783ead0be4cf190507723fe5ce/server/djangoWechat/pay/__pycache__/views.cpython-36.pyc
--------------------------------------------------------------------------------
/server/djangoWechat/pay/admin.py:
--------------------------------------------------------------------------------
1 | from django.contrib import admin
2 |
3 | # Register your models here.
4 |
--------------------------------------------------------------------------------
/server/djangoWechat/pay/apps.py:
--------------------------------------------------------------------------------
1 | from django.apps import AppConfig
2 |
3 |
4 | class PayConfig(AppConfig):
5 | name = 'pay'
6 |
--------------------------------------------------------------------------------
/server/djangoWechat/pay/migrations/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mrhaoji/django-wechat-pay/0907922452f8d7783ead0be4cf190507723fe5ce/server/djangoWechat/pay/migrations/__init__.py
--------------------------------------------------------------------------------
/server/djangoWechat/pay/migrations/__pycache__/__init__.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mrhaoji/django-wechat-pay/0907922452f8d7783ead0be4cf190507723fe5ce/server/djangoWechat/pay/migrations/__pycache__/__init__.cpython-36.pyc
--------------------------------------------------------------------------------
/server/djangoWechat/pay/models.py:
--------------------------------------------------------------------------------
1 | from django.db import models
2 |
3 | # Create your models here.
4 |
--------------------------------------------------------------------------------
/server/djangoWechat/pay/tests.py:
--------------------------------------------------------------------------------
1 | from django.test import TestCase
2 |
3 | # Create your tests here.
4 |
--------------------------------------------------------------------------------
/server/djangoWechat/pay/urls.py:
--------------------------------------------------------------------------------
1 | from django.conf.urls import url
2 | from rest_framework.urlpatterns import format_suffix_patterns
3 | from pay import views
4 |
5 | urlpatterns = [
6 | url(r'^wxpay/', views.wxpay),
7 | url(r'^wxpayNotify/', views.wxpayNotify),
8 | ]
9 |
--------------------------------------------------------------------------------
/server/djangoWechat/pay/views.py:
--------------------------------------------------------------------------------
1 | from django.shortcuts import render
2 | from rest_framework.decorators import api_view
3 | from django.http import HttpResponse, JsonResponse
4 | import requests
5 | import json
6 | from django.conf import settings
7 | from wechatpy.pay import WeChatPay
8 |
9 | def get_user_info(js_code):
10 | """
11 | 使用 临时登录凭证code 获取 session_key 和 openid 等
12 | 支付部分仅需 openid,如需其他用户信息请按微信官方开发文档自行解密
13 | """
14 | req_params = {
15 | 'appid': settings.WECHAT['APPID'],
16 | 'secret': settings.WECHAT['APPSECRET'],
17 | 'js_code': js_code,
18 | 'grant_type': 'authorization_code',
19 | }
20 | user_info = requests.get('https://api.weixin.qq.com/sns/jscode2session',
21 | params=req_params, timeout=3, verify=False)
22 | return user_info.json()
23 |
24 | @api_view(['GET', 'POST'])
25 | def wxpay(request):
26 | """
27 | 通过小程序前端 wx.login() 接口获取临时登录凭证 code
28 | 将 code 作为参数传入,调用 get_user_info() 方法获取 openid
29 | """
30 | code = request.GET.get("code", None)
31 | openid = get_user_info(code)['openid']
32 |
33 | pay = WeChatPay(settings.WECHAT['APPID'], settings.WECHAT['MERCHANT_KEY'], settings.WECHAT['MCH_ID'])
34 | order = pay.order.create(
35 | trade_type = settings.WECHAT['TRADE_TYPE'], # 交易类型,小程序取值:JSAPI
36 | body = settings.WECHAT['BODY'], # 商品描述,商品简单描述
37 | total_fee = settings.WECHAT['TOTAL_FEE'], # 标价金额,订单总金额,单位为分
38 | notify_url = settings.WECHAT['NOTIFY_URL'], # 通知地址,异步接收微信支付结果通知的回调地址,通知url必须为外网可访问的url,不能携带参数。
39 | user_id = openid # 用户标识,trade_type=JSAPI,此参数必传,用户在商户appid下的唯一标识。
40 | )
41 | wxpay_params = pay.jsapi.get_jsapi_params(order['prepay_id'])
42 |
43 | return HttpResponse(json.dumps(wxpay_params))
44 |
45 | @api_view(['GET', 'POST'])
46 | def wxpayNotify(request):
47 | _xml = request.body
48 | #拿到微信发送的xml请求 即微信支付后的回调内容
49 | xml = str(_xml, encoding="utf-8")
50 | print("xml", xml)
51 | return_dict = {}
52 | tree = et.fromstring(xml)
53 | #xml 解析
54 | return_code = tree.find("return_code").text
55 | try:
56 | if return_code == 'FAIL':
57 | # 官方发出错误
58 | return_dict['message'] = '支付失败'
59 | #return Response(return_dict, status=status.HTTP_400_BAD_REQUEST)
60 | elif return_code == 'SUCCESS':
61 | #拿到自己这次支付的 out_trade_no
62 | _out_trade_no = tree.find("out_trade_no").text
63 | #这里省略了 拿到订单号后的操作 看自己的业务需求
64 | except Exception as e:
65 | pass
66 | finally:
67 | return HttpResponse(return_dict, status=status.HTTP_200_OK)
--------------------------------------------------------------------------------
/server/djangoWechat/requirements.txt:
--------------------------------------------------------------------------------
1 | asn1crypto==0.24.0
2 | certifi==2018.4.16
3 | cffi==1.11.5
4 | chardet==3.0.4
5 | cryptography==3.3.2
6 | Django==2.2.24
7 | djangorestframework==3.11.2
8 | idna==2.7
9 | optionaldict==0.1.1
10 | pycparser==2.18
11 | python-dateutil==2.7.3
12 | pytz==2018.4
13 | requests==2.20.0
14 | six==1.11.0
15 | urllib3==1.26.5
16 | wechatpy==1.7.0
17 | xmltodict==0.11.0
18 |
--------------------------------------------------------------------------------