python 微信开发入门篇-调用JS SDK 含微信支付

Posted 汪丛兴

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 微信开发入门篇-调用JS SDK 含微信支付相关的知识,希望对你有一定的参考价值。

  本节完成微信js sdk + 微信支付调用,项目基础部分请参照入门篇第一章:https://www.cnblogs.com/wangcongxing/p/11546780.html

  1.微信服务号设置

     登录服务号后台设置如下:

   1.登录地址:https://mp.weixin.qq.com/

   2.设置-->公众号设置-->功能设置

   设置后结果如下

    

  2.微信商户后台设置

   登录微信支付平台设置如下:

   1.登录地址(因为需要安装exe插件, 设置浏览为兼容模式  建议使用QQ浏览器):https://pay.weixin.qq.com  

    

   2.账户中心-->账户设置-->API安全

    

    

   3.产品中心-->开发配置  设置支付授权目录

    
    

    3.产品中心-->APPID授权管理 

    

  3.演示页面如下

  扫码或识别二维码在线查看案例

  

  

  转发效果如下图

支付效果:

  4.案例源码

   案例目录结构如下

    

    源码部分

路由源码 urls.py

from django.contrib import admin
from django.urls import path
from app import views

urlpatterns = [
    path(\'admin/\', admin.site.urls),
    # 微信认证文件建议使用nginx配置
    path(\'MP_verify_b1reLtO1xRzEjqxJ.txt\', views.wechatauth),
    # 微信登录页面userinfo
    path(\'userinfo\', views.userinfo),

    # 微信JS SDK 接口调用
    path(\'wxjssdk/\', views.wxjssdk),
    path(\'get_signature\', views.jsapi_signature),
    path(\'log\', views.log),
]

视图源码  views.py

from wechatpy.oauth import WeChatOAuth
from django.shortcuts import render, redirect
from django.http import JsonResponse, HttpResponse, HttpResponseRedirect
import time

from django.conf import settings
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render
import uuid
from wechatpy import WeChatClient
import os
import json
from wechatpy import WeChatPay
from wechatpy.pay import dict_to_xml


# Create your views here.

# 公众号id
AppID = "AppID "
# 公众号AppSecret
AppSecret = "AppSecret"

# 商户id
MCH_ID = \'商户号\'
# 商户API秘钥
API_KEY = \'API KET\'
# 接收微信支付异步通知回调地址
notify_url = "http://i157422s94.iok.la/wxjssdk/"


# 微信认证文件,建议通过nginx配置
def wechatauth(request):
    return HttpResponse("b1reLtO1xRzEjqxJ")


# 定义授权装饰器

def getWeChatOAuth(redirect_url):
    return WeChatOAuth(AppID, AppSecret, redirect_url, \'snsapi_userinfo\')


def oauth(method):
    def warpper(request):
        if request.session.get(\'user_info\', None) is None:
            code = request.GET.get(\'code\', None)
            wechat_oauth = getWeChatOAuth(request.get_raw_uri())
            url = wechat_oauth.authorize_url
            print(url)
            if code:
                try:
                    wechat_oauth.fetch_access_token(code)
                    user_info = wechat_oauth.get_user_info()
                    print(user_info)
                except Exception as e:
                    print(str(e))
                    # 这里需要处理请求里包含的 code 无效的情况
                    # abort(403)
                else:
                    # 建议存储在用户表
                    request.session[\'user_info\'] = user_info
            else:
                return redirect(url)

        return method(request)

    return warpper


# 获取用户信息UserInfo

@oauth
def userinfo(request):
    user_info = request.session.get(\'user_info\')
    return render(request, \'userinfo.html\', {"user_info": user_info})


# 微信JS SDK调用
@oauth
def wxjssdk(request):
    user_info = request.session.get(\'user_info\')
    trade_type = "JSAPI"
    body = "商品描述"
    total_fee = "100"
    notify_url = "http://i157422s94.iok.la/notify_url/"
    user_id = user_info["openid"]
    wechatPay = WeChatPay(
        appid=AppID,
        api_key=API_KEY,
        mch_id=MCH_ID,
    )

    order = wechatPay.order.create(trade_type, body, total_fee, notify_url, user_id=user_id)
    wxpay_params = wechatPay.jsapi.get_jsapi_params(order[\'prepay_id\'])

    print(wxpay_params)
    return render(request, \'index.html\', {"wxpay_params": wxpay_params})


@csrf_exempt
def jsapi_signature(request):
    noncestr = uuid.uuid4()
    timestamp = int(time.time())
    url = request.POST[\'url\']

    client = WeChatClient(AppID, AppSecret)
    ticket_response = client.jsapi.get_ticket()
    signature = client.jsapi.get_jsapi_signature(
        noncestr,
        ticket_response[\'ticket\'],
        timestamp,
        url
    )
    ret_dict = {
        \'noncestr\': noncestr,
        \'timestamp\': timestamp,
        \'url\': url,
        \'signature\': signature,
    }
    return JsonResponse(ret_dict)


def log(request):
    print(\'Hello World!\')
    return JsonResponse({
        \'status\': \'ok\',
    })

templates-->index.html 源码

<!doctype html>
<html>
<head>
   <title>微信JS-SDK Demo</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0">
    <style type="text/css">
      html {
  -ms-text-size-adjust: 100%;
  -webkit-text-size-adjust: 100%;
  -webkit-user-select: none;
  user-select: none;
}
body {
  line-height: 1.6;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  background-color: #f1f0f6;
}
* {
  margin: 0;
  padding: 0;
}
button {
  font-family: inherit;
  font-size: 100%;
  margin: 0;
  *font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}
ul,
ol {
  padding-left: 0;
  list-style-type: none;
}
a {
  text-decoration: none;
}
.label_box {
  background-color: #ffffff;
}
.label_item {
  padding-left: 15px;
}
.label_inner {
  padding-top: 10px;
  padding-bottom: 10px;
  min-height: 24px;
  position: relative;
}
.label_inner:before {
  content: " ";
  position: absolute;
  left: 0;
  top: 0;
  width: 200%;
  height: 1px;
  border-top: 1px solid #ededed;
  -webkit-transform-origin: 0 0;
  transform-origin: 0 0;
  -webkit-transform: scale(0.5);
  transform: scale(0.5);
  top: auto;
  bottom: -2px;
}
.lbox_close {
  position: relative;
}
.lbox_close:before {
  content: " ";
  position: absolute;
  left: 0;
  top: 0;
  width: 200%;
  height: 1px;
  border-top: 1px solid #ededed;
  -webkit-transform-origin: 0 0;
  transform-origin: 0 0;
  -webkit-transform: scale(0.5);
  transform: scale(0.5);
}
.lbox_close:after {
  content: " ";
  position: absolute;
  left: 0;
  top: 0;
  width: 200%;
  height: 1px;
  border-top: 1px solid #ededed;
  -webkit-transform-origin: 0 0;
  transform-origin: 0 0;
  -webkit-transform: scale(0.5);
  transform: scale(0.5);
  top: auto;
  bottom: -2px;
}
.lbox_close .label_item:last-child .label_inner:before {
  display: none;
}
.btn {
  display: block;
  margin-left: auto;
  margin-right: auto;
  padding-left: 14px;
  padding-right: 14px;
  font-size: 18px;
  text-align: center;
  text-decoration: none;
  overflow: visible;
  /*.btn_h(@btnHeight);*/
  height: 42px;
  border-radius: 5px;
  -moz-border-radius: 5px;
  -webkit-border-radius: 5px;
  box-sizing: border-box;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  color: #ffffff;
  line-height: 42px;
  -webkit-tap-highlight-color: rgba(255, 255, 255, 0);
}
.btn.btn_inline {
  display: inline-block;
}
.btn_primary {
  background-color: #04be02;
}
.btn_primary:not(.btn_disabled):visited {
  color: #ffffff;
}
.btn_primary:not(.btn_disabled):active {
  color: rgba(255, 255, 255, 0.9);
  background-color: #039702;
}
button.btn {
  width: 100%;
  border: 0;
  outline: 0;
  -webkit-appearance: none;
}
button.btn:focus {
  outline: 0;
}
.wxapi_container {
  font-size: 16px;
}
h1 {
  font-size: 14px;
  font-weight: 400;
  line-height: 2em;
  padding-left: 15px;
  color: #8d8c92;
}
.desc {
  font-size: 14px;
  font-weight: 

以上是关于python 微信开发入门篇-调用JS SDK 含微信支付的主要内容,如果未能解决你的问题,请参考以下文章

PHP微信公众平台开发高级篇—微信JS-SDK

微信小程序开发之入门篇(熟悉项目结构)

26-ESP8266 SDK开发基础入门篇--编写WIFI模块 SmartConfig/Airkiss 一键配网

.Net微信网页开发之使用微信JS-SDK调用微信扫一扫功能

微信公众号开发纪要-调用微信扫一扫功能

微信js-sdk调用