流程:
1、需要微信登陆后,才可以访问网页;
2、微信登陆的会判断是否已关注相关微信公众号;
3、如未关注,需要关注后,才可微信登陆;
4、关注微信公众号后,点击登陆,登陆成功。
代码:
$appid = 'appid';
$appkey = 'appkey';
$redirect_uri = "回调地址";//回调地址
$year = date("Y");
$month = date("m");
$day = date("d");
$dayBegin = mktime(0, 0, 0, $month, $day, $year);
if (!isset($_GET['code'])) {
$state = md5(uniqid(rand(), true));
$callback = urlencode($redirect_uri);
$wxurl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$callback&response_type=code&scope=snsapi_userinfo&state=$state#wechat_redirect";
$this->redirect($wxurl);
}else{
$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid .'&secret=' . $appkey . '&code=' . $_GET['code'] .'&grant_type=authorization_code';
$arr = json_decode(file_get_contents($url),1);
$access_token = $arr['access_token'];
$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid .'&secret=' . $appkey;
$arrc = json_decode(file_get_contents($url),1);
$access_token = $arrc['access_token'];
$url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token=' . $access_token .'&openid=' . $arr['openid'] . '&lang=zh_CN';
$userinfo = json_decode(file_get_contents($url),1);
if($userinfo['subscribe']!=1){
$url="https://mp.weixin.qq.com/s/jlOw9k1dy0X8xGSbUDVz6g";
$this->redirect($url);
die();
}
$openid = $userinfo['openid'];
if($openid==""){
echo "登录失败";
die();
}
echo "登陆成功";
}