1. 程式人生 > >微信公眾號獲取使用者的openid

微信公眾號獲取使用者的openid

公眾號可獲得關注者的OpenID(加密後的微訊號,每個使用者對每個公眾號的OpenID是唯一的。對於不同公眾號,同一使用者的openid不同)。公眾號可通過本介面來根據OpenID獲取使用者基本資訊,包括暱稱、頭像、性別、所在城市、語言和關注時間。

對於微信開發者來說獲取使用者openid是最基本的操作了,然而還是有人不會獲取,說報錯,其實錯誤原因主要存在於:
1.你使用的公眾號沒有許可權,一般認證服務號有次許可權,部分訂閱號也有;
2.在公眾號後臺沒有配置網頁授權域名


話不多說,直接上程式碼:

//設定網路請求配置
public function _request($curl,$https=true,$method='GET',$data=null){
	// 建立一個新cURL資源
	$ch = curl_init();
	
	// 設定URL和相應的選項
	curl_setopt($ch, CURLOPT_URL, $curl);    //要訪問的網站
	curl_setopt($ch, CURLOPT_HEADER, false);    //啟用時會將標頭檔案的資訊作為資料流輸出。
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  //將curl_exec()獲取的資訊以字串返回,而不是直接輸出。 

	if($https){
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  //FALSE 禁止 cURL 驗證對等證書(peer's certificate)。
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);  //驗證主機
	}
	if($method == 'POST'){
		curl_setopt($ch, CURLOPT_POST, true);  //傳送 POST 請求
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);  //全部資料使用HTTP協議中的 "POST" 操作來發送。
	}
	
	
	// 抓取URL並把它傳遞給瀏覽器
	$content = curl_exec($ch);
	if ($content  === false) {
	  return "網路請求出錯: " . curl_error($ch);
	  exit();
	}
	//關閉cURL資源,並且釋放系統資源
	curl_close($ch);
	
	return $content;
}


/**
 * 獲取使用者的openid
 * @param  string $openid [description]
 * @return [type]         [description]
 */
public function baseAuth($redirect_url){
	
	//1.準備scope為snsapi_base網頁授權頁面
	$baseurl = urlencode($redirect_url);
	$snsapi_base_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->appid.'&redirect_uri='.$baseurl.'&response_type=code&scope=snsapi_base&state=YQJ#wechat_redirect';
	
	//2.靜默授權,獲取code
	//頁面跳轉至redirect_uri/?code=CODE&state=STATE
	$code = $_GET['code'];
	if( !isset($code) ){
		header('Location:'.$snsapi_base_url);
	}
	
	//3.通過code換取網頁授權access_token和openid
	$curl = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$this->appid.'&secret='.$this->appsecret.'&code='.$code.'&grant_type=authorization_code';
	$content = $this->_request($curl);
	$result = json_decode($content,true);
	
	return $result;
}
返回的結果如下表,其中的openid就是我們想要的。