微信網頁受權是服務號纔有的高級功能,開發者能夠經過受權後獲取用戶的基本信息;在此以前,想要獲取消息信息只能在用戶和公衆號交互時根據openid獲取用戶信息;而微信網頁受權可在不須要消息交互,也不須要關注的狀況下獲取用戶的基本信息php
微信網頁受權時經過OAuth2.0完成的,整個過程分爲三步:json
用戶受權,獲取code;
根據code獲取access_token【可經過refresh_token刷新獲取較長有效期】
經過access_token和openid獲取用戶信息
對微信網頁受權過程作了簡單封裝:api
<?php微信
/**app
微信受權相關接口*/
class Wechat {curl
//高級功能-》開發者模式-》獲取
private $app_id = 'xxx';
private $app_secret = 'xxxxxxx';post
/**this
獲取微信受權連接
@param string $redirect_uri 跳轉地址
@param mixed $state 參數*/
public function get_authorize_url($redirect_uri = '', $state = '') {url
$redirect_uri = urlencode($redirect_uri);
return "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->app_id}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_userinfo&state={$state}#wechat_redirect";
}debug
/**
獲取受權token
@param string $code 經過get_authorize_url獲取到的code*/
public function get_access_token($app_id = '', $app_secret = '', $code = '') {
$token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->app_id}&secret={$this->app_secret}&code={$code}&grant_type=authorization_code";
$token_data = $this->http($token_url);
if($token_data[0] == 200)
{
return json_decode($token_data[1], TRUE);
}
return FALSE;
}
/**
獲取受權後的微信用戶信息
@param string $access_token
@param string $open_id*/
public function get_user_info($access_token = '', $open_id = '') {
if($access_token && $open_id)
{
$info_url = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$open_id}&lang=zh_CN";
$info_data = $this->http($info_url);
if($info_data[0] == 200)
{
return json_decode($info_data[1], TRUE);
}
}
return FALSE;
}
public function http($url, $method, $postfields = null, $headers = array(), $debug = false) {
$ci = curl_init();
/ Curl settings /
curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ci, CURLOPT_TIMEOUT, 30);
curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
switch ($method) {
case 'POST':
curl_setopt($ci, CURLOPT_POST, true); if (!empty($postfields)) { curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields); $this->postdata = $postfields; } break;
}
curl_setopt($ci, CURLOPT_URL, $url);
curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ci, CURLINFO_HEADER_OUT, true);
$response = curl_exec($ci);
$http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
if ($debug) {
echo "=====post data======rn";
var_dump($postfields);
echo '=====info=====' . "rn";
print_r(curl_getinfo($ci));
echo '=====$response=====' . "rn";
print_r($response);
}
curl_close($ci);
return array($http_code, $response);
}
}