今天项目小程序有个提醒用户到店取货的需求,一想这需求咱们不是手到擒来吗?意外的是还被这东西折腾了一会,大伙来看看你们有没有遇到同样问题。
1、小程序模板消息接口(已废弃),之前项目用到的估计都改了了吧各位,微信就是这么豪横!!!
2、现在采用订阅消息
3、需要用户订阅权限才能推送消息,用户订阅一次发送一次(用户未勾选默认推送每个模板消息只能发送一次,勾选能主动推送3次)
下面贴上我的案例代码供大家参考:
public function sendMessage($orderid,$username,$code,$store_name,$store_address,$store_phone,$openid)
{
$wechat = new Wechat();//移入你自己的微信类
$token = $wechat->get_access_token();//获取access_token
$post = [];
$post['touser'] = $openid;//被推送者的openid
$post['page'] = '/pages/orderDetail/orderDetail?id='.$orderid;//订阅消息的跳转页面
$post['template_id'] = '2lC4siiXRbNuj_2fEglcbNPouT3eFImvmFGs3E-GbIc';//消息模板
$post['data'] = [
'name1'=>['value'=>$username,'color'=>'#173177'],
'character_string11'=>['value'=>$code,'color'=>'#173177'],
'thing2'=>['value'=>$store_name,'color'=>'#173177'],
'thing3'=>['value'=>$store_address,'color'=>'#173177'],
'phone_number9'=>['value'=>$store_phone,'color'=>'#173177']
];//推送内容 按照你自己的模板写
$url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token='.$token;
$re = $this->curl_url($url,$post);
return $re;
}
private function curl_url($url, $json)
{
$body = json_encode($json);
$headers = array("Content-type: application/json;charset=UTF-8", "Accept: application/json", "Cache-Control: no-cache", "Pragma: no-cache");
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
//.........................获取access_token............
/**
* Notes:获取access_token
* User: 小海
* Time:下午 2:55
* DATE:2020/7/2 0002
*/
public function get_access_token() {
$tokenFile = "/www/wwwroot/disanxiang/application/access_token.txt";//我是将token保存在文件中,你也可以存数据库自己定就好
$data = json_decode(file_get_contents($tokenFile));
if ($data->expire_time < time() || !$data->expire_time) {
//小程序appid
$appid = '';
//小程序 APPSecret 密钥
$appsecret = '';
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
$res = json_decode(file_get_contents($url));
$access_token = $res->access_token;
if($access_token) {
$data_new['expire_time'] = time() + 7000;//有效期两小时
$data_new['access_token'] = $access_token;
file_put_contents($tokenFile, json_encode($data_new));
}
}else{
$access_token = $data->access_token;
}
return $access_token;
}
完了直接调用sendMessage方法即可,效果如下: