200多行代碼實現微信公衆號網頁授權登錄 獲取用戶基本信息(頭像/暱稱/openid)

前期準備

1、認證的服務號
2、服務號已經將授權域名和目錄綁定

代碼

<?php
error_reporting(1);
header('Content-type:text/html; Charset=utf-8');
/* 配置開始 */
$appid = '';  //微信公衆平臺->開發->基本配置->AppID
$appKey = '';   //微信公衆平臺->開發->基本配置->AppSecret
/* 配置結束 */

//①、獲取用戶openid
$wxPay = new WxService($appid,$appKey);
$data = $wxPay->GetOpenid();      //獲取openid
if(!$data['openid']) exit('獲取openid失敗');
//②、獲取用戶信息
$user = $wxPay->getUserInfo($data['openid'],$data['access_token']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="renderer" content="webkit" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,Chrome=1" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
    <title>微信獲取用戶信息demo</title>
    <link href="https://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcss.com/jquery/2.1.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
    <div class="row">
        <h1>你的基本信息如下:</h1>
        <table class="table table-bordered">
            <tr>
                <td>openid</td>
                <td><?=$user['openid']?></td>
            </tr>
            <tr>
                <td>unionid</td>
                <td><?=$user['unionid']?></td>
            </tr>
            <tr>
                <td>暱稱</td>
                <td><?=$user['nickname']?></td>
            </tr>
            <tr>
                <td>頭像</td>
                <td><img src="<?=$user['headimgurl']?>" style="width: 100px;" alt=""></td>
            </tr>               
            <tr>
                <td>性別</td>
                <td><?php
                    switch (strtoupper($user['sex'])){
                        case 1:
                            echo '男性';
                            break;
                        case 2:
                            echo '女性';
                            break;
                        default:
                            echo '未知';
                            break;
                    }
                    ?></td>
            </tr>
            <tr>
                <td>省份 / 城市</td>
                <td><?=$user['province'].' / '.$user['city']?></td>
            </tr>
            <tr>
                <td>language</td>
                <td><?=$user['language']?></td>
            </tr>
        </table>
    </div>
</div>
</body>
</html>
<?php
class WxService
{
    protected $appid;
    protected $appKey;

    public $data = null;

    public function __construct($appid, $appKey)
    {
        $this->appid = $appid; //微信支付申請對應的公衆號的APPID
        $this->appKey = $appKey; //微信支付申請對應的公衆號的APP Key
    }

    /**
     * 通過跳轉獲取用戶的openid,跳轉流程如下:
     * 1、設置自己需要調回的url及其其他參數,跳轉到微信服務器https://open.weixin.qq.com/connect/oauth2/authorize
     * 2、微信服務處理完成之後會跳轉回用戶redirect_uri地址,此時會帶上一些參數,如:code
     *
     * @return 用戶的openid
     */
    public function GetOpenid()
    {
        //通過code獲得openid
        if (!isset($_GET['code'])){
            //觸發微信返回code碼
            $baseUrl = $this->getCurrentUrl();
            $url = $this->__CreateOauthUrlForCode($baseUrl);
            Header("Location: $url");
            exit();
        } else {
            //獲取code碼,以獲取openid
            $code = $_GET['code'];
            $openid = $this->getOpenidFromMp($code);
            return $openid;
        }
    }

    public function getCurrentUrl()
    {
        $scheme = $_SERVER['HTTPS']=='on' ? 'https://' : 'http://';
        $uri = $_SERVER['PHP_SELF'].$_SERVER['QUERY_STRING'];
        if($_SERVER['REQUEST_URI']) $uri = $_SERVER['REQUEST_URI'];
        $baseUrl = urlencode($scheme.$_SERVER['HTTP_HOST'].$uri);
        return $baseUrl;
    }

    /**
     * 通過code從工作平臺獲取openid機器access_token
     * @param string $code 微信跳轉回來帶上的code
     * @return openid
     */
    public function GetOpenidFromMp($code)
    {
        $url = $this->__CreateOauthUrlForOpenid($code);        
        $res = self::curlGet($url);
        $data = json_decode($res,true);
        $this->data = $data;
        return $data;
    }

    /**
     * 構造獲取open和access_toke的url地址
     * @param string $code,微信跳轉帶回的code
     * @return 請求的url
     */
    private function __CreateOauthUrlForOpenid($code)
    {
        $urlObj["appid"] = $this->appid;
        $urlObj["secret"] = $this->appKey;
        $urlObj["code"] = $code;
        $urlObj["grant_type"] = "authorization_code";
        $bizString = $this->ToUrlParams($urlObj);
        return "https://api.weixin.qq.com/sns/oauth2/access_token?".$bizString;
    }

    /**
     * 構造獲取code的url連接
     * @param string $redirectUrl 微信服務器回跳的url,需要url編碼
     * @return 返回構造好的url
     */
    private function __CreateOauthUrlForCode($redirectUrl)
    {
        $urlObj["appid"] = $this->appid;
        $urlObj["redirect_uri"] = "$redirectUrl";
        $urlObj["response_type"] = "code";
        $urlObj["scope"] = "snsapi_userinfo";
        $urlObj["state"] = "STATE";
        $bizString = $this->ToUrlParams($urlObj);
        return "https://open.weixin.qq.com/connect/oauth2/authorize?".$bizString;
    }

    /**
     * 拼接簽名字符串
     * @param array $urlObj
     * @return 返回已經拼接好的字符串
     */
    private function ToUrlParams($urlObj)
    {
        $buff = "";
        foreach ($urlObj as $k => $v)
        {
            if($k != "sign") $buff .= $k . "=" . $v . "&";
        }
        $buff = trim($buff, "&");
        return $buff;
    }

    /**
     * 獲取用戶信息
     * @param string $openid 調用【網頁授權獲取用戶信息】接口獲取到用戶在該公衆號下的Openid
     * @return string
     */
    public function getUserInfo($openid,$access_token)
    {

        $response = self::curlGet('https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN');
        return json_decode($response,true);
        
    }

    public static function curlGet($url = '', $options = array())
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https請求 不驗證證書和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }

    public static function curlPost($url = '', $postData = '', $options = array())
    {
        if (is_array($postData)) {
            $postData = http_build_query($postData);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //設置cURL允許執行的最長秒數
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https請求 不驗證證書和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }

}

說明:修改appid和appKey,上傳服務器,微信內訪問即可。

demo

在這裏插入圖片描述
微信掃碼體驗

在這裏插入圖片描述
Author:TANKING
Date:2020-04-15
Web:www.likeyunba.com
WeChat:face6009

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章