微信網頁授權功能來獲取用戶信息(昵稱或頭像)之php實現


授權頁面鏈接:

https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx14f******33aca21&redirect_uri=http://****.************.com/wechat/php/oauth_response.php&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect

授權頁面會跳轉到一個帶有code參數的頁面,頁面地址沒變,簡單點說就是頁面刷新了個你所需要的code參數

<?php
        //獲取地址鏈接中的code參數
	$location = $_SERVER["QUERY_STRING"];
	$data = strstr($location,'&',true);
	$code = substr($data, 5);
	//curl 的post請求
	function CurlPost($url, $data)
	{
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
		curl_setopt($curl, CURLOPT_URL, $url);
		if(!empty($data))
		{
			curl_setopt($curl, CURLOPT_POST, true);
			curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		}
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		$result = curl_exec($curl);
		curl_close($curl);
		return $result;
	}
        //get請求
	function CurlGet($url)
	{
		return CurlPost($url, "");
	}
	//通過code換取網頁授權access_token
	$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx14f******33aca21&secret=332cab69b**********e5481b9bfe6ce&code=".$code."&grant_type=authorization_code";
	$rs = json_decode(CurlGet($url));
	//請求成功返回access_token
	if(isset($rs->{'access_token'})){
		//保存access_token
		$access_token = $rs->{'access_token'};
		$openid = $rs->{'openid'};
	//請求成功返回errcode
	}else if (isset($rs->{'errcode'})) {
		//# code...
	}
	//拉取用戶信息(需scope為 snsapi_userinfo)
	$user = json_decode(CurlGet("https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN"));
	echo $user->{'nickname'};
?>    

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM