``话不多说直接贴代码(公众号设置模板id看官方文档
)
<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;
use think\Session;
use think\Request;
class sendinfo extends Controller{
public function sendinfo(){
//提交成功,触发信息推送
$data=[
'touser'=>'想收到消息人的openid',
'template_id'=>'你设置的微信公众号模板消息的模板id',
'url'=>$web_url = "http://".$_SERVER['SERVER_NAME'],//用户收到消息后点击调整的url,可自定义
'topcolor'=>"#FF0000",
'data'=>array(
'first'=>array('value'=>"恭喜您报名成功",'color'=>"#fc0101"),
'applyTitle'=>array('value'=>'111','color'=>"#173177"),
'applyTitleTime'=>array('value'=>'2222','color'=>"#173177"),
'customName'=>array('value'=>date("Y-m-d H:i:s",time()),'color'=>"#173177"),
'customPhone'=>array('value'=>'28845674542341','color'=>"#173177"),
'reportBuilding'=>array('value'=>'发的萨芬撒','color'=>"#173177"),
'remark'=>array('value'=>"测试消息啊测试消磁啊测试反撒娇发哪家",'color'=>"#173177"),
)
];
$get_access_token = $this->get_access_token();
$json_data=json_encode($data);//转化成json数组让微信可以接收
//dump($json_data);
$url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$get_access_token;//模板消息请求URL
$res=$this->https_request($url,urldecode($json_data));//请求开始
$res=json_decode($res,true);
if($res['errcode']==0 && $res['errcode']=="ok"){
return '成功'
}else{
return '失败';
}
}
public function https_request($url,$data = null){
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
if (!empty($data)){
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
public function get_access_token(){
$appid = '微信公众号appid';
$secret = '微信公众号secret';
$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
$res = $this->https_request($url);
$access_token1=json_decode($res,true);
$access_token = $access_token1['access_token'];
// dump($access_token);
return $access_token;
}
}
注意:直接访问域名测试的话会报错,
但是并不影响结果
后续我会继续写tp5微信小程序模板消息,以及微信小程序支付等完整的tp5例子。