<?php
namespace Wechat\Controller;
use Think\Controller;
header("Content-Type:text/html;charset=utf-8");
class OAuthController extends Controller{
	public function __construct()
    {
		parent::__construct();
		$this->_is_Login();
   	}

    /**
     * 检测是否已经登录
     */
  	private function _is_Login()
    {
        //自动获取openid
	 	if(!cookie('openid')){
			vendor('WxPayPubHelperMp.WxPayPubHelper');
			//使用jsapi接口
			$jsApi = new \JsApi_pub();
			//通过code获得openid
			if (!isset($_GET['code']))
			{
				//触发微信返回code码
				$url = $jsApi->createOauthUrlForCode2("http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
                //echo $url;die;
				Header("Location: $url");die;
			} else {
				//获取code码，以获取openid
				$code = $_GET['code'];

				$jsApi -> setCode($code);
				$userinfo = $jsApi->getUserinfo();
				$userinfo = json_decode($userinfo[0], TRUE);
                session("access_token",$userinfo['access_token']);
				$info_url = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $userinfo['access_token'] . "&openid=" . $userinfo['openid'] . "&lang=zh_CN";
				$info_data = $jsApi->http($info_url);  
				$userinfo = json_decode($info_data[0], TRUE);
                cookie("openid", $userinfo['openid'], 7200);//OpenID
                cookie("nickname", $userinfo['nickname'], 7200);//昵称
                cookie("sex", $userinfo['sex'], 7200);//性别（1 男  2 女  0 未知）
                cookie("headimgurl", $userinfo['headimgurl'], 7200);//头像
                cookie("city", $userinfo['city'], 7200);//城市
                cookie("province", $userinfo['province'], 7200);//省份
                cookie("country", $userinfo['country'], 7200);//国籍
                cookie("language", $userinfo['language'], 7200);//语言
                cookie("privilege", $userinfo['privilege'], 7200);//用户特权信息(json 数组)
                $data = array(
                    "nickname" => $userinfo['nickname'],
                    "sex" => $userinfo['sex'],
                    "headimgurl" => $userinfo['headimgurl'],
                    "city" => $userinfo['city'],
                    "province" => $userinfo['province'],
                    "country" => $userinfo['country'],
                    "language" => $userinfo['language']
                );
                // 保存微信信息
                $info = M("usersOa")->where("`openid` = '" . cookie("openid") . "'")->find();
                // 查看 usersOa 表是否有该openid
                if ($info) {
                    M("usersOa")->where("`openid`='{$userinfo['openid']}'")->save($data);
                } else {
                    $data['openid'] = $userinfo['openid'];
                    $data['create_time'] = time();
                    M("usersOa")->add($data);
                }
			}
	 	}
  	}
}