微信小程序发送模板消息详细教程
最近做了正在做一个微信小程序,在其中遇到了的一个难点,就是这个微信小程序的模板消息的发送,这个东西对于初学者的我来说,可是让我费了不少事,好了废话不多说,上干货!!
在这里我先附上我的相关学习视频(B站上好东西还不少):添加链接描述 一个忠告:你可以看着视频,同时结合这边文章,对你的代码进行修改
大家先来看一下这个功能的实际流程:不求看懂,只用知道我的大致流程基本就是按照这个来做的
首先第一步:获取openid(微信用户身份的证明)
在登陆的时候,或者在登陆后自己设置一个选项(按钮 或者view随意),让用户来触发事件
js代码:
wx.login({
success: res => {
// 发送 res.code 到后台换取 openId, sessionKey, unionId
wx.request({
url: '自己的服务器相关文件的URL',
method: "POST",
data: {
code: res.code,
},
header: {
"content-type": "application/x-www-form-urlencoded;charset=utf-8"
},
success: res1 => {
var openid = res1.data.openid;}})}})
这里就来看看后台文件的相关代码:其中的appid与secret可以在微信公众品台上面找到,httpGet函数不用动直接调用就可以了
<?php
$code = $_POST["code"];
$appid="。。。。。";
$secret="。。。。。";
$api="https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$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,true);
curl_setopt($curl,CURLOPT_URL,$url);
$res=curl_exec($curl);
curl_close($curl);
return $res;
}
$str=httpGet($api);
echo $str;
?>
这样就可以在前台上面获取到用户或者自己的openid,这时候你可以把其存入到数据库里面,或者可是直接使用(这样的等同于给自己发了一条微信消息)
第二步:就是选择自己想要的消息模板
在微信公众平台上面,有一个模板消息板块,在哪里你可以添加你所需要的消息模板,当然了在里面你也可以自己申请适合自己的字段(但是或许字段已满,不会让你申请)
第三步:那就是正式发送微信模板消息
首先获取formid,及其要使用的信息,之后查询数据库,找到你想要的给谁发微信消息的openid,之后再次请求自己的服务器,把相应的数据传输过去(formid openid 还有微信模板上面你所需要的信息)让服务器来请求微信的服务器,来发送这个模板消息
设置按钮,来触发form事件,如果涉及到多按钮提交,你可以看看我这篇文章,或许对你有所帮助 添加链接描述
wxml代码:
<form bindsubmit="clickFormView" report-submit="true" class="form-view">
<view></view>
.....
<button class="end_submit" form-type="submit">提交</button>
</form>
js代码:
var formid = e.detail.formId;//这个必须要,微信公众号要求
var values = e.detail.value;
var name = values.input.split("+")[0];
var style = values.input.split("+")[1];
var kecheng = values.input.split("+")[2];//这几个是你传递的信息,需要你自己来获取,在微信开发者工具里面,你可以使用console.log来打印出来所有信息,选用你最需要的信息就可以了
var openids = "";
//查询数据库获取你所需要的openid
wx.request({
url: '.....',
method: "POST",
data: {//这里面的数据库看你的后台代码了
sql: "select openid from wx_openid where tea_id='20190804100' or tea_id='" + app.globalData.userInfo['username'] + "'",
type: 'select',
fetch_type: 'assoc'//assoc字段索引,num数字索引
},
header: {
"content-type": "application/x-www-form-urlencoded;charset=utf-8"
},
success: res => {
openids = res.data;
for (var a in openids) {
if (openids[a]['openid'] == "") continue;
wx.request({
url: '后台模板URL',
method: "POST",
data: {
name: name,
time: time,
style: style,
kecheng: kecheng,
formid: formid,
openid: openids[a]['openid'],
},
header: {
"content-type": "application/x-www-form-urlencoded;charset=utf-8"
},
success: res1 => {
console.log("ok");
} }) }} })
最后在来看看后台代码(只是其中之一):在这里把微信公众平台相应的模板id给复制到这个代码的变量templateid
还有在这里面记得 结尾END 前面不要加空格,不然会报错
<?php
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,true);
curl_setopt($curl,CURLOPT_URL,$url);
$res=curl_exec($curl);
curl_close($curl);
return $res;
}
function httpPost($data,$url){
$curl=curl_init();
curl_setopt($curl,CURLOPT_URL,$url);
curl_setopt($curl,CURLOPT_CUSTOMREQUEST,'POST');
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,false);
curl_setopt($curl,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows NT 10.0; WOW64)');
curl_setopt($curl,CURLOPT_FOLLOWLOCATION,1);
curl_setopt($curl,CURLOPT_AUTOREFERER,1);
curl_setopt($curl,CURLOPT_POSTFIELDS,$data);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
$tmpInfo=curl_exec($curl);
if(curl_errno($curl)){
return curl_error($curl);
}
curl_close($curl);
return $tmpInfo;
}
$openid=$_POST["openid"];
$formid=$_POST["formid"];
$name=$_POST["name"];
$time=$_POST["time"];
$style=$_POST["style"];
$kecheng=$_POST["kecheng"];
$templateid='。。。。。';
$data = <<<END
{
"touser": "{$openid}",
"template_id": "{$templateid}",
"page": "/pages/login1/login1",
"form_id": "{$formid}",
"data": {
"keyword1": {
"value": "{$name}"
},
"keyword2": {
"value": "{$time}"
},
"keyword3": {
"value": "{$style}"
} ,
"keyword4": {
"value": "{$kecheng}"
}
},
"emphasis_keyword": "keyword3.DATA"
}
END;
$appid="。。。。";
$secret="。。。。";
$gettokenapi="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
$resultstr=httpGet($gettokenapi);
$arr=json_decode($resultstr,true);
$token=$arr['access_token'];
//发送模板
$templateapi="https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={$token}";
$res=httpPost($data,$templateapi);
?>
最后说一下,这个代码并不会完全适合你,你需要做一些必要修改,祝你成功发送微信模板消息