1.首先先创建一个简单的wxml页面,包括一个简单的form表单:
特别注意必须加上report-submit='true'
2.获取用户(要发送的用户)的openid
js代码:
/** * 生命周期函数--监听页面加载 */ onLoad: function(options) { wx.login({ success: function(res) { wx.request({ url: app.globalData.myUrl + '/ce/php/main.php',//请求的url,视自己情况而定,我用的php后台 data: { type: "openid", js_code: res.code//将js_code传到后台 }, success: function(res) { console.log(res.data.openid); wx.setStorageSync("openid", res.data.openid)//将用户openid存起来 } }) } }) }
php后台代码(请求api获取到openid):
case 'openid': $js_code = $_REQUEST["js_code"];//接收前台传来的js_code $appid = "wx084xxxxxxxxxxf6fc";//appid(需要到小程序官网上查看自己的appid和appSerect) $appSerect = "4b435xxxxxxxx5ba4bdxxxxxx3f99ee7"; $api = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$appSerect}&js_code={$js_code}&grant_type=authorization_code"; function httpGet($url) { $curl = curl_init(); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_TIMEOUT, 500); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($curl, CURLOPT_URL, $url); $res = curl_exec($curl); curl_close($curl); return $res; } $str = httpGet($api); echo $str; break;
3.获取access_token
orderSign: function(e) { console.log(e) wx.request({ url: 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx0xxxxxxxxxxxx6fc&secret=4b43xxxxxxxxxxxxxxxe3f99ee7', data: {}, success: function(res) { var openid = wx.getStorageSync("openid")//取前一步存起来的openid wx.request({ url: 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' + res.data.access_token,//获取的access_token data: { "touser": openid,//要发送的用户的openid "template_id": 'L8hCIxb9K1fQ85yAn6C5J4eAxfruNyALTG_mfE01K4U',//模版ID "form_id": e.detail.formId,//获取的formid "data": {//模版数据 "keyword1": { "value": "2018年3月26日", "color": "#173177" }, "keyword2": { "value": "扫一扫", "color": "#173177" }, "keyword3": { "value": "1000元", "color": "#173177" }, "keyword4": { "value": "测试的商户详情", "color": "#173177" }, "keyword5": { "value": "6546546846544-1w", "color": "#173177" } }, "emphasis_keyword": "keyword3.DATA"//需要放大显示的数据 }, method: 'post', header: { 'content-type': 'application/json' // 默认值 }, success: function(res) { console.log(res.data) } }) } }) }
模版id需要在小程序官网上获取:
完成这几步之后,点击提交按钮,表单提交成功后就可以成功发送模版消息!!