获取小程序openid
public function getKcOpenId(){
$code =Request::get('code');
//$code='021EBA1002o7KL14ZO100zkKfk2EBA1W';
$appid = 'wxf334e7c59c87813b';
$appsecret = 'd8b8c958d00576bfe3a65ad64caf7d39';
$get_code_url ="https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$appsecret."&js_code=".$code."&grant_type=authorization_code";
$res = file_get_contents($get_code_url);
$response=json_decode($res,true);
return json_encode(array('openid' => $response['openid']));
}
//appid 小程序appid
//appsecret 小程序密钥
//code 小程序登录时会生成code值
获取小程序access_token值
public function getToken() {
$appid ='wxf334e7c59c87813b';
$secret='d8b8c958d00576bfe3a65ad64caf7d39';
$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
$data = '';
$AccessToken = $this->sendCmd($url,$data);//公共方法sendCmd
$AccessToken = json_decode($AccessToken, true);
$AccessToken = $AccessToken['access_token'];
return $AccessToken;//获取到的accesstoken
}
//appid 小程序appid
//appsecret 小程序密钥
公共方法sendCmd
public 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, 0); // 从证书中检查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; // 返回数据
}
发送订阅消息
public function sendMessage(){
$openid='o53Un4_jndi4LKQLuLB4oSMT2LLM';
$templateid="wiGlHSLfmFM6QKWpVdGfZCFzlG4s6bNM6Vz9aWXyi4Q";
$token='45_PobVTmuPu76mY51UAyYv0dfmyIYadCGif67r1XXADI53QADdp4Wu1tnsXiS6XSrS0OvKrIeDy6MGxFakHBl_xdRSCd4NQ0dYneU3fCCJI6pnmaLm_nnobiIlUTCTX8Z_0YE1p_wRnB14aFAAEUUiAFARHH';
$access_token = $token;
$senddata=[
"touser"=>$openid,
"template_id"=>$templateid,
"page"=>'pages/mine/mine',
"form_id"=>123,
"data"=>[
"phrase1" => [
"value"=> $v['']
],
"time2" => [
"value"=>date('Y-m-d H:i:s',time())
],
"time3" => [
"value"=> date('Y-m-d H:i:s',time())
],
"thing4" => [
"value"=> "XC".time()
]
],
];
$urls = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token='.$access_token;
$data= json_encode($senddata);
$ret = $this->sendCmd($urls, $data);
return $ret;
}
//formid 小程序端生成
//template_id 模板id 点击小程序后台可在订阅消息处查看
注意事项
1.data里面的值应与模板详情里一直(属性名和值的类型都要一致)
2.如果出现{"errcode":43101,"errmsg":"user refuse to accept the msg rid: 5f66c169-36dc383e-31b0a11b"}这个报错,让小程序端打开订阅设置开启即可。