<?php

namespace Cas\Controller;

use KIF\Cache\Memcached;
use KIF\Core\Controller;
use KIF\Core\Request;
use Cas\Module\RefreshAccessToken;
use KIF\Core\Config;

/**
 * WeixinJsSDK 用于微信 js 调用 
 * 吐出相应数据
 * 可查看:http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html
 *
 * @author lihuanchun
 *        
 */
class WeixinJsSDK extends Controller {
	private $objMemache;
	public function __construct() {
		$this->objMemache = new Memcached ();
		$wechat_cfg = Config::getInstance ()->get ( 'wechat_cfg' );
		$this->appId = $wechat_cfg ['appId'];
		$this->appSecret = $wechat_cfg ['appSecret'];
	}
	
	/**
	 * ajax 返回微信所需js配置信息
	 * http://cas.lishuy.com/?c=WeixinJsSDK&a=AjaxConfigData
	 */
	public function doAjaxConfigData() {
		$thisPageUrl = Request::g ( 'thisPageUrl' );
		$returnData = $this->getSignPackage ( $thisPageUrl );
		$this->ajax_success_exit ( $returnData );
	}
	
	/**
	 * getSignPackage
	 */
	private function getSignPackage($url = null) {

		$jsapiTicket = $this->getJsApiTicket ();
		if ($url == null) {
			$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
		} else {
			$url = htmlspecialchars_decode ( $url );
		}
		
		$timestamp = time ();
		$nonceStr = $this->createNonceStr ();
		$string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
		$signature = sha1 ( $string );
		$signPackage = array (
				"appId" => $this->appId,
				"nonceStr" => $nonceStr,
				"timestamp" => $timestamp,
				"url" => $url,
				"signature" => $signature,
				"rawString" => $string 
		);
		return $signPackage;
	}
	
	/**
	 * createNonceStr
	 */
	private function createNonceStr($length = 16) {
		$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		$str = "";
		for($i = 0; $i < $length; $i ++) {
			$str .= substr ( $chars, mt_rand ( 0, strlen ( $chars ) - 1 ), 1 );
		}
		return $str;
	}
	
	/**
	 * getJsApiTicket
	 */
	private function getJsApiTicket() {
		$data = json_decode($this->objMemache->get('ticket'));
	    if ($data->expire_time < time()) {  
	      $accessToken = $this->getAccessToken();  
	      $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=' . $accessToken;  
	      $res = json_decode($this->httpGet($url));  
	      $ticket = $res->ticket;  
	      if ($ticket) {  
	        $data->expire_time = time() + 7000;  
	        $data->jsapi_ticket = $ticket;  
	        $this->objMemache->set('ticket', json_encode($data));
	      }  
	    } else {  
	      $ticket = $data->jsapi_ticket;  
	    }  
	  
	    return $ticket; 
	}
	
	/*
	 * (non-PHPdoc)
	 * @see \KIF\Core\Controller::run()
	 */
	public function run() {
		$action = $this->action;
		$this->$action ();
	}

	private function getAccessToken() {
		$data = json_decode($this->objMemache->get('token'));
		if ($data->expire_time < time()) {
			$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->appId.'&secret=' . $this->appSecret;
			$res = json_decode($this->httpGet($url));
			$access_token = $res->access_token;
			if ($access_token) {
				$data->expire_time = time() + 7000;
				$data->access_token = $access_token;
				$this->objMemache->set('token', json_encode($data));
			}
		} else {  
			$access_token = $data->access_token;  
		}
		return $access_token;  
	}

	private function httpGet($url) {  
	    $curl = curl_init();  
	    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);  
	    curl_setopt($curl, CURLOPT_TIMEOUT, 500);  
	    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);  
	    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);  
	    curl_setopt($curl, CURLOPT_URL, $url);  
	  
	    $res = curl_exec($curl);  
	    curl_close($curl);  
	  
	    return $res;
  	}
}