首先需要去微信公众平台配置一下关联 可以看一下这个链接 有详细讲述
微信小程序向公众号推送消息超详细教程_小程序通过公众号推送消息_亿只王菜菜的博客-CSDN博客
配置好以后就是代码部分
//获取token
public function get_token(){
$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), true);
dd($res);
$access_token = $res['access_token'];
return $access_token;
}
public function sendMessage(){
$ACCESS_TOKEN = $this->get_token();//通过微信获取access_token接口 获取的token
// dd($ACCESS_TOKEN);
$template_id = 'xxxxxxxx';//配置的模板id
$url = 'index';//点击模板消息跳转的链接
$template = array(
'touser' => $openid,
'template_id' => $template_id,
'url' => $url,
'data' => array(
'first' => array('value' => 'xxxxx'), //标题
'keyword1' => array('value' => 'xxxxx'), //姓名
'keyword2' => array('value' => 'xxxxx'), //手机
'keyword3' => array('value' => 'xxxxx'), //时间
'remark' => array('value' => 'xxxxx'))//消息内容
);
$send_template_url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $ACCESS_TOKEN;
$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, json_encode($template));
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$res = curl_exec($ch);
curl_close($ch);
return $res;
}
这样就可以直接拿过去用了