评论

第三方平台获取component_verify_ticket 和 component_access_token的源代码类

第三方平台获取component_verify_ticket 和 component_access_token的源代码类,thinkphp5开发。

<?php
/**

  • 第三方平台与微信通讯接口
    */
    namespace app\task\controller;

use app\common\library\wechat\WxBizMsgCrypt;
use app\common\model\Config as ConfigModel;

class Callback
{
/**
* 异步通知处理
*/
public function ticket()
{
$config = ConfigModel::detail();//获取第三方平台配置信息

	$token = $config['token'];
	$encodingAesKey = $config['encoding_aes_key'];
	$appId = $config['app_id'];
	
	// 接收公众号平台发送的消息
	$timeStamp = empty ( $_GET ['timestamp']) ? "" : trim ( $_GET ['timestamp'] );
    $nonce = empty ( $_GET ['nonce'] ) ?"" : trim ( $_GET ['nonce'] );
    $msg_sign = empty ( $_GET['msg_signature'] ) ? "" : trim ( $_GET ['msg_signature'] );
    $encryptMsg = file_get_contents ('php://input' );
	
    //创建解密类(该类另外发布)
	$pc = new WxBizMsgCrypt($token, $encodingAesKey, $appId);
	$msg = '';
	//开始解密
	$errCode = $pc->decryptMsg($msg_sign, $timeStamp, $nonce, $encryptMsg, $msg);
	if($errCode == 0){
		$data = $this->_xmlToArr($msg);	//XML转换为数组
		//write_log($data, __DIR__);
		//信息类型判断
		if($data['InfoType'] == 'component_verify_ticket'){
			//更新过期的令牌component_access_token
			if($config['expires_in'] < time()){
				$token = $this->getToken($config['app_id'], $config['app_secret'], $config['component_verify_ticket']);
				$config['component_access_token'] = $token['component_access_token'];
				$config['expires_in'] = time()+6000;
			}
			$config['component_verify_ticket'] = $data['ComponentVerifyTicket']; 
			$config->save();	//保存ticket
		}
		
		return 'success';
	}else{
		write_log('解密失败 - 错误代码:'.$errCode, __DIR__);
	}
	
}
/**
 * 获取 component_access_token
*/
private function getToken($appid, $appsecret, $ticket)
{
	$url = 'https://api.weixin.qq.com/cgi-bin/component/api_component_token';
	$data = '{"component_appid":"'.$appid.'","component_appsecret":"'.$appsecret.'","component_verify_ticket":"'.$ticket.'"}';
	$result = http_request($url,$data);
	return json_decode($result,true);
}

/**
 * 将xml转为array
*/
private function _xmlToArr($xml) {
    $res = @simplexml_load_string ( $xml,NULL, LIBXML_NOCDATA );
    $res = json_decode ( json_encode ( $res), true );
    return $res;
}

}

最后一次编辑于  10-23  
点赞 0
收藏
评论