微信公众号模板消息推送功能
最近因为客户需求,研究了一下微信公众号的模板消息推送,花了一个半小时,终于搞出来了,如图:
下面介绍一下流程
1.首先先获取access_token
2.获取到了access_token,那么就去微信的模板库里挑选模板,并且把它添加到我的模板里面
3.接下来就是编辑数据,传递过去即可
4.当你发送了数据之后,微信会把推送成功的信息发送到你公众号基本配置里的服务器配置里配置的地址上面去
具体代码如下:
//推送消息 public function push(){ $access_token = $this->access_token(); if ($access_token == 400){ return json(['code'=>0,'message'=>'获取access_token失败']); }$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token; $data = array( "touser" => $openid, //openid "template_id" => '模板id', //模板id "url" => '用户点击信息跳转地址', "data" => array( 'first' => array( 'value'=>'尊敬的客户,您的订单有了新的进展', 'color'=>'' ), 'keyword1'=>array( 'value'=>123465, 'color'=>'' ), 'keyword2'=>array( 'value'=>'订单进度提醒', 'color'=>'' ), 'keyword3'=>array( 'value'=>66666, 'color'=>'' ), 'keyword4'=>array( 'value'=>date('Y-m-d H:i:s', time()), 'color'=>'' ), 'remark' => array( 'value'=>'最新订单状态', 'color'=>'' ), ), //模板数据 ); return $this->http_post_json($url,json_encode($data));//发送请求 } public function http_post_json($url, $jsonStr) { $ch = curl_init(); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json; charset=utf-8', 'Content-Length: ' . strlen($jsonStr) ) ); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); return json_encode(array($httpCode, $response),true); } //获取access_token public function access_token(){ $access_token = Cache::get('access_token'); if (!empty($access_token)){ return $access_token; } $appId = APPID; $appSecret = appsecret; $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appId."&secret=".$appSecret; $ch = curl_init();//初始化curl curl_setopt($ch, CURLOPT_URL,$url); //要访问的地址 curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//跳过证书验证 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在 $data = json_decode(curl_exec($ch),true); if(curl_errno($ch)){ var_dump(curl_error($ch)); //若错误打印错误信息 } curl_close($ch);//关闭curl if(Cache::set('access_token',$data['access_token'],172800)){ return $data['access_token']; }else{ return 400; } }