微信開發服務號鑑權

零love發表於2018-02-06

微信開發

版權宣告:本文為博主原創文章,部落格地址:http://blog.csdn.net/u012279647/article/details/79268033,未經博主允許不得轉載。

class HomeBaseController extends BaseController
{
    private $appId;
    private $appSecret;

    public function _initialize()
    {

        $this->appId = '';

        $this->appSecret = '';
        Session::set('openid_session','');

        $openid_ss = Session::get('openid_session');
        if(!$openid_ss){
            $openid_s = $this -> GetOpenid();
             Session::set('openid_session',$openid_s['openid']);
            Session::set('userinfo_session',$openid_s);
        }
    }

    /**
     * 微信
     */
    public function GetOpenid()
    {
        //通過code獲得openid
        if (!isset($_GET['code'])){
            //觸發微信返回code碼
//            $baseUrl = urlencode('http://bbsd.yllfbaobao.cn/portal/wechat/GetOpenid');
            $baseUrl = urlencode('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
//           print_r($baseUrl);die();
            $url = $this->__CreateOauthUrlForCode($baseUrl,1);
            Header("Location: $url");
            exit();
        } else {
            //獲取code碼   ,以獲取openid
            $code = $_GET['code'];
            $data = $this->GetOpenidFromMp($code);
            $urlObj = [];
            $urlObj["access_token"] =  $data['access_token'];
            $urlObj["openid"] = $data['openid'];
//            $urlObj["lang"] = 'zh_CN';
            $bizString = $this->ToUrlParams($urlObj);
            $url = 'https://api.weixin.qq.com/sns/userinfo?'.$bizString;
            //獲取使用者資訊,openid,暱稱,頭像。
            $userinfo = json_decode($this->httpGet($url),true);
            //查取資料庫資訊,核對openid是否存在 存資料庫 
        //     $user = new UserModel;
        //     $openid = $user->where('openid',$userinfo['openid'])->find();
            if(empty($openid)){
                //存資料庫  
            }
         }
        // return $userinfo['openid'];
        return $userinfo;
//        Session::set('openid_s',$userinfo['openid']);
//        return redirect('Index/index');
    }
    /**
     *
     * 通過code從工作平臺獲取openid機器access_token
     * @param string $code 微信跳轉回來帶上的code
     *
     * @return openid
     */
    public function GetOpenidFromMp($code)
    {
        $url = $this->__CreateOauthUrlForOpenid($code);
        //初始化curl
        $ch = curl_init();
        //設定超時
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($ch, CURLOPT_TIMEOUT, 500);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        // if(WechatConfig::CURL_PROXY_HOST != "0.0.0.0"
        //     && WechatConfig::CURL_PROXY_PORT != 0){
        //     curl_setopt($ch,CURLOPT_PROXY, WechatConfig::CURL_PROXY_HOST);
        //     curl_setopt($ch,CURLOPT_PROXYPORT, WechatConfig::CURL_PROXY_PORT);
        // }
        //執行curl,結果以jason形式返回
        $res = curl_exec($ch);
        curl_close($ch);
        //取出openid
        $data = json_decode($res,true);
        return $data;
    }
    public function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);

        $res = curl_exec($curl);
        //dump($res);
        curl_close($curl);
        return $res;
    }
    /**
     *
     * 拼接簽名字串
     * @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;
    }
    /**
     *
     * 構造獲取code的url連線
     * @param string $redirectUrl 微信伺服器回跳的url,需要url編碼
     *
     * @return 返回構造好的url
     */
    private function __CreateOauthUrlForCode($redirectUrl,$state)
    {
        $urlObj["appid"] = $this->appId;
        $urlObj["redirect_uri"] = "$redirectUrl";
        $urlObj["response_type"] = "code";
        if($state == 1){
            $urlObj["scope"] = "snsapi_userinfo";
        }else if($state == 2){
            $urlObj["scope"] = "snsapi_base";
        }
        $urlObj["state"] = "STATE"."#wechat_redirect";
        $bizString = $this->ToUrlParams($urlObj);
        return "https://open.weixin.qq.com/connect/oauth2/authorize?".$bizString;

    }
    /**
     *
     * 構造獲取open和access_toke的url地址
     * @param string $code,微信跳轉帶回的code
     *
     * @return 請求的url
     */
    private function __CreateOauthUrlForOpenid($code)
    {
        $urlObj["appid"] = $this->appId;
        $urlObj["secret"] = $this->appSecret;
        $urlObj["code"] = $code;
        $urlObj["grant_type"] = "authorization_code";
        $bizString = $this->ToUrlParams($urlObj);
        return "https://api.weixin.qq.com/sns/oauth2/access_token?".$bizString;
    }
    public function curlPost($url,$data=""){
        $ch = curl_init();
        $opt = array(
            CURLOPT_URL     => $url,
            CURLOPT_HEADER  => 0,
            CURLOPT_POST    => 1,
            CURLOPT_POSTFIELDS      => $data,
            CURLOPT_RETURNTRANSFER  => 1,
            CURLOPT_TIMEOUT         => 20
        );
        $ssl = substr($url,0,8) == "https://" ? TRUE : FALSE;
        if ($ssl){
            $opt[CURLOPT_SSL_VERIFYHOST] = 1;
            $opt[CURLOPT_SSL_VERIFYPEER] = FALSE;
        }
        curl_setopt_array($ch,$opt);
        $data = curl_exec($ch);
        //dump($data);
        curl_close($ch);
        return $data;

    }

    /**
     * @return code
     */
    public function code(){
        $host = $_SERVER['HTTP_HOST'];
        $code = $this ->httpGet($host.'/api/home/Index/index');
        print_r($code);
        $aa = \session('token');
        $this->pr($aa);
        $code =  json_decode($code,true);
        $token = $code['data']['token'];
        $token = (int)$token;

        session('token',$token);
        return $token;
    }

}

相關文章