首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP微信第三方網頁授權登錄:OAuth2.0獲取用戶信息免注冊實現

     編輯:PHP 綜合知識

前置要求

  • 認證服務號(訂閱號不支持網頁授權)
  • 配置 OAuth2.0 授權回調域名(如 www.xxx.com)

前端授權鏈接

<a href="https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=https://www.xxx.com/action/oauth2&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect">授權登錄</a>

後端邏輯實現

public function oauth2() {
    include './Card/Common/class_weixin_adv.php';
    $wx = new class_weixin_adv("APPID", "SECRET");

    if (isset($_GET['code'])) {
        // 1. 換取 access_token + openid
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code={$_GET['code']}&grant_type=authorization_code";
        $res = $wx->https_request($url);
        $data = json_decode($res, true);

        // 2. 獲取用戶詳情
        $user = $wx->get_user_info($data['openid']);
        // $user 包含:openid, nickname, sex, province, city, country, headimgurl, privilege, unionid

        if ($user['openid']) {
            // 免注冊邏輯:openid作為唯一標識存Cookie/數據庫
            cookie('weixin', $user['openid'], 2592000); // 30天
            // 重定向或展示頁面
        } else { $this->error('授權失敗'); }
    } else { echo "NO CODE"; }
    $this->display();
}

SDK 核心類

class class_weixin_adv {
    var $appid, $appsecret, $access_token, $lasttime;
    function __construct($appid, $appsecret) { /* 初始化 */ }
    function get_user_info($openid) {
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$this->access_token}&openid=$openid&lang=zh_CN";
        return json_decode($this->https_request($url), true);
    }
    function https_request($url, $data=null) {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        if ($data) { curl_setopt($ch, CURLOPT_POSTFIELDS, $data); }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        return curl_exec($ch);
    }
}

免注冊設計思路

OpenID 唯一標識用戶,存入 Cookie 實現「無感登錄」,關鍵業務驗證只需比對數據庫 OpenID,極大降低用戶門檻。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved