使用API
wx.request
但有一些前提条件要知道
一、access_token:取得方法
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={secret}
二、Openid取得方法
先使用
wx.login
API 得到js_code
再请求
https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={AppSecret}&grant_type=authorization_code&js_code={login方法得到的jscode}
得到某个用户的openid
三、发送消息
https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={access_token}
JSON参数中
form_id:一定要这个放到一个form中
四、模板ID
小程序 的模板消息管理页中
show me the code
index.js
Page({
data: {
motto: 'Hello World',
userInfo: {},
hasUserInfo: false,
userOpenID:'',
canIUse: wx.canIUse('button.open-type.getUserInfo')
},
testSubmit: function (e) {
var self = this;
let _access_token = '10_KpTN5ba0iXKFNRuA3mNRRAyNvBy6jpMs3ai2azJU1dxJ8hGIxTWnI2pw56WSYiVLxpgYBJy8cD--ZZ2IBcLN4uLziXoD2cFtBwJSfHwyE9kYFBnKqz6fwQvCqe7XWYD9JkKQVd5X4yg9iXDbYVGgAHAHEP';
let url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' + _access_token
;
console.log("e.detail.formId: " + e.detail.formId);
let _jsonData = {
access_token: _access_token,
touser: 'orsUR0fn2kGG8UdvfW8jLl6z5vWc',
template_id: 'tvYE1nsU_oOrJoZRRJD5AhDRFuxGBC7Cc0SuEjY9XGo',
form_id: e.detail.formId,
page: "pages/index/index",
data: {
"keyword1": { "value": "测试数据一", "color": "#173177" },
"keyword2": { "value": "测试数据二", "color": "#173177" },
}
}
wx.request({
url: url,
data: _jsonData,
method: 'POST',
success: function (res) {
console.log(res)
},
fail: function (err) {
console.log('request fail ', err);
},
complete: function (res) {
console.log("request completed!");
}
})
},
onLoad: function () {
wx.login({
success: function (res) {
if (res.code) {
console.log(res.code);
} else {
console.log('登录失败!' + res.errMsg)
}
}
});
if (app.globalData.userInfo) {
this.setData({
userInfo: app.globalData.userInfo,
hasUserInfo: true
})
} else if (this.data.canIUse){
app.userInfoReadyCallback = res => {
this.setData({
userInfo: res.userInfo,
hasUserInfo: true
})
}
} else {
// 在没有 open-type=getUserInfo 版本的兼容处理
wx.getUserInfo({
success: res => {
app.globalData.userInfo = res.userInfo
this.setData({
userInfo: res.userInfo,
hasUserInfo: true
})
}
})
}
}
})
index.wxml