admin

微信网页授权登陆 获取用户基本信息
//微信签名开发文档:https://pay.weixin.qq.com/wiki/doc/api/jsapi.p...
扫描右侧二维码阅读全文
12
2018/12

微信网页授权登陆 获取用户基本信息

//微信签名开发文档:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=4_3
class wxPay
{
    const KEY               = 'KEY';                                               // api密钥
    const CODEURL           = 'https://open.weixin.qq.com/connect/oauth2/authorize?';//微信获取code的url
    const APPID             = 'APPID';                                            //appid
    const SECRET            = 'SECRET';                                            //api密钥
    const REDIRECT_URI      = '';                                                        //微信授权回调地址
    const ACCESS_TOKEN_URL  = '         //微信获取access_token的url 
    const USER_INFO_URL     = 'https://api.weixin.qq.com/sns/userinfo?';            //拉取微信用户信息的url
    /*
     *获取用户openid
     开发文档地址:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842
     */
 
     public function getUserInfo()
     {
         $appid             = self::APPID; 
         $secert            = self::SECRET; 
         $redirect_url      = self::REDIRECT_URI;
         $access_token_url  = self::ACCESS_TOKEN_URL;
         $user_info_url     = self::USER_INFO_URL;
         $code_url          = self::CODEURL;
         session_start();
         //如果openid保存在session中的
         if(!isset($_SESSION['access_token'])){
            if(!isset($_GET['code'])){
            //如果没有code,给用户构建一个跳转地址获得code
            $url = $code_url."appid=$appid&redirect_uri=$redirect_url&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
            header('Location:'.$url);
            exit;
             }else{
             //如果存在access_token,直接使用access_token拉取用户信息
             if(!isset($_SESSION['access_token'])){
                $code                 =       $_GET['code'];
                $url                  =       $access_token_url."appid=$appid&secret=$secert&code=$code&grant_type=authorization_code";
                $result               =       file_get_contents($url);
                $result               =       json_decode($result,true);
                $_SESSION['access_token']           =       $result['access_token'];
                $_SESSION['openid']   =       $result['openid'];
             }
             //拉取用户信息
                $openid               =       $_SESSION['openid'];
                $access_token         =       $_SESSION['access_token'];
                $getUserInfoUrl       =     $user_info_url."access_token=$access_token&openid=$openid&lang=zh_CN";
                $userInfo             =       file_get_contents($getUserInfoUrl);
             }
             //userInfo为获取到的用户信息
             return $userInfo;
         }
     }
}
$pay    = new wxPay();
最后修改:2019 年 08 月 12 日 07 : 15 PM
如果觉得我的文章对你有用,请随意赞赏

发表评论