php , laravel 小程序信息推送到公众号消息模版
1.登录公众号,新建消息推送模版
2.打开微信官方文档 ->找到模版消息接口 https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Template_Message_Interface.html
3. 代码
<?php namespace App\Admin\Controllers;
use App\Models\AdminWechat; use Dcat\Admin\Http\Controllers\AdminController; use Illuminate\Http\Request; class SendWeChatController extends AdminController { public function sendWx(Request $request){ $data = array( "character_string2" => array("value" => $request->input("name")), "time3" => array("value" => date("Y-m-d")), "thing8" => array("value" => $request->input("name1")), "amount18" => array("value" => $request->input("name2")), ); $template_id = ''; $openid = ''; return $this->sendWechatMessage($openid,$template_id,$data); } public function sendWechatMessage($openid,$template_id,$data) { $dataArr = array( "touser" => $openid, //openid "template_id" => $template_id, //模板id "url" => "", "miniprogram" => array( "appid" => '', //小程序APPID "pagepath" => 'pages_gzh/index/formgzh?table=pend&djbh=1231', ), "client_msg_id" => $openid.'_'.rand(1000000,999999), "data" => $data, ); $access_token = $this->access_token(); if ($access_token == 400){ return ['code'=>0,'message'=>'获取access_token失败']; } $urls = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token; //发送请求 $result = $this->http_post_json($urls,$dataArr); echo "<pre>"; print_r($result);exit; if($result['errcode'] == 0){ return ['code'=>200,'data'=>'推送成功']; } return ['code'=>0,'message'=>$result[1]['errmsg']]; } # 发送消息 接受消息的用户openid,发送的消息,点击详情跳转的url public function http_post_json($send_template_url,$template) { $data=json_encode($template); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $send_template_url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $res = curl_exec($ch); curl_close($ch); return $res; } #获取access_token public function access_token(){ $appId = ""; $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 return $data['access_token']; } }
4.展示效果
!!!注意:小程序和公众号有关联,获取access_token需要在公众号加入白名单