//调用
$this->accessToken($code, $title, $amount , date('Y-m-d H:i:s',time()));
/*
*获取access_token
*$code 前端传过来
*$title = 标题
*$amount = 金额
*$time = 时间
*/
protected function accessToken($code = '', $title = '', $amount = '', $time = ''){
$appid = '****';
$secret = '****';
// 设置请求的 URL
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
// 初始化 cURL
$ch = curl_init();
// 设置 cURL 选项
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// 执行请求并获取响应
$response = curl_exec($ch);
// 检查是否有错误
if (curl_errno($ch)) {
return false;
}
// 关闭 cURL
curl_close($ch);
$response = json_decode($response,true);
if(!isset($response['access_token'])) return false;
//获取access_token
$accessToken = $response['access_token'];
//获取用户的openId
$userOpenId = $this->userOpenId($appid,$secret,$code);
if (!$userOpenId) return false;
//结构体 (根据公众平台选择推送模版自行配置)
$info = (object)array(
'touser' => $userOpenId['openid'],
'template_id' => 'SXo-qjIdtIPbD-P1w6wZ-BMJkGv0TIveHrJkbw_3Z3Q',
'page' => '/pages/order/index',
'data' => array(
'thing7'=>['value'=>$title],
'amount4'=>['value'=>$amount],
'time5'=>['value'=>$time],
),
);
//发送订阅消息
return $this->subscribe($info,$accessToken);
}
//获取用户的openId
protected function userOpenId($appid, $secret, $code)
{
$url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$secret."&js_code=".$code."&grant_type=authorization_code";
$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);
if (curl_errno($curl)) {
return false;
}
curl_close($curl);
$data = json_decode($output, true);
if (isset($data['openid'])) {
return $data;
}
return false;
}
//发送订阅消息
protected function subscribe($data,$access_token){
$url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=".$access_token;
$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, json_encode($data));
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
if (curl_errno($curl)) {
return false;
}
curl_close($curl);
$info = json_decode($output, true);
if ($info['errcode'] == '0') {
return true;
}
return false;
}