微信测试号开发
2 第二步:通过code换取网页授权access_token
4 第四步:拉取用户信息(需scope为 snsapi_userinfo)
public function wxCode(){
header('location:https://open.weixin.qq.com/connect/oauth2/authorize?appid='.self::$appid.'&redirect_uri=http%3A%2F%2F'.$_SERVER['SERVER_NAME'].'%2FXXX%2F%2FXXX%2FXXX&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect');exit;
}
public function WxInfo(){
$code = $_GET['code'];
if (empty($code)) die('授权失败');
$token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.self::$appid.'&secret='.self::$appsecret.'&code='.$code.'&grant_type=authorization_code';
$token = json_decode(file_get_contents($token_url));
if (isset($token->errcode)) {
echo '<h1>错误1:</h1>'.$token->errcode;
echo '<br/><h2>错误信息:</h2>'.$token->errmsg;
echo '<br/><h2>appsecret:</h2>'.self::$appsecret;
echo '<br/><h2>appid:</h2>'.self::$appid;
exit;
}
$access_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.self::$appid.'&grant_type=refresh_token&refresh_token='.$token->refresh_token;
//转成对象
$access_token = json_decode(file_get_contents($access_token_url));
if (isset($access_token->errcode)) {
echo '<h1>错误2:</h1>'.$access_token->errcode;
echo '<br/><h2>错误信息:</h2>'.$access_token->errmsg;
exit;
}
$user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token->access_token.'&openid='.$access_token->openid.'&lang=zh_CN';
//转成对象
$user_info = json_decode(file_get_contents($user_info_url));
if (isset($user_info->errcode)) {
echo '<h1>错误3:</h1>'.$user_info->errcode;
echo '<br/><h2>错误信息:</h2>'.$user_info->errmsg;
exit;
}
echo '<pre>';
var_dump($user_info);
exit;
}