赞
踩
查看源码 https://github.com/kingov/wechat_node
https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index
- 申请成功之后页面会给出appID和appsecret(用于获取access_token)
- 在填写接口配置信息的时候需要后台配合验证才能配置成功
router.get('/', function(req, res, next) {
var token = config.wechat.token
var signature = req.query.signature
var nonce = req.query.nonce
var timestamp = req.query.timestamp
var echostr = req.query.echostr
var str = [token, timestamp, nonce].sort().join('')
var sha = sha1(str)
if (sha === signature) {
res.send(echostr + '');
} else {
res.send(wong);
}
});
// 获取access_token
var url = 'https://api.weixin.qq.com/cgi-bin/token';
axios.get( url , {
params:{
grant_type:'client_credential',
appid:config.wechat.appID,
secret:config.wechat.appsecret
}
}).then((userinfo)=>{
var access_token = userinfo.data.access_token ;
});
var url = `https://api.weixin.qq.com/cgi-bin/menu/create?access_token=${access_token}`
var menu = {
"button":[
{
"type":"view", //view表示跳转
"name":"**商城",
"url":"http://***.cn/shop"
},
{
"type":"click", //表示事件
"name":"戳一下",
"key":"clickEvent" //事件的key可自定义,微信服务器会发送到指定的服务器用于识别事件做出相应回应
},
{
"name":"菜单",
"sub_button":[ //二级菜单
{
"type":"view",
"name":"搜索",
"url":"http://***.cn/shop"
},
{
"type":"click",
"name":"赞一下我们",
"key":"V1001_GOOD"
}]
}]
}
//创建菜单,发送http请求
axios.post( url ,menu,{
headers:{
'content-type':'application/x-www-form-urlencoded'
}
}).then(function(dt){
console.log( '创建菜单请求已发出' , dt.data )
})
<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[fromUser]]></FromUserName>
<CreateTime>1348831860</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[用户发送的文字内容]]></Content>
</xml>
// 响应用户发送来的消息
var xml2js=require('xml2js');
router.post('/',(req, res)=>{
var xml = ''
var json = null
req.on('data',(chunk)=>{
xml += chunk
})
req.on('end',()=>{
//将接受到的xml数据转化为json
xml2js.parseString(xml, {explicitArray : false}, function(err, json) {
var backTime = new Date().getTime(); //创建发送时间,整数
if( json.xml.MsgType == 'event' ){ //消息为事件类型
if( json.xml.EventKey == 'clickEvent' ){
res.send( getXml( json , backTime , '你戳我干啥...' ) ) //回复用户的消息
}
}else if( json.xml.MsgType == 'text' ){ //消息为文字类型
res.send( getXml( json , backTime , `你发"${json.xml.Content}"过来干啥?` ) ) //回复用户的消息
}
});
})
function getXml( json , backTime , word ){
var backXML = `
<xml>
<ToUserName><![CDATA[${json.xml.FromUserName}]]></ToUserName>
<FromUserName><![CDATA[${json.xml.ToUserName}]]></FromUserName>
<CreateTime>${backTime}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[${word}]]></Content>
</xml>
`
return backXML;
};
})
var APPID = '************'
var rui = 'http://****.cn/response'
var code = 'code'
var SCOPE = 'snsapi_userinfo' // 需要用户授权
location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${APPID}&redirect_uri=${rui}&response_type=${code}&scope=${SCOPE}&state=STATE#wechat_redirect`
// 获取用户权限后跳转到response
router.get('/response',(req,ress)=>{
// 授权成功之后跳转到response路由,携带code. 根据code拿到access_token
axios.get('https://api.weixin.qq.com/sns/oauth2/access_token',{
params:{
appid:config.wechat.appID,
secret:config.wechat.appsecret,
code:req.query.code,
grant_type:'authorization_code'
}
}).then(function(response){
// 拿到access_token和openId值
access_token = response.data.access_token
openId = response.data.openid
// 获取用户信息
axios.get( 'https://api.weixin.qq.com/sns/userinfo' , {
params:{
access_token:response.data.access_token,
openid:response.data.openid,
lang:'zh_CN'
}
}).then((userinfo)=>{
// userinfo.data.nickname
//userinfo.data.sex
//userinfo.data.province
//userinfo.data.city
ress.render('shop' , { ...userinfo.data })
});
})
})
$.ajax({
type:'get',
url:'http://***.cn/getWxConfig',
data:{ nonceStr:'getoperateaccess' , url:location.href },
dataType:'json',
success:function(data){
//开始验证
wx.config({
debug:true,
appId:data.appId,
timestamp:data.timestamp,
nonceStr:'getoperateaccess',
signature:data.signature,
jsApiList: ['onMenuShareTimeline',
'onMenuShareAppMessage',
'onMenuShareQQ',
'onMenuShareWeibo',
'onMenuShareQZone',
'scanQRCode'
]
});
wx.ready(function(){
//验证成功
点击页面按钮
$('.openCamera').on('click',function(){
//打开微信扫描二维码
wx.scanQRCode({
needResult: 0, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
scanType: ["qrCode","barCode"], // 可以指定扫二维码还是一维码,默认二者都有
success: function (res) {
}
});
})
});
wx.error(function(err){
//验证失败
})
}
})
// 获取用户权限后跳转到response路由
router.get('/response', responseShop.shop)
// 生成签名用于wx.config
router.get('/getWxConfig', (req, res) => {
var noncestr = req.query.nonceStr //前端传过来的随机字符串
var timestamp = parseInt(new Date().getTime() / 1000) + '' //获取当前时间戳, 单位秒
var url = req.query.url //获取前端页面的url, 不包括#及之后的内容
//按照微信的官方说法要将用于生成签名的noncestr timestamp url jsapi_ticket 按照ASCII码由小到大排序, 以键值对的形式
//拼接成字符串, "jsapi_ticket".charCodeAt()可查询
var str = `jsapi_ticket=${data.jsapi_ticket}&noncestr=${noncestr}×tamp=${timestamp}&url=${url}`
// 使用哈希加密成签名
var signature = sha1(str) //npm install sha1
// 返回给前端
res.json({
appId: config.wechat.appID,
signature: signature,
timestamp: timestamp,
jsapi_ticket22: data.jsapi_ticket,
noncestr: noncestr,
})
})
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。