微信开发文档---JS-SDK说明文档:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html
自己可以先看下对应的文档,里面有介绍,主要的就是 配置js安全域名和IP白名单,前端配置wx.config,调用对应的接口;
首先需要在微信公众号中配置JS接口安全域名,路径:微信公众号->设置->公众号设置->功能设置,点击设置里面有详细的教程,根据教程操作将域名写到里面,如图:
获取开发者ID和密码,获取路径:微信公众号->开发->基本配置->公众号开发信息;配置ip白名单,如图:
下面为具体的代码展示,这里只介绍扫一扫对应的代码,展示效果有点简单,可以自行配置对应的展示效果;
前端代码,需要引入JS文件,如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>微信扫一扫</title>
<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
<script src="https://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
</head>
<body>
<div>
<input type="text" name="sn" id="codeValue"><input id="scanQRCode" value="扫一扫" type="button">
</div>
<script type="text/javascript">
$(function() {
//需要把当前页面的url地址传到后台,生成签名信息时需要使用到
var tokenUrl= location.href;
//获取签名的后台接口
var _getWechatSignUrl = '/sign';
$(document).ready(function(){
//获取签名
$.ajax({
url:_getWechatSignUrl,
data:{tokenUrl:tokenUrl},
dataType:"json",
success:function(res){
//获得签名之后传入配置中进行配置
if (res.code != 0){
alert(res.message+',请刷新重试')
return false
}
wxConfig(res.appId,res.timestamp,res.nonceStr,res.signature);
},
error: function (data) {
alert(data)
}
})
})
function wxConfig(_appId,_timestamp, _nonceStr, _signature) {
wx.config({
debug:true,// 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: _appId,// 必填,公众号的唯一标识
timestamp: _timestamp,// 必填,生成签名的时间戳
nonceStr: _nonceStr,// 必填,生成签名的随机串
signature: _signature,// 必填,签名,见附录1
jsApiList: ['checkJsApi','scanQRCode']
// 必填,需要使用的JS接口列表,所有JS接口列表见附录2
});
}
$("#scanQRCode").click(function(event){
wx.scanQRCode({
desc: 'scanQRCode desc',
needResult : 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
scanType : [ "qrCode", "barCode" ], // 可以指定扫二维码还是一维码,默认二者都有
success : function(res) {
var result = res.resultStr; // 当needResult 为 1 时,扫码返回的结果
$("#codeValue").val(result)//赋值
},
error:function(res){
alert(res)
}
});
})
});
</script>
</body>
</html>
后端代码:
views.py:
# -*- encoding:utf-8 -*-
import hashlib
from flask import request, jsonify,render_template
from app import app
from wx_method import get_token,get_jsapi_ticket,create_noncestr,create_timestamp
@app.route('/sign',methods=['GET'])
def sign():
'''
生成签名算法;
返回微信config接口注入权限验证配置参数;
'''
url = request.args.get('tokenUrl')
ok,access_token = get_token()
if not ok:
return jsonify({'code':1005,'message':'获取token失败'})
ok,jsapi_ticket = get_jsapi_ticket(access_token)
if not ok :
return jsonify({'code':1006,'message':'获取签名算法失败'})
noncestr = create_noncestr()
timestamp = create_timestamp()
string1 = "jsapi_ticket={}&noncestr={}×tamp={}&url={}".format(jsapi_ticket,noncestr,timestamp,url)
crypt = hashlib.sha1(string1.encode('utf-8'))
signature = crypt.hexdigest()
result_dict = {
"code":0,
"nonceStr":noncestr,
"timestamp":timestamp,
"signature":signature,
"appId":app_id,
"message":""
}
return jsonify(result_dict)
wx_method.py
# -*- encoding:utf-8 -*-
import uuid
import time
import requests
#app_id和secret从微信公众号中获取;获取路径:微信公众号->开发->基本配置->公众号开发信息
app_id = '微信公众号开发者ID'
secret = '微信公众号开发者密码'
grant_type = "client_credential"
def get_token():
"""
获取微信access_token;
access_token有效期为2小时,建议保存到数据库中,定时更新;
直接获取数据库中的数据.
"""
token_url = "https://api.weixin.qq.com/cgi-bin/token"
payload = {
"appid" : app_id,
"secret" : secret,
"grant_type":grant_type
}
res = requests.get(token_url,params=payload)
resp = json.loads(res.text)
if resp.get('access_token'):
return True,resp['access_token']
return False,resp
def create_noncestr():
'''
生成签名的随机串
'''
return uuid.uuid1()
def create_timestamp():
'''
生成签名的时间戳
'''
return str(int(time.time()))
def get_jsapi_ticket(access_token):
'''
获取jsapi_ticket;
jsapi_ticket是公众号用于调用微信JS接口的临时票据;
'''
url = ''
payload = {
"access_token" : access_token,
"type" : "jsapi"
}
res = requests.get(url,params=payload)
res_result = json.loads(res.text)
if res_result["errcode"] == 0:
return True,res_result['ticket']
return False,res_result
关于后端代码部分,微信文档中也有对应的demo,写的也挺不错的,是用python2写的,可以参考;
注意事项:如果在微信网页开发过程中,调用其他基础接口出现权限报粗时,可以查看前端wx.config中的jsApiList列表中是否有对应的js接口;在电脑上测试可以用微信提供的web开发工具。