最近微信小程序甲方需新增下单提醒功能,于是我去微信文章看接入模板信息,但是看到最新公告(模板消息接口将下线,推荐使用订阅信息)官方通知:
1. 小程序订阅信息分为一次性订阅信息和长期性订阅信息,但是长期性订阅信息要求比较高,只有指定的类别才能申请,一次性订阅信息需要每次向用户发起授权请求,具体小程序端代码如下官方api:
var templateid = [后台订阅信息模板id];//注意这里是数组
uni.requestSubscribeMessage({tmplIds: templateid,success (res) {console.log(res)},fail:(res) => {console.log(res)}})
注意:用户只有发生点击行为或者发起支付回调后,才可以调起订阅信息界面。
2. 后台设置订阅消息模板
3. PHP后台
access_token 是小程序全局唯一后台接口调用凭据,调用绝大多数后台接口时都需使用。注意access_token的有效期只有2小时,所以建议用缓存redis,时间过期就更新。
获取access_token官方api获取access_token
/*** Notes:获取accessToken* @return mixed* @throws \think\Exception* @throws \think\exception\PDOException*/
public function getAccessToken()
{//当前时间戳$now_time = strtotime(date('Y-m-d H:i:s',time())) ;//失效时间$timeout = 7200 ;//判断access_token是否过期$before_time = $now_time - $timeout ;//未查找到就为过期$access_token = Db::table('takeout_access_token')->where('id',1)->where('update_time' ,'>',$before_time)->value('access_token');//如果过期if( !$access_token ) {//获取新的access_token$appid = APPID;$secret = SECRET;$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;$res = json_decode(file_get_contents($url),true);$access_token = $res['access_token'] ;//更新数据库$update = ['access_token' => $access_token ,'update_time' => $now_time] ;Db::table('takeout_access_token')->where('id',1)->update($update) ;}return $access_token ;
}
发送模板信息官方HTTPS调用api
//发送订阅消息
public function sendSubscribeMessage($touser,$template_id,$page,$content)
{//access_token$access_token = self::getAccessToken() ;//请求url$url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' . $access_token ;//发送内容$data = [] ;//接收者(用户)的 openid$data['touser'] = $touser ;//所需下发的订阅模板id$data['template_id'] = $template_id ;//点击模板卡片后的跳转页面,仅限本小程序内的页面。支持带参数,(示例index?foo=bar)。该字段不填则模板无跳转。$data['page'] = $page ;//模板内容,格式形如 { "key1": { "value": any }, "key2": { "value": any } }$data['data'] = ["phrase10"=>['value' => '123456'],"name8"=>['value' => '123456'],"amount12"=>['value' => '123'],'date4'=>['value'=>'123456'],'phone_number31'=>['value'=>'123456']];//跳转小程序类型:developer为开发版;trial为体验版;formal为正式版;默认为正式版$data['miniprogram_state'] = 'formal' ;return self::curlPost($url,json_encode($data)) ;
}
//发送post请求
protected function curlPost($url,$data)
{$ch = curl_init();$params[CURLOPT_URL] = $url; //请求url地址$params[CURLOPT_HEADER] = FALSE; //是否返回响应头信息$params[CURLOPT_SSL_VERIFYPEER] = false;$params[CURLOPT_SSL_VERIFYHOST] = false;$params[CURLOPT_RETURNTRANSFER] = true; //是否将结果返回$params[CURLOPT_POST] = true;$params[CURLOPT_POSTFIELDS] = $data;curl_setopt_array($ch, $params); //传入curl参数$content = curl_exec($ch); //执行curl_close($ch); //关闭连接return $content;
}