WxloginController.php 6.2 KB
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Powerless < wzxaini9@gmail.com>
// +----------------------------------------------------------------------
namespace app\portal\controller;

use cmf\controller\HomeBaseController;
use think\Config;
use think\Session;
use think\Db;


class WxloginController extends HomeBaseController
{
    /**
     * 初始化
     */
    public function _initialize()
    {
        $getTypeOf = $this->request->param();
        $expUrl = explode('/',$_SERVER['REQUEST_URI']);
        //        模板消息页面重定向
        if(!empty($getTypeOf['typeof'])){
            if($getTypeOf['typeof'] == 1 || $getTypeOf['typeof'] == 3){
                $rediUrl = 'http://' .$_SERVER['HTTP_HOST'].'/portal/Member/myOrder';
            }else if($getTypeOf['typeof'] == 2){
                $rediUrl = 'http://' .$_SERVER['HTTP_HOST'].'/portal/Member/myResume';
            }
        }else{
            if(count($expUrl) == 4){
                $rediUrl = 'http://' .$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
            }else{
                $rediUrl = 'http://' .$_SERVER['HTTP_HOST'];
            }
        }
        parent::_initialize(); // TODO: Change the autogenerated stub
        if(!Session::get('user.accessToken')){
            session('uid',null);
            session('user.accessToken',null);
            session('user.accessTime',null);
            $this->OAuth($rediUrl);
        }else{
            //                判断accesstoken时间
            $overTime = Session::get('user.accessTime');
            if(($overTime + 7100) < time() ){
                //                    超过时间,重新获取accesstoken
                session('uid',null);
                session('user.accessToken',null);
                session('user.accessTime',null);
                $this->OAuth($rediUrl);
            }else{
                //                    未超过
                //                    查询用户是否存在
                $uid = Session::get('uid');
                $id = Db::name('Member')->where(array('id'=>$uid,'status'=>1))->value('id');
                if(!$id){
                    $this->OAuth($rediUrl);
                }else{
                    $url = $rediUrl;
                }
            }
        }

    }
    /**
     * Main:判断是否是微信打开
     */
    function is_weixin(){
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
            return true;
        }
        return false;
    }

    /**
     * Main:授权登录 获取openid
     */
    public function OAuth($redirect_uri){
        if (!Session::get('uid')) {
            $url = $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
            $temp_one = explode('code=',$url);
            if(!empty($temp_one[1])){
                $temp_two = explode('&state',$temp_one[1]);
                if ($temp_two[0]) {
                    //第二步 获取access_token
                    $url      = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".Config::get('WX_APPID')."&secret=".Config::get('WX_APP_SECRET')."&code=" . $temp_two[0] . "&grant_type=authorization_code";
                    $resp     = file_get_contents($url);
                    $resp_arr = json_decode($resp, true);
//                    将accesstoken 存session
                    Session::set('user.accessToken',$resp_arr['access_token']);
                    Session::set('user.accessTime',time());
                   //第三步
                    $refresh_token = $resp_arr['refresh_token'];
                    $url1 = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=".Config::get('WX_APPID')."&grant_type=refresh_token&refresh_token=".$refresh_token;
                    $resp1     = file_get_contents($url1);
                    $resp_arr1 = json_decode($resp1, true);
                    //第四步
                    $access_token = $resp_arr1['access_token'];
                    $openid = $resp_arr1['openid'];
                    $url2 = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
                    $resp2 = file_get_contents($url2);
                    $resp_arr2 = json_decode($resp2, true);
                    $user_headFile['headimgurl'] = $resp_arr2['headimgurl'];
//                    图片路径
                    $save_path['wx_name'] = $resp_arr2['nickname'];
                    $save_path['wx_pic'] = $resp_arr2['headimgurl'];
                    $save_path['openid'] = $resp_arr2['openid'];
                    $save_path['create_time'] = time();
                    $save_path['update_time'] = time();
                    $is_isset = Db::name('Member')->where(array('openid' => $resp_arr2['openid']))->find();
                    if(!$is_isset){
                        $user_id = Db::name('Member')->insertGetId($save_path);
                        Session::set('uid',$user_id);
                    }else{
                        Session::set('uid',$is_isset['id']);
                    }
                } else {
                    $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".Config::get('WX_APPID')."&redirect_uri=" . $redirect_uri . "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
                    Header("Location: $url");
                    exit;
                }
            }else{
                $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".Config::get('WX_APPID')."&redirect_uri=" . $redirect_uri . "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
                echo "<pre/>";
                print_r(111111111);
                print_r($redirect_uri);
                die;
                Header("Location: $url");
                exit;
            }
        }
    }
}