PHP判断微信用户是否关注公众号的实现方法
当前各类活动中,常要求用户关注公众号方可参与。如何准确识别用户是否已完成关注?本文将提供相应的PHP代码以解决此问题。
参考官方文档:获取用户基本信息(含UnionID机制)
https://mp.weixin.qq.com/wiki/14/bb5031008f1494a59c6f71fa0f319c66.html
1、只要有基础的access_token和用户openid就可以判断用户是否关注该公众号 2、利用的接口url为:https://api.weixin.qq.com/cgi-bin/user/info?access_token=$token&openid=$openid 3、判断接口返回的字段subscribe是否为1.【1关注,0未关注】
注意事项: 1. 获取openid采用静默授权方式,用户无感知; 2. 此功能依赖微信认证的服务号,订阅号不支持;
具体代码示例如下
< ? php
$access_token = $this - > _getAccessToken();
$subscribe_msg = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$access_token.'&openid='.$_SESSION['wecha_id'];
$subscribe = json_decode($this - > curlGet($subscribe_msg));
$zyxx = $subscribe - > subscribe;
if ($zyxx !== 1) {
echo'未关注!';
}
private function _getAccessToken() {
$where = array('token' = > $this - > token);
$this - > thisWxUser = M('Wxuser') - > where($where) - > find();
$url_get = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this - > thisWxUser['appid'].'&secret='.$this - > thisWxUser['appsecret'];
$json = json_decode($this - > curlGet($url_get));
if (!$json - > errmsg) {
} else {
$this - > error('获取access_token发生错误:错误代码'.$json - > errcode.',微信返回错误信息:'.$json - > errmsg);
}
return $json - > access_token;
}
? >
以上内容希望对您的学习有所帮助,欢迎继续支持本站。