一:前期准备:

  1. 首先你需要一台服务器,:阿里云或者腾讯云啥的,最便宜的可以选择类似阿里云这种轻量级服务器,和域名配置好A记录。
  2. 需要在服务器打架node环境:可以找客服帮忙基本配置环境搭好。
  3. 需要有一个自己的公众号:官方详见文档

二:配置

  1. 公众号配置:IP白名单:为服务器IP地址。
    img1

  2. 公众号配置:JS接口安全域名。
    img3

node后端JS代码:

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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
var express = require('express'); //node的一个框架 就是相当于jquery
var path = require('path');
var request = require('request');
var ejs = require('ejs'); // 后台模板库
var wechat = require('wechat'); //第三方处理微信推送的库
var https = require('https'); // node 端 请求别的服务的模块
var sign = require('sign'); //微信提供的签名工具

const stringRandom = require('string-random')
const crypto = require('crypto')

var app = express();
app.use("*", function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");

// if (req.method === 'OPTIONS') {
// res.send(200)
// } else {
// next()
// }
next()
});

const getSha1 = function(str) {

var sha1 = crypto.createHash("sha1"); //定义加密方式:md5不可逆,此处的md5可以换成任意hash加密的方法名称;
sha1.update(str);
var res = sha1.digest("hex"); //加密后的值d
return res;
};

const getSignature = function(nowUrl,key){
let noncestr = stringRandom(16,{numbers:false})
let timestamp = new Date().getTime()
let jsapi_ticket = `jsapi_ticket=${key}&noncestr=${noncestr}&timestamp=${timestamp}&url=${nowUrl}`;

let signature = getSha1(jsapi_ticket)
return {
noncestr,
timestamp,
signature
}

}

app.set('views', './views');
app.engine('.html', ejs.__express);
app.set('view engine', 'html');
app.use(express.static('./'));

//发送请求

app.get('/index', function(req, res) {
console.log('this is index')
res.render('index');
});

//处理URL 验证的 微信服务器要通过get请求来测试的

app.get('/weixin', wechat('wechat', function(req, res, next) {
console.log('true');
}));

//处理后台获取签名的请求

app.post('/getSignature', function(req, res) {
let nowurl = req.headers['referer']
console.log(nowurl)
console.log('this is getSignature')
var token = 'wechat',
appsecret = '', //你申请的
APPID = '', //你申请的id
url = '' //JS接口安全域名 参与签名用的
Res = res;

//发送https get请求 获取 access_token;l

https.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APPID + "&secret=" + appsecret, function(res) {
var datas = [];
var size = 0;
res.on('data', function(data) {
datas.push(data);
size += data.length;
});

res.on("end", function() {
var buff = Buffer.concat(datas, size);
var result = buff.toString();
//console.log(JSON.parse(result).access_token);

// 获取 jsapi_ticket //异步嵌套是不合理的 不推荐这样 使用promise

https.get('https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' + JSON.parse(result).access_token + '&type=jsapi', function(res) {

var datas = [];
var size = 0;
res.on('data', function(data) {
datas.push(data);
size += data.length;
});

res.on('end', function() {
var buff = Buffer.concat(datas, size);
var rlt = buff.toString();
let resultData = getSignature(nowurl,JSON.parse(rlt).ticket)
rlt = Object.assign(JSON.parse(rlt),resultData)
// var config = sign(JSON.parse(rlt).ticket, url);
// console.log(111,config)
Res.json(rlt);
});

}).on('error', function(e) {
console.log("Got error: " + e.message);
})
});
}).on('error', function(e) {
console.log("Got error: " + e.message);
});

});

var server = app.listen(80, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});

前端代码:

  1. 先设置wx.config
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    this.$post("/getSignature", {}).then(config => {
    console.log(config)
    // config = JSON.parse(config);
    if (config != undefined && config != null) {
    wx.config({
    debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
    appId: '', // 必填,appID公众号的唯一标识
    timestamp: config.timestamp, // 必填,生成签名的时间戳
    nonceStr: config.noncestr, // 必填,生成签名的随机串
    signature: config.signature,// 必填,签名,见附录1
    jsApiList: ['getLocation', 'scanQRCode', 'closeWindow', 'checkJsApi', 'startRecord', 'stopRecord', 'translateVoice', 'openCard','chooseImage']

    // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
    });
    // alert('配置成功!');
    }
    });
  2. 在调取微信接口
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    wx.ready(function () {
    wx.getLocation({
    type: 'wgs84', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
    success: function (res) {
    var latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90
    var longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180。
    var speed = res.speed; // 速度,以米/每秒计
    var accuracy = res.accuracy; // 位置精度
    console.log(latitude,longitude,speed,accuracy)
    alert(latitude,longitude,speed,accuracy)
    }
    });
    wx.scanQRCode({
    needResult: 0, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
    scanType: ["qrCode","barCode"], // 可以指定扫二维码还是一维码,默认二者都有
    success: function (res) {
    var result = res.resultStr; // 当needResult 为 1 时,扫码返回的结果
    alert(result);
    }
    });
    })