<?php namespace Phpcmf\Controllers;

// 登录跳转
class Go extends \Phpcmf\Common {

    // 从微信菜单中进入授权
    // 公众号内自动登陆
    public function index() {

        $url = (!$this->is_mobile ? SITE_URL : SITE_MURL).'index.php?s=weixin&c=member&m=login';
        if ($_GET['url']) {
            $burl = urlencode($_GET['url']);
        } else {
            $burl = urlencode((!$this->is_mobile ? SITE_URL : SITE_MURL).'index.php?s=member');
        }
        
        dr_redirect('https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->weixin['account']['appid'].'&redirect_uri='.urlencode($url).'&response_type=code&scope=snsapi_userinfo&state='.($burl).'#wechat_redirect');
    }

    // 静默授权获取openid（snsapi_base）
    public function check() {

        $code = \Phpcmf\Service::L('input')->get('code');
        $burl = $_GET['url'] ? $_GET['url'] : FC_NOW_URL;

        if ($code) {
            $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$this->weixin['account']['appid'].'&secret='.$this->weixin['account']['appsecret'].'&code='.$code.'&grant_type=authorization_code';
            $rt = wx_get_https_json_data($url);
            if (!$rt['code']) {
                $this->_msg(0, $rt['msg']);
            } elseif ($rt['data']['openid']) {
                \Phpcmf\Service::L('input')->set_cookie('weixin_gzh_openid', $rt['data']['openid'], 86400 * 30);
            }
            dr_redirect($burl);
        }

        $redirect_uri = (!$this->is_mobile ? SITE_URL : SITE_MURL).'index.php?s=weixin&c=go&m=check&url='.urlencode($burl);
        dr_redirect('https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->weixin['account']['appid'].'&redirect_uri='.urlencode($redirect_uri).'&response_type=code&scope=snsapi_base&state=check#wechat_redirect');
    }

}
