<?php
namespace Addons\QyWechat\Controller\Api\Providers;
use Models\BaseModel as Model;
use Addons\QyWechat\Helper;
require_once(DOXCX_FRAME_PATH . 'fun/library/QyWxCypto/WXBizMsgCrypt.php');
 
class ReceiveSuiteTicket extends \BaseController
{
	  public function  index(){
		  if(isset($_GET['echostr'])){
			  //接受验证数据
		  	  $sVerifyMsgSig = $_GET['msg_signature'];
			  $sVerifyTimeStamp = $_GET['timestamp'];
			  $sVerifyNonce = $_GET['nonce'];
			  $sVerifyEchoStr = $_GET['echostr'];
			  $configList = (new Model('qy_agency_thirdappsetting'))->list_all();
			  foreach($configList as $config){
				  $encodingAesKey = $config->encodingAESKey;
				  $token = $config->token;
				  $corpId = $config->corpid;
				  $wxcpt = new \WXBizMsgCrypt($token, $encodingAesKey, $corpId);
				  // 需要返回的明文
				  $sEchoStr = "";
				  $errCode = $wxcpt->VerifyURL($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $sVerifyEchoStr, $sEchoStr);
				  if($errCode == 0){
					echo $sEchoStr;
					exit();
				  }
			  }
		  }else{
			  //搜集参数
			  $sReqMsgSig = $_GET['msg_signature'];
			  $sReqTimeStamp = $_GET['timestamp'];
			  $sReqNonce = $_GET['nonce'];
			  //获取xml冰去除特殊字符
			  $sReqData = preg_replace("/[\n\s]/", '', file_get_contents('php://input'));
			  //解密
			  $config = (new Model('qy_agency_thirdappsetting'))->find(['suite_id'=>xml_to_array($sReqData)['ToUserName']]);
			  $encodingAesKey = $config->encodingAESKey;
			  $token = $config->token;
			  $corpId = $config->suite_id;
			  $wxcpt = new \WXBizMsgCrypt($token, $encodingAesKey, $corpId);
			  $sMsg = "";  // 解析之后的明文
			  $errCode = $wxcpt->DecryptMsg($sReqMsgSig, $sReqTimeStamp, $sReqNonce, $sReqData, $sMsg);
			  if ($errCode == 0) {
				  $arr = xml_to_array($sMsg);
				  if($arr['InfoType'] == 'suite_ticket'){
					  $this->save_suite_ticket($arr);
				  }
			  } else {
				  diy_log("解密失败ERR: " . $errCode . "\n\n");
			  }
			  echo "success";
			  exit();
		  }
	  }
	  
	  public function save_suite_ticket($arr){
		  $st = (new Model('qy_providers_suite_ticket'))->find(['suite_id'=>$arr['SuiteId']]);
		  $st->suite_id = $arr['SuiteId'];
		  $st->suite_ticket = $arr['SuiteTicket'];
		  $st->ctime =  date('Y-m-d H:i:s', $arr['TimeStamp']);
		  $st->save();
	  }
}
