1. 程式人生 > >微信公眾平臺頁面授權處理方法(單一方法處理)

微信公眾平臺頁面授權處理方法(單一方法處理)

在使用微信公眾平臺進行第三方開發的過程中,我們經常會遇到需要呼叫微信頁面授權、從而獲取使用者資訊。但是單一的使用微信頁面授權的方式進入頁面,總會存在跳轉到微信頁面進行授權的問題,這樣就會增加使用者進入頁面所費時間,從而影響使用者體驗。
所以我們需要一種方式,藉助其他機制等,不必要使得使用者每次均要跳轉到微信頁面授權位置。這樣在使用者不是第一次進入頁面的過程中,即可以不用跳轉微信頁面授權,從而減少使用者進入頁面時間,提升使用者體驗。
這樣的使用方式,可以藉助伺服器session機制,利用if判斷,進行判斷。
示例程式碼如下:

public function OAuth()
{
    header('Content-type: text/html; charset=utf-8'
); //首先獲取微信配置資訊 $m_sssmall_conf_weixin = M('sssmall_conf_weixin'); $conf = $m_sssmall_conf_weixin->where('id=1')->find(); //將appid、appsecret設為超全域性變數,便於呼叫。 $appid = $conf['appid']; $appsecret = $conf['appsecret']; //$access_token = getApiToken(); dump($_SESSION['oauth'
]); //條件判斷(假如session不存在,進行頁面授權,並設定session) if (empty($_SESSION['oauth']) && empty($_GET['code'])) { $redirect_uri = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; //此即為本頁面地址 $redirect_uri = urlencode($redirect_uri); $getCodeUrl
= 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appid . '&redirect_uri=' . $redirect_uri . '&response_type=code&scope=snsapi_userinfo&state=oauth#wechat_redirect'; redirect($getCodeUrl, 0); } elseif (!empty($_GET['code']) && empty($_SESSION['oauth'])) { $getAccesstokenUrl = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $appsecret . '&code=' . $_GET['code'] . '&grant_type=authorization_code'; $res = WeChat_request($getAccesstokenUrl); $openid = $res->openid; $_SESSION['oauth'] = $openid; dump($openid); //獲取使用者資訊儲存 } else { dump('第二次進入'); dump($_SESSION['oauth']); } dump('看到我就證明成功啦'); }

此處對於頁面授權的重定向地址為此頁面本身,重新進入頁面後會進行條件判斷,當openid資訊已經存在使,即可不用在進行頁面授權,從而提升使用者體驗。