$appid="xxx";
$secret="xxx";
$code=$_GET["code"]?$_GET['code']:"getcode";//有code值说明是跳转过来的 没有code值就走跳转的方法
switch ($code) {
case 'getcode'://跳转方法
$redirect_uri = urlencode($_lang['host']."passport/wx");//重定向地址
$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
header("Location:" . $url);//直接跳转到微信的路径 微信会给回调路径返回一个code
break;
case $code://有code值了就获取access_token和openid
$url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$secret."&code=".$code."&grant_type=authorization_code";
$oauth2 = getJson($url);
$access_token = $oauth2["access_token"];
$openid = $oauth2['openid'];
//根据access_token和openid获取到用户信息
$get_user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
$userinfo = getJson($get_user_info_url);
var_dump($userinfo);
//用户信息包括openid、nickname、sex、language、city、country、headimageurl、privilege、unionid
// Common::base_header("Location:".$_lang['host']."member/\n");
break;
}
function getJson($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
return json_decode($output, true);
}
网友评论