通过小程序和公众号关联后发公众号模板消息
关联后用户登录获取到union_id,主体在小程序,根据对应场景发送模板消息
代码如下:
/**
* 模板消息 发送
* @param $openid 接收消息的用户openid
* @param $arr 模板消息所需要的参数
* @param $templat_id 模板id
* @param $page 点击详情进入的小程序页面路径(小程序上线后才有效)
*/
function send_temp($openid, $arr,$templat_id='*******',$page='')
{
$appid="小程序appid";
$sercet="appsercret";
$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$sercet;
//小程序信息获取token
$res = curl_get($url);
$data = json_decode($res, true);
if (isset($data['access_token'])) {
$send_url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token=' . $data['access_token'];
$send_data = [
'touser' => $openid,//微信小程序openid
'mp_template_msg' => [
'appid' => '****',//公众号appid
'template_id' => $templat_id,//模板id
'url' => '',//发送后用户点击跳转的链接
'miniprogram' => [ //与公众号绑定的小程序(选传)
'appid' => $appid,//小程序id
'path' => $page,//跳转页面
],
'data' => $arr
],
];
$send_data_decode = json_encode($send_data, true);
return $res_send = sendCmd($send_url, $send_data_decode);
}
}
function sendCmd($url, $data)
{
$curl = curl_init(); // 启动一个CURL会话
curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检测
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Expect:')); //解决数据包大不能提交
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循
curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
$tmpInfo = curl_exec($curl); // 执行操作
if (curl_errno($curl)) {
echo 'Errno' . curl_error($curl);
}
curl_close($curl); // 关键CURL会话
return $tmpInfo; // 返回数据
}