<?php
/*
 +----------------------------------------------------------------------
 | TEMMOKUMVC [ NO BEST , ONLY BETTER ]
 +----------------------------------------------------------------------
 | Copyright (c) 2018~2019 https://www.temmoku.cn All rights reserved.
 +----------------------------------------------------------------------
 | Author: 张宗强 Email:webmaster@temmoku.cn QQ:158726877 516669373 TEL:17895221001 微信:temmokumvc
 +---------------------------------------------------------------------- 
*/
namespace plugin\login\vendor\qq\user;
use \temmoku\db;
use \temmoku\controller;
use \temmoku\lib\cookie;
class bind extends controller{
	private $data;
	function __construct($data)
    {
    	parent :: __construct();
    	$this->data=unserialize(stripslashes($data['setting']));
    }
	public function index(){
		$this->assign('WEBNAME','QQ用户绑定_'.C('WEBNAME'));
		$TO_URL=urlencode(user_login_url."login_m/login");
		$url="https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=".$this->data['appid']."&state=1&redirect_uri=".$TO_URL;
		header("Location:$url");
	}
	
	public function login(){
		$this->assign('WEBNAME','QQ用户登陆_'.C('WEBNAME'));
		$TO_URL=urlencode(user_login_url."login_m/login");
		$url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id=".$this->data['appid']."&client_secret=".$this->data['appkey']."&code=".$_GET['code']."&redirect_uri=".$TO_URL;	
		$content = http_request($url);
		$_content=explode('&',$content);
		foreach($_content as $value){
			list($key,$_value)=explode('=',$value);
			$oicq[$key]=$_value;
		}
		if(!$oicq['access_token']){
			$this->err("出错了，以下为QQ具体返回的错误信息<br>".$content);
		}
		$url = "https://graph.qq.com/oauth2.0/me?access_token=".$oicq['access_token'];
		$content = http_request($url);
		preg_match_all('/{(.*?)}/', $content, $matches);
		if(!$matches[0][0]){
			$this->err("出错了，以下为QQ具体返回的错误信息<br>".$content);
		}
		$content=json_decode($matches[0][0],true);
		if(!$content['openid']){
			$this->err("出错了，以下为QQ具体返回的错误信息<br>".$content);
		}
		
		$data=db::select('*')->from(jab.'user')->where("qq_openid= '$content[openid]' ")->row();
		if($data){
			$this->err('此qq已经绑定过用户了，请先解绑，然后再绑定');
		}
		db::update(jab.'user')->cols(['qq_openid'=>$content['openid']])->where("uid=".C('MYDB.uid'))->query();
		
		$this->success('QQ绑定成功','/user/index/maps');
	}

}
?>