<?php

namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Http\Requests;
use Illuminate\Http\Request;
use App\Libs\Classes\BLogger;
use App\Libs\Classes\WxSign;
use EasyWeChat\Foundation\Application;
use WechatOP;
use Illuminate\Support\Facades\Redis;
use Doctrine\Common\Cache\PredisCache;

class WechatOpController extends Controller
{
	
	public $openPlatform;
	public $WxSign;
// 	public $wechat_group_gzh;

	public function __construct($gzh_app_id='') {
		v('start_wechat_op_construct');
		$options = [
		// ...
		'open_platform' => [
			'app_id'   => env('WECHAT_OP_APPID'),
			'secret'   => env('WECHAT_OP_SECRET'),
			'token'    => env('WECHAT_OP_TOKEN'),
			'aes_key'  => env('WECHAT_OP_AES_KEY'),
			],
		// ...
		];
		v('$options');v($options);
		$app = new Application($options);
		$this->openPlatform = $app->open_platform;
		v('end_wechat_op_construct');
		
		$this->WxSign = new WxSign();
		$this->set_init_param();
		v('post:');v($_POST);
	}
		
	// 初始化post，get变量，兼容两种
	public function set_init_param(){
		if(empty($_POST)) {
			$_POST = $_REQUEST;
		}
		if(empty($_REQUEST)) {
			$_REQUEST = $_POST;
		}

		if(isset($_POST['_url'])) {
			unset($_POST['_url']);
		}
		if(isset($_REQUEST['_url'])) {
			unset($_REQUEST['_url']);
		}
	}	
	
	public function redirect_url($response_url){
//		v('redirect_url in:'.$response_url);
		header("Location:".$response_url);
        exit;
	}
	
	/**
	 * 检查签名和时间戳
	 * @param unknown_type $request
	 */
	public function check_sign_params($request){
		$result = array('code'=>1,'msg'=>'','data'=>'');
		$timestamp = !empty($request->get('timestamp'))?$request->get('timestamp'):'';
		$sign = !empty($request->get('sign'))?$request->get('sign'):'';
		v('check_sign_params:$timestamp:'.$timestamp.' $sign:'.$sign);
		if(empty($timestamp) || empty($sign)){
			$result['code'] = 0;
			$result['msg'] = 'invalid param';
			return $result;
		}
		
		$timestamp = $request->get('timestamp');
		$sign = $request->get('sign');
		$now = microtime(true);
		$diff = $now - $timestamp;
		v('timestamp:'.$timestamp.' now:'.$now.' diff:'.$diff);
		// 时间戳8小时内
		if($diff > 28*3600){
			$result['code'] = 0;
			$result['msg'] = 'invalid time';
			return $result;
		}

		$my_sign = $this->WxSign->get_sign($request->all());
		v('check_sign_params sign:'.$sign.' my_sign:'.$my_sign.' info:'.json_encode($request->all()));
		if($sign != $my_sign){
			$result['code'] = 0;
			$result['msg'] = 'invalid sign';
			return $result;
		}
		return $result;
	}
	
}
