背景
参考官方文档,主要难点在于获取formId,目前发送模板消息只能由用户主动触发,以表单的形式提交后拿到formId。此外发送模板消息,还需要获取接收者(用户)的access_token,openId,template_id(小程序后台申请的模板id)。
demo
小程序代码:https://github.com/IvyYao/miniApp-notification-demo/blob/master/README.md
技术实现
获取openId
在进入小程序的时候获取openid
// app.js
App({
onLaunch: function () {
// 登录后才能获取openid
wx.login({
success: res => {
this.getOpenId(res.code)
}
})
},
globalData: {
openId: '',
},
getOpenId(code) {
let _this = this;
wx.request({
url: $you_api,
data: {
code: code,
type: 'openid'
},
header: {
'content-type': 'application/x-www-form-urlencoded'
},
method: 'GET',
success: function (res) {
let openId = res.data.data.openid;
_this.globalData.openId = openId;
},
fail: function () {
console.log("获取openid失败")
}
});
}
})
获取formId
通过用户点击
相应处理函数
formSubmit(e) {
this.requestNotification(e, 0)
},
requestNotification(e, templateType) {
const formId = e.detail.formId;
const _this = this
wx.request({
// 不要忘记换成你的api
url: $you_api,
data: {
type: 'pushnews',
openid: app.globalData.openId,
formid: formId,
templateType
},
header: {
'content-type': 'application/x-www-form-urlencoded'
},
method: 'GET',
success: function (res) {
wx.showToast({
title: '请查看微信消息',
icon: 'succes',
duration: 1000,
mask: true
})
},
fail: function () {
wx.showToast({
title: '发送失败',
icon: 'succes',
duration: 1000,
mask: true
})
}
});
}
后端逻辑实现(php)
获取access_token
function getAccessToken(){
$dataJson = readTxt();
$data = json_decode($dataJson,true);
if ($data['expire_time'] < time()) {
// echo "过期了";
$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.APPID.'&secret='.APPSECRET;
$r1 = ccurl($url);
$r2 = json_decode($r1,true);
// print_r($r2);
if ($r2['access_token']) {
$data2 = new stdClass();
$data2->expire_time = time() + 7000;
$data2->access_token = $r2['access_token'];
writeTxt(json_encode($data2));
}
return $r2['access_token'];
}else{
return $data['access_token'];
}
}
获取openid和发送消息
$ret = array('code' => 0,'msg'=>'');
$type = isset($_GET['type']) ? trim($_GET['type']) : '';
switch($type){
// 通过code得到openid
case 'openid':
$code = isset($_GET['code']) ? trim($_GET['code']) : '';
if(empty($code)){
$ret['code'] = -1;
$ret['msg'] = '登录凭证code获取失败';
$ret['data']['show'] = 1;
exit(json_encode($ret));
}
$url = "https://api.weixin.qq.com/sns/jscode2session?appid=".APPID."&secret=".APPSECRET."&js_code=$code&grant_type=authorization_code";
$json = json_decode(ccurl($url),true);
if((isset($json['errcode']) && $json['errcode']) || $json['openid'] == ''){
$ret['msg'] = $json['errcode'].', '.$json['errmsg'];
$ret['code'] = -1;
$ret['data']['openid'] = '';
exit(json_encode($ret));
}
$openid = $json['openid'];
$ret['code'] = 1;
$ret['data']['openid'] = $openid;
exit(json_encode($ret));
break;
// 发送模板消息
case 'pushnews':
pushNews();
break;
default :
$ret['code'] = -1;
$ret['msg'] = '错误: ' . $type;
exit(json_encode($ret));
break;
}
// 发送模板消息
function pushNews(){
$templateType = $_GET['templateType'];
$templateData = array(
"keyword1" => array(
"value" => "防脱发攻略",
"color" => "#173177"
),
"keyword2" => array(
"value" => "攻略",
"color" => "red"
),
"keyword3" => array(
"value" => "公司",
"color" => "#173177"
),
"keyword4" => array(
"value" => "要什么攻略,剃光头就好了",
"color" => "#173177"
)
);
if ($templateType == 1) {
$templateData = array(
"keyword1" => array(
"value" => "心理安慰",
"color" => "#173177"
),
"keyword2" => array(
"value" => "心理安慰",
"color" => "red"
),
"keyword3" => array(
"value" => "公司",
"color" => "#173177"
),
"keyword4" => array(
"value" => "不要担心,脱发乃大势所趋!",
"color" => "#173177"
)
);
}
$data = array(
'touser' => $_GET['openid'],
'template_id' => 'Yd4AA2IcyRDiZ_AHy6ba4grswFYX2tl37BZ2k-qHd_c',//模板id
'page' => 'pages/index/index?from=ivy',//跳转路径
"form_id" => $_GET['formid'],//formid
"data" => $templateData,
"emphasis_keyword" => "keyword1.DATA"
);
$r = ccurl('https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.getAccessToken(),$data=json_encode($data));
print_r($r);