1. 程式人生 > >PHP 微信網頁授權獲取使用者資訊

PHP 微信網頁授權獲取使用者資訊

 


class WxController extends Controller {

    //put your code here
    /**
     * 微信授權相關介面
     */
    //高階功能-》開發者模式-》獲取
    private $app_id = '';//appid
    private $app_secret = '';//微信公眾號金鑰

    function index() {

//C("YUM") === $_SERVER['HTTP_HOST']
        $url = "http://".C("YUM")."/Home/Wx/index_1"; // 回撥地址--授權後跳轉頁面,附帶code和
        redirect($this->get_authorize_url($url, "STATE"));
    }
    
    function bbc(){
        session("name","你打野");
        redirect(U("Home/Index/index_1"));
    }

    function index_1() {
        $code = I("code");
        $userinfo = $this->get_access_token($code);
        //使用者授權
        if ($userinfo) {
            $openid = $userinfo['openid'];
            $access_token = $userinfo['access_token'];
            $user = $this->get_user_info($access_token, $openid);
            $mod = M("user");
            $where['openid'] = $openid;
            //判斷使用者已註冊
            $res = $mod->where($where)->find();
//            var_dump($res);die;
            //資料庫無匹配
            if (!$res) {
                //註冊新使用者
                $add = array(
                    "openid" => $openid,
                    "nickname" => $user['nickname'],
                    "city" => $user['city'],
                    "province" => $user['province'],
                    "country" => $user['country'],
                    "headimgurl" => $user['headimgurl'],
                    "sex" => $user['sex'],
                    "create_time" => time(),
                );
                $mod->add($add);
                $res = $mod->where($where)->find();
            }
//            $_COOKIE['user'] = $res; //儲存使用者資訊到會話中
//            $_SESSION['user'] = $res; //儲存使用者資訊到會話中
            session("user",$res);
            //修改最後登入時間
            $mod->where($where)->setField("end_time",time());
            //跳轉網頁
            $url="http://".C("YUM")."";
//            $url = "http://xkjh.lmkf.net";
            redirect($url);
        } else {
            echo '<meta charset="UTF-8">';
            echo "未授權無法訪問---(You are not eligible to visit)";
        }
    }

    /**
     * 獲取微信授權連結
     *
     * @param string $redirect_uri 跳轉地址
     * @param mixed $state 引數
     */
    public function get_authorize_url($redirect_uri = '', $state = '') {
        $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";
    }

    /**
     * 獲取授權token
     *
     * @param string $code 通過get_authorize_url獲取到的code
     */
    public function get_access_token($code = '', $app_id = '', $app_secret = '') {
        $app_id = empty($app_id) ? $this->app_id : $app_id;
        $app_secret = empty($app_secret) ? $this->app_secret : $app_secret;
        $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======\r\n";
            var_dump($postfields);

            echo '=====info=====' . "\r\n";
            print_r(curl_getinfo($ci));

            echo '=====$response=====' . "\r\n";
            print_r($response);
        }
        curl_close($ci);
        return array($http_code, $response);
    }

}

 

類就在這裡啦!  3分靠努力,3分靠打拼,3分靠天賦。