小程序模板推送消息

1.在微信小程序平台选择模板

2.在小程序里面写代码发送

wxml:

<form bind:submit="testSubmit" report-submit="true">

<button formType="submit">发送模板消息</button>

</form>

js:

var formId = e.detail.formId;

var access_token1 = '';

wx.request({

url:'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=appid&secret=secret',

data: {

},

header: {

"Content-Type": "application/x-www-form-urlencoded"

},

method: "get",

success: function (res) {

console.log(res)

access_token = res.data.access_token;

console.log(res.data.access_token)

let url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' + access_token;

wx.login({

success: res => {

// 发送 res.code 到后台换取 openId, sessionKey, unionId

var that = this;

// 可以通过 wx.getSetting 先查询一下用户是否授权了 "scope.userInfo" 这个 scope

var code = res.code;//登录凭证 code获取openid只能使用一次

wx.request({

url: 'https://api.weixin.qq.com/sns/jscode2session?appid=appid&secret=secret&js_code=' + code + '&grant_type=authorization_code',

data: {},

header: {

'content-type': 'application/json'

},

success: function (res) {

var openid = res.data.openid //返回openid

console.log("openid是")

console.log(openid);

wx.request({

url: url,

data: {

'touser': openid,

'template_id': 'template_id',//微信品台的小程序推送模板id

'form_id': formId,

'page': "pages/yhh/index/index",

'data': {

"keyword1": { "value": new Date().getDate, "color": "#173177" },

"keyword2": {

"value": '一个大西瓜',

"color": "#9b9b9b"

},

"keyword3": {

"value": '1000.00',

"color": "#9b9b9b"

},

}

},

method: 'POST',

success: function (res) {

console.log(res)

console.log("发送成功")

},

fail: function (err) {

console.log('request fail ', err);

},

})

}

})

}

})

}

注意的事项

formId是页面表单发起模板推送的默认id  用e.detail.formId获取  或者是支付的pre_id

需要openid  access_token  

在微信开发者工具是不能发送的,会报formId: "the formId is a mock one"错  ,  只能在开发者工具  用远程调试机制  然后在手机端点击  然后才能获取formId,如果报openid 或者 access_token错 则要注意 access_token每次获取都不一样  并且有时效性

猜你喜欢

转载自my.oschina.net/u/3559695/blog/1823275