我们在做微信公众号活动的时候,会做一些H5的海报供用户分享,在分享过程中经常会遇到对用户身份的判断,尤其是该用户是不是粉丝。如果不是粉丝,我们可以引导关注公众号,从而达到吸粉目的,如果是粉丝,我们再进行一些福利的派发或活动资格的领取。那么如何用PHP实现对用户是否关注公众号进行判断呢?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | <?php error_reporting(1); $appid='公众号APPID'; $secret='公众号APPSECRET'; $web_url='https://www.xiebit.com/'; if (!isset($_GET['code'])) { $redirect_uri=urlencode($web_url); $url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_base&state=1#wechat_redirect'; header("location:$url");exit(); }//此IF语句是判断是否为微信浏览器打开,如果不是,则提示请在微信打开该页面 $code=trim($_GET['code']);//PHP获取页面CODE $url='https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code'; $access=file_get_contents($url); $data=json_decode($access,true); $access_token=$data['access_token'];//根据CODE、APPID、APPSECRET获取网页授权的ACCESSTOKEN(此ACCESSTOKEN接口不限制次数) $url='https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid=OPENID&lang=zh_CN'; $user=file_get_contents($url); $arr=json_decode($user,true); $openid=$arr['openid']; //使用网页授权ACCESSTOKEN获取OPENID $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret; $access=file_get_contents($url); $access_arr=json_decode($access,true); $access_token=$access_arr['access_token']; //获取全局ACCESSTOKEN(此接口消耗每日2000的次数,建议缓存) $url="https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$openid."&lang=zh_CN"; $response = curlGet($url); $result = json_decode($response,true);//转换JSON文件为数组 function curlGet($url = '', $options = array()) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 30); if (!empty($options)) { curl_setopt_array($ch, $options); } //https请求 不验证证书和host curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); $data = curl_exec($ch); curl_close($ch); return $data; } //var_dump($res); $fans=$result['subscribe'];//根据$result中的subscribe键值来判断是否关注,1为已关注,0为未关注 if($fans === 1) {echo "已关注"; } else {echo "未关注"; } |