微信通過網頁獲取用戶頭像與暱稱等信息

		define("APPID", "xxxx");
		define("APPSECRET", "xxx");

		$code = $_GET['code'];
		if(!$code){
		echo '<a href="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx5d7a4bb756e53b28&redirect_uri=http://www.xxx.com/index.php?m=oauth2&a=init&response_type=code&scope=snsapi_base&state=1#wechat_redirect" target="_blank">點擊登陸</a>';
		}else{
				

		//使用code獲取OpenID
		$openid_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".APPID."&secret=".APPSECRET."&code=".$code."&grant_type=authorization_code";
		$openid_data = file_get_contents($openid_url); 
		$arr_openid = (Array)json_decode($openid_data); 
		$openid = $arr_openid['openid'];


		//獲取全局Access Token
		/*
		$access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".APPID."&secret=".APPSECRET;
		$access_token_data = file_get_contents($access_token_url); 		
		$arr_access_token = (Array)json_decode($access_token_data); 
		$ACCESS_TOKEN = $arr_access_token['access_token'];
		*/

		$mem = new Memcache;
        $mem->connect('localhost', 11211) or die ("Could not connect");
        $ACCESS_TOKEN = $mem->get('access_token');
        if (empty($ACCESS_TOKEN)){
			$access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".APPID."&secret=".APPSECRET;
			$access_token_data = file_get_contents($access_token_url); 		
			$arr_access_token = (Array)json_decode($access_token_data); 
            $ACCESS_TOKEN = $arr_access_token['access_token'];
            $mem->set('access_token', $ACCESS_TOKEN, 0, 7200);
        }
		

		//使用全局ACCESS_TOKEN獲取OpenID的詳細信息
		$userinfo_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$ACCESS_TOKEN."&openid=".$openid."&lang=zh_CN";
		$userinfo_data = file_get_contents($userinfo_url); 
		$arr_userinfo = (Array)json_decode($userinfo_data);
		
		
		/*

		參數				說明
		subscribe		 用戶是否訂閱該公衆號標識,值爲0時,代表此用戶沒有關注該公衆號,拉取不到其餘信息。
		openid			 用戶的標識,對當前公衆號唯一
		nickname		 用戶的暱稱
		sex				 用戶的性別,值爲1時是男性,值爲2時是女性,值爲0時是未知
		city			 用戶所在城市
		country			 用戶所在國家
		province		 用戶所在省份
		language		 用戶的語言,簡體中文爲zh_CN
		headimgurl		 用戶頭像,最後一個數值代表正方形頭像大小(有0、46、64、96、132數值可選,0代表640*640正方形頭像),用戶沒有頭像時該項爲空。若用戶更換頭像,原有頭像URL將失效。
		subscribe_time	 用戶關注時間,爲時間戳。如果用戶曾多次關注,則取最後關注時間
		unionid			 只有在用戶將公衆號綁定到微信開放平臺帳號後,纔會出現該字段。詳見:獲取用戶個人信息(UnionID機制)

		*/

		//獲取全部信息:$openid, $nickname, $sex, $city, $province, $country, $headimgurl
		$subscribe = $arr_userinfo['subscribe']; 
		$nickname = $arr_userinfo['nickname'];
		$sex = $arr_userinfo['sex'];
		$city = $arr_userinfo['city'];
		$province = $arr_userinfo['province'];
		$country = $arr_userinfo['country'];
		$headimgurl = $arr_userinfo['headimgurl'];
		


		
		echo "ACCESS TOKEN:".$ACCESS_TOKEN;
		echo "<br>";
		echo "openid:".$openid; 
		echo "<br>";
		echo "nickname:".$nickname;
		echo "<br>";
		echo "city:".$province.$city; 
	}
	}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章