<?php namespace WeChatController; use ThinkController; class BaseController extends Controller { protected $user_id; protected function _initialize(){ if(empty($_SESSION['user']['id'])) { $code = $_GET['code']; if($code){ $url = "https://api.weixin.qq.com/sns/oauth2/access_token"; $data['appid'] = C('WX_APPID'); $data['secret'] = C('WX_SECRET'); $data['code'] = $code; $data['grant_type'] = "authorization_code"; $httpstr = http($url, $data, 'GET'); $steam=json_decode($httpstr); $_SESSION['user']['openid'] = $steam->openid; $_SESSION['user']['token'] = $steam->access_token; $member_model = D('Member'); $result = $member_model->where(['openid' => $steam->openid])->find(); if(!$result){ $member_data = get_wechat_user_info($steam->access_token, $steam->openid); if($member_data->errcode) { echo '用户信息错误,请重新加载';return; }else{ $add_wechat_member = $member_model->add([ 'openid' => $member_data->openid, 'user_name' => $member_data->nickname, 'sex' => $member_data->sex, 'create_time' => time(), 'headimgurl' => $member_data->headimgurl ]); $_SESSION['user']['openid'] = $member_data->openid; $_SESSION['user']['id'] = $this->user_id = $add_wechat_member; $_SESSION['user']['user_name'] = $member_data->nickname; $_SESSION['user']['sex'] = $member_data->sex; $_SESSION['user']['headimgurl'] = $member_data->headimgurl; $_SESSION['user']['time'] = time(); } }else{ $_SESSION['user']['openid'] = $result['openid']; $_SESSION['user']['id'] = $this->user_id = $result['id']; $_SESSION['user']['user_name'] = $result['user_name']; $_SESSION['user']['sex'] = $result['sex']; $_SESSION['user']['headimgurl'] = $result['headimgurl']; $_SESSION['user']['time'] = time(); } }else{ $appid = C('WX_APPID'); $redirect_uri = "http://pttest.itsumy.com".$_SERVER['REQUEST_URI']; $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"; header("Location:".$url); } } } }