码迷,mamicode.com
首页 > 微信 > 详细

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

时间:2019-10-15 11:40:04      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:dmi   inner   同步   location   ppi   通过   back   nsf   开启   

  本章节完成微信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: 400;
  line-height: 2em;
  color: #8d8c92;
}
.wxapi_index_item a {
  display: block;
  color: #3e3e3e;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
.wxapi_form {
  background-color: #ffffff;
  padding: 0 15px;
  margin-top: 30px;
  padding-bottom: 15px;
}
h3 {
  padding-top: 16px;
  margin-top: 25px;
  font-size: 16px;
  font-weight: 400;
  color: #3e3e3e;
  position: relative;
}
h3:first-child {
  padding-top: 15px;
}
h3: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);
}
.btn {
  margin-bottom: 15px;
}


  </style>
</head>
<body>
<div class="wxapi_container">
    <div class="wxapi_index_container">
      <ul class="label_box lbox_close wxapi_index_list">
        <li class="label_item wxapi_index_item"><a class="label_inner" href="#menu-basic">基础接口</a></li>
        <li class="label_item wxapi_index_item"><a class="label_inner" href="#menu-share">分享接口</a></li>
        <li class="label_item wxapi_index_item"><a class="label_inner" href="#menu-image">图像接口</a></li>
        <li class="label_item wxapi_index_item"><a class="label_inner" href="#menu-voice">音频接口</a></li>
        <li class="label_item wxapi_index_item"><a class="label_inner" href="#menu-smart">智能接口</a></li>
        <li class="label_item wxapi_index_item"><a class="label_inner" href="#menu-device">设备信息接口</a></li>
        <li class="label_item wxapi_index_item"><a class="label_inner" href="#menu-location">地理位置接口</a></li>
        <li class="label_item wxapi_index_item"><a class="label_inner" href="#menu-webview">界面操作接口</a></li>
        <li class="label_item wxapi_index_item"><a class="label_inner" href="#menu-scan">微信扫一扫接口</a></li>
        <li class="label_item wxapi_index_item"><a class="label_inner" href="#menu-shopping">微信小店接口</a></li>
        <li class="label_item wxapi_index_item"><a class="label_inner" href="#menu-card">微信卡券接口</a></li>
        <li class="label_item wxapi_index_item"><a class="label_inner" href="#menu-pay">微信支付接口</a></li>
      </ul>
    </div>
    <div class="lbox_close wxapi_form">
      <h3 id="menu-basic">基础接口</h3>
      <span class="desc">判断当前客户端是否支持指定JS接口</span>
      <button class="btn btn_primary" id="checkJsApi">checkJsApi</button>

      <h3 id="menu-share">分享接口</h3>
      <span class="desc">获取“分享到朋友圈”按钮点击状态及自定义分享内容接口</span>
      <button class="btn btn_primary" id="onMenuShareTimeline">onMenuShareTimeline</button>
      <span class="desc">获取“分享给朋友”按钮点击状态及自定义分享内容接口</span>
      <button class="btn btn_primary" id="onMenuShareAppMessage">onMenuShareAppMessage</button>
      <span class="desc">获取“分享到QQ”按钮点击状态及自定义分享内容接口</span>
      <button class="btn btn_primary" id="onMenuShareQQ">onMenuShareQQ</button>
      <span class="desc">获取“分享到腾讯微博”按钮点击状态及自定义分享内容接口</span>
      <button class="btn btn_primary" id="onMenuShareWeibo">onMenuShareWeibo</button>
      <span class="desc">获取“分享到QZone”按钮点击状态及自定义分享内容接口</span>
      <button class="btn btn_primary" id="onMenuShareQZone">onMenuShareQZone</button>

      <h3 id="menu-image">图像接口</h3>
      <span class="desc">拍照或从手机相册中选图接口</span>
      <button class="btn btn_primary" id="chooseImage">chooseImage</button>
      <span class="desc">预览图片接口</span>
      <button class="btn btn_primary" id="previewImage">previewImage</button>
      <span class="desc">上传图片接口</span>
      <button class="btn btn_primary" id="uploadImage">uploadImage</button>
      <span class="desc">下载图片接口</span>
      <button class="btn btn_primary" id="downloadImage">downloadImage</button>

      <h3 id="menu-voice">音频接口</h3>
      <span class="desc">开始录音接口</span>
      <button class="btn btn_primary" id="startRecord">startRecord</button>
      <span class="desc">停止录音接口</span>
      <button class="btn btn_primary" id="stopRecord">stopRecord</button>
      <span class="desc">播放语音接口</span>
      <button class="btn btn_primary" id="playVoice">playVoice</button>
      <span class="desc">暂停播放接口</span>
      <button class="btn btn_primary" id="pauseVoice">pauseVoice</button>
      <span class="desc">停止播放接口</span>
      <button class="btn btn_primary" id="stopVoice">stopVoice</button>
      <span class="desc">上传语音接口</span>
      <button class="btn btn_primary" id="uploadVoice">uploadVoice</button>
      <span class="desc">下载语音接口</span>
      <button class="btn btn_primary" id="downloadVoice">downloadVoice</button>

      <h3 id="menu-smart">智能接口</h3>
      <span class="desc">识别音频并返回识别结果接口</span>
      <button class="btn btn_primary" id="translateVoice">translateVoice</button>

      <h3 id="menu-device">设备信息接口</h3>
      <span class="desc">获取网络状态接口</span>
      <button class="btn btn_primary" id="getNetworkType">getNetworkType</button>

      <h3 id="menu-location">地理位置接口</h3>
      <span class="desc">使用微信内置地图查看位置接口</span>
      <button class="btn btn_primary" id="openLocation">openLocation</button>
      <span class="desc">获取地理位置接口</span>
      <button class="btn btn_primary" id="getLocation">getLocation</button>

      <h3 id="menu-webview">界面操作接口</h3>
      <span class="desc">隐藏右上角菜单接口</span>
      <button class="btn btn_primary" id="hideOptionMenu">hideOptionMenu</button>
      <span class="desc">显示右上角菜单接口</span>
      <button class="btn btn_primary" id="showOptionMenu">showOptionMenu</button>
      <span class="desc">关闭当前网页窗口接口</span>
      <button class="btn btn_primary" id="closeWindow">closeWindow</button>
      <span class="desc">批量隐藏功能按钮接口</span>
      <button class="btn btn_primary" id="hideMenuItems">hideMenuItems</button>
      <span class="desc">批量显示功能按钮接口</span>
      <button class="btn btn_primary" id="showMenuItems">showMenuItems</button>
      <span class="desc">隐藏所有非基础按钮接口</span>
      <button class="btn btn_primary" id="hideAllNonBaseMenuItem">hideAllNonBaseMenuItem</button>
      <span class="desc">显示所有功能按钮接口</span>
      <button class="btn btn_primary" id="showAllNonBaseMenuItem">showAllNonBaseMenuItem</button>

      <h3 id="menu-scan">微信扫一扫</h3>
      <span class="desc">调起微信扫一扫接口</span>
      <button class="btn btn_primary" id="scanQRCode0">scanQRCode(微信处理结果)</button>
      <button class="btn btn_primary" id="scanQRCode1">scanQRCode(直接返回结果)</button>

      <h3 id="menu-shopping">微信小店接口</h3>
      <span class="desc">跳转微信商品页接口</span>
      <button class="btn btn_primary" id="openProductSpecificView">openProductSpecificView</button>

      <h3 id="menu-card">微信卡券接口</h3>
      <span class="desc">批量添加卡券接口</span>
      <button class="btn btn_primary" id="addCard">addCard</button>
      <span class="desc">调起适用于门店的卡券列表并获取用户选择列表</span>
      <button class="btn btn_primary" id="chooseCard">chooseCard</button>
      <span class="desc">查看微信卡包中的卡券接口</span>
      <button class="btn btn_primary" id="openCard">openCard</button>

      <h3 id="menu-pay">微信支付接口</h3>
      <span class="desc">发起一个微信支付请求</span>
      <button class="btn btn_primary" id="chooseWXPay">chooseWXPay</button>
    </div>
  </div>
<script src="https://www.szyfd.xyz/static/HOME/style/js/jquery-1.7.2.js"></script>

<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script type="text/javascript">
    (function (window, $) {
        var fInitWeixin = function (d) {
            wx.config({
                debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
                appId: wx975992a7ef6d6c9d, // 必填,公众号的唯一标识
                timestamp: d.timestamp, // 必填,生成签名的时间戳
                nonceStr: d.noncestr, // 必填,生成签名的随机串
                signature: d.signature,// 必填,签名,见附录1
                jsApiList: [checkJsApi,
                    onMenuShareTimeline,
                    onMenuShareAppMessage,
                    onMenuShareQQ,
                    onMenuShareWeibo,
                    onMenuShareQZone,
                    hideMenuItems,
                    showMenuItems,
                    hideAllNonBaseMenuItem,
                    showAllNonBaseMenuItem,
                    translateVoice,
                    startRecord,
                    stopRecord,
                    onVoiceRecordEnd,
                    playVoice,
                    onVoicePlayEnd,
                    pauseVoice,
                    stopVoice,
                    uploadVoice,
                    downloadVoice,
                    chooseImage,
                    previewImage,
                    uploadImage,
                    downloadImage,
                    getNetworkType,
                    openLocation,
                    getLocation,
                    hideOptionMenu,
                    showOptionMenu,
                    closeWindow,
                    scanQRCode,
                    chooseWXPay,
                    openProductSpecificView,
                    addCard,
                    chooseCard,
                    openCard] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
            });
        }
        $.ajax({
            type: post,
            url: /get_signature,
            dataType: json,
            data: {url: location.href},
            success: function (d) {
                fInitWeixin(d)
            }
        })
    })(window, jQuery)
</script>

<script type="text/javascript">

    /*
 * 注意:
 * 1. 所有的JS接口只能在公众号绑定的域名下调用,公众号开发者需要先登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”。
 * 2. 如果发现在 Android 不能分享自定义内容,请到官网下载最新的包覆盖安装,Android 自定义分享接口需升级至 6.0.2.58 版本及以上。
 * 3. 完整 JS-SDK 文档地址:http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html
 *
 * 如有问题请通过以下渠道反馈:
 * 邮箱地址:weixin-open@qq.com
 * 邮件主题:【微信JS-SDK反馈】具体问题
 * 邮件内容说明:用简明的语言描述问题所在,并交代清楚遇到该问题的场景,可附上截屏图片,微信团队会尽快处理你的反馈。
 */
    wx.ready(function () {
        // 1 判断当前版本是否支持指定 JS 接口,支持批量判断
        document.querySelector(#checkJsApi).onclick = function () {
            wx.checkJsApi({
                jsApiList: [
                    getNetworkType,
                    previewImage
                ],
                success: function (res) {
                    alert(JSON.stringify(res));
                }
            });
        };




        // 3 智能接口
        var voice = {
            localId: ‘‘,
            serverId: ‘‘
        };
        // 3.1 识别音频并返回识别结果
        document.querySelector(#translateVoice).onclick = function () {
            if (voice.localId == ‘‘) {
                alert(请先使用 startRecord 接口录制一段声音);
                return;
            }
            wx.translateVoice({
                localId: voice.localId,
                complete: function (res) {
                    if (res.hasOwnProperty(translateResult)) {
                        alert(识别结果: + res.translateResult);
                    } else {
                        alert(无法识别);
                    }
                }
            });
        };

        // 4 音频接口
        // 4.2 开始录音
        document.querySelector(#startRecord).onclick = function () {
            wx.startRecord({
                cancel: function () {
                    alert(用户拒绝授权录音);
                }
            });
        };

        // 4.3 停止录音
        document.querySelector(#stopRecord).onclick = function () {
            wx.stopRecord({
                success: function (res) {
                    voice.localId = res.localId;
                },
                fail: function (res) {
                    alert(JSON.stringify(res));
                }
            });
        };

        // 4.4 监听录音自动停止
        wx.onVoiceRecordEnd({
            complete: function (res) {
                voice.localId = res.localId;
                alert(录音时间已超过一分钟);
            }
        });

        // 4.5 播放音频
        document.querySelector(#playVoice).onclick = function () {
            if (voice.localId == ‘‘) {
                alert(请先使用 startRecord 接口录制一段声音);
                return;
            }
            wx.playVoice({
                localId: voice.localId
            });
        };

        // 4.6 暂停播放音频
        document.querySelector(#pauseVoice).onclick = function () {
            wx.pauseVoice({
                localId: voice.localId
            });
        };

        // 4.7 停止播放音频
        document.querySelector(#stopVoice).onclick = function () {
            wx.stopVoice({
                localId: voice.localId
            });
        };

        // 4.8 监听录音播放停止
        wx.onVoicePlayEnd({
            complete: function (res) {
                alert(录音( + res.localId + )播放结束);
            }
        });

        // 4.8 上传语音
        document.querySelector(#uploadVoice).onclick = function () {
            if (voice.localId == ‘‘) {
                alert(请先使用 startRecord 接口录制一段声音);
                return;
            }
            wx.uploadVoice({
                localId: voice.localId,
                success: function (res) {
                    alert(上传语音成功,serverId 为 + res.serverId);
                    voice.serverId = res.serverId;
                }
            });
        };

        // 4.9 下载语音
        document.querySelector(#downloadVoice).onclick = function () {
            if (voice.serverId == ‘‘) {
                alert(请先使用 uploadVoice 上传声音);
                return;
            }
            wx.downloadVoice({
                serverId: voice.serverId,
                success: function (res) {
                    alert(下载语音成功,localId 为 + res.localId);
                    voice.localId = res.localId;
                }
            });
        };

        // 5 图片接口
        // 5.1 拍照、本地选图
        var images = {
            localId: [],
            serverId: []
        };
        document.querySelector(#chooseImage).onclick = function () {
            wx.chooseImage({
                success: function (res) {
                    images.localId = res.localIds;
                    alert(已选择  + res.localIds.length +  张图片);
                }
            });
        };

        // 5.2 图片预览
        document.querySelector(#previewImage).onclick = function () {
            wx.previewImage({
                current: http://img5.douban.com/view/photo/photo/public/p1353993776.jpg,
                urls: [
                    http://img3.douban.com/view/photo/photo/public/p2152117150.jpg,
                    http://img5.douban.com/view/photo/photo/public/p1353993776.jpg,
                    http://img3.douban.com/view/photo/photo/public/p2152134700.jpg
                ]
            });
        };

        // 5.3 上传图片
        document.querySelector(#uploadImage).onclick = function () {
            if (images.localId.length == 0) {
                alert(请先使用 chooseImage 接口选择图片);
                return;
            }
            var i = 0, length = images.localId.length;
            images.serverId = [];

            function upload() {
                wx.uploadImage({
                    localId: images.localId[i],
                    success: function (res) {
                        i++;
                        //alert(‘已上传:‘ + i + ‘/‘ + length);
                        images.serverId.push(res.serverId);
                        if (i < length) {
                            upload();
                        }
                    },
                    fail: function (res) {
                        alert(JSON.stringify(res));
                    }
                });
            }

            upload();
        };

        // 5.4 下载图片
        document.querySelector(#downloadImage).onclick = function () {
            if (images.serverId.length === 0) {
                alert(请先使用 uploadImage 上传图片);
                return;
            }
            var i = 0, length = images.serverId.length;
            images.localId = [];

            function download() {
                wx.downloadImage({
                    serverId: images.serverId[i],
                    success: function (res) {
                        i++;
                        alert(已下载: + i + / + length);
                        images.localId.push(res.localId);
                        if (i < length) {
                            download();
                        }
                    }
                });
            }

            download();
        };

        // 6 设备信息接口
        // 6.1 获取当前网络状态
        document.querySelector(#getNetworkType).onclick = function () {
            wx.getNetworkType({
                success: function (res) {
                    alert(res.networkType);
                },
                fail: function (res) {
                    alert(JSON.stringify(res));
                }
            });
        };

        // 7 地理位置接口
        // 7.1 查看地理位置
        document.querySelector(#openLocation).onclick = function () {
            wx.openLocation({
                latitude: 23.099994,
                longitude: 113.324520,
                name: TIT 创意园,
                address: 广州市海珠区,
                scale: 14,
                infoUrl: https://www.szyfd.xyz
            });
        };

        // 7.2 获取当前地理位置
        document.querySelector(#getLocation).onclick = function () {
            wx.getLocation({
                success: function (res) {
                    alert(JSON.stringify(res));
                },
                cancel: function (res) {
                    alert(用户拒绝授权获取地理位置);
                }
            });
        };

        // 8 界面操作接口
        // 8.1 隐藏右上角菜单
        document.querySelector(#hideOptionMenu).onclick = function () {
            wx.hideOptionMenu();
        };

        // 8.2 显示右上角菜单
        document.querySelector(#showOptionMenu).onclick = function () {
            wx.showOptionMenu();
        };

        // 8.3 批量隐藏菜单项
        document.querySelector(#hideMenuItems).onclick = function () {
            wx.hideMenuItems({
                menuList: [
                    menuItem:readMode, // 阅读模式
                    menuItem:share:timeline, // 分享到朋友圈
                    menuItem:copyUrl // 复制链接
                ],
                success: function (res) {
                    alert(已隐藏“阅读模式”,“分享到朋友圈”,“复制链接”等按钮);
                },
                fail: function (res) {
                    alert(JSON.stringify(res));
                }
            });
        };

        // 8.4 批量显示菜单项
        document.querySelector(#showMenuItems).onclick = function () {
            wx.showMenuItems({
                menuList: [
                    menuItem:readMode, // 阅读模式
                    menuItem:share:timeline, // 分享到朋友圈
                    menuItem:copyUrl // 复制链接
                ],
                success: function (res) {
                    alert(已显示“阅读模式”,“分享到朋友圈”,“复制链接”等按钮);
                },
                fail: function (res) {
                    alert(JSON.stringify(res));
                }
            });
        };

        // 8.5 隐藏所有非基本菜单项
        document.querySelector(#hideAllNonBaseMenuItem).onclick = function () {
            wx.hideAllNonBaseMenuItem({
                success: function () {
                    alert(已隐藏所有非基本菜单项);
                }
            });
        };

        // 8.6 显示所有被隐藏的非基本菜单项
        document.querySelector(#showAllNonBaseMenuItem).onclick = function () {
            wx.showAllNonBaseMenuItem({
                success: function () {
                    alert(已显示所有非基本菜单项);
                }
            });
        };

        // 8.7 关闭当前窗口
        document.querySelector(#closeWindow).onclick = function () {
            wx.closeWindow();
        };

        // 9 微信原生接口
        // 9.1.1 扫描二维码并返回结果
        document.querySelector(#scanQRCode0).onclick = function () {
            wx.scanQRCode();
        };
        // 9.1.2 扫描二维码并返回结果
        document.querySelector(#scanQRCode1).onclick = function () {
            wx.scanQRCode({
                needResult: 1,
                desc: scanQRCode desc,
                success: function (res) {
                    alert(JSON.stringify(res));
                }
            });
        };

        // 10 微信支付接口
        // 10.1 发起一个支付请求
        document.querySelector(#chooseWXPay).onclick = function () {
            // 注意:此 Demo 使用 2.7 版本支付接口实现,建议使用此接口时参考微信支付相关最新文档。
            wx.chooseWXPay({
                timestamp: {{ wxpay_params.timeStamp }},
                nonceStr: {{ wxpay_params.nonceStr }},
                package: {{ wxpay_params.package }},
                signType: {{ wxpay_params.signType }}, // 注意:新版支付接口使用 MD5 加密
                paySign: {{ wxpay_params.paySign }}
            });
        };

        // 11.3  跳转微信商品页
        document.querySelector(#openProductSpecificView).onclick = function () {
            wx.openProductSpecificView({
                productId: pDF3iY_m2M7EQ5EKKKWd95kAxfNw,
                extInfo: 123
            });
        };

        // 12 微信卡券接口
        // 12.1 添加卡券
        document.querySelector(#addCard).onclick = function () {
            wx.addCard({
                cardList: [
                    {
                        cardId: pDF3iY9tv9zCGCj4jTXFOo1DxHdo,
                        cardExt: {"code": "", "openid": "", "timestamp": "1418301401", "signature":"f54dae85e7807cc9525ccc127b4796e021f05b33"}
                    },
                    {
                        cardId: pDF3iY9tv9zCGCj4jTXFOo1DxHdo,
                        cardExt: {"code": "", "openid": "", "timestamp": "1418301401", "signature":"f54dae85e7807cc9525ccc127b4796e021f05b33"}
                    }
                ],
                success: function (res) {
                    alert(已添加卡券: + JSON.stringify(res.cardList));
                }
            });
        };

        var codes = [];
        // 12.2 选择卡券
        document.querySelector(#chooseCard).onclick = function () {
            wx.chooseCard({
                cardSign: 8ef8aa071f1d2186cb1355ec132fed04ebba1c3f,
                timestamp: 1437997723,
                nonceStr: k0hGdSXKZEj3Min5,
                success: function (res) {
                    res.cardList = JSON.parse(res.cardList);
                    encrypt_code = res.cardList[0][encrypt_code];
                    alert(已选择卡券: + JSON.stringify(res.cardList));
                    decryptCode(encrypt_code, function (code) {
                        codes.push(code);
                    });
                }
            });
        };

        // 12.3 查看卡券
        document.querySelector(#openCard).onclick = function () {
            if (codes.length < 1) {
                alert(请先使用 chooseCard 接口选择卡券。);
                return false;
            }
            var cardList = [];
            for (var i = 0; i < codes.length; i++) {
                cardList.push({
                    cardId: pDF3iY9tv9zCGCj4jTXFOo1DxHdo,
                    code: codes[i]
                });
            }
            wx.openCard({
                cardList: cardList
            });
        };
        shareData = {
            title: 深圳易方达软件,
            desc: 按时交付完美主义者,
            link: location.href,
            imgUrl: https://www.szyfd.xyz/static/HOME/style/images/shareLogo.png,
            trigger: function (res) {
                // 不要尝试在trigger中使用ajax异步请求修改本次分享的内容,因为客户端分享操作是一个同步操作,这时候使用ajax的回包会还没有返回

            },
            success: function (res) {

            },
            cancel: function (res) {

            },
            fail: function (res) {
                //alert(JSON.stringify(res));
            }
        }
        // 2. 分享接口

        wx.onMenuShareAppMessage(shareData);

        wx.onMenuShareTimeline(shareData);

        wx.onMenuShareQQ(shareData);

        wx.onMenuShareWeibo(shareData);

        wx.onMenuShareQZone(shareData);

        function decryptCode(code, callback) {
            $.getJSON(/jssdk/decrypt_code.php?code= + encodeURI(code), function (res) {
                if (res.errcode == 0) {
                    codes.push(res.code);
                }
            });
        }
    });

    wx.error(function (res) {
        alert(res.errMsg);
    });


</script>
</body>
</html>

 

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

标签:dmi   inner   同步   location   ppi   通过   back   nsf   开启   

原文地址:https://www.cnblogs.com/wangcongxing/p/11665901.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!