2026-10-12 17:34:58 +08:00

1343 lines
51 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace app\index\controller;
use app\common\controller\Frontend;
use fast\Http;
use think\Exception;
use think\Queue;
class Index extends Frontend
{
protected $noNeedLogin = '*';
protected $noNeedRight = '*';
protected $layout = '';
protected $AppModel;
protected $appSecret;
protected $redis;
protected $token;
protected $encodingAesKey;
protected $appId;
protected $key;
public function _initialize()
{
parent::_initialize();
$redis = new \Redis();
try {
$redis->connect('127.0.0.1', 6379);
$redis->auth('qwe2019@');
$redis->select(12);
} catch (\Exception $e) {
\think\Log::error('Redis连接失败: ' . $e->getMessage());
}
$this->AppModel = new \app\common\model\App;
$this->appSecret = "8e76ea205dcc1d3e506ce6c102375bdd"; // 这里应该填上实际的AppSecret
$this->redis = $redis;
$this->token = "lujS6QH8jUkabwOwMuAqe9odz7";
$this->encodingAesKey = "lujS6QH8jUkabwOwMuAqe9odz7jmKEnT37XMahpSmrU";
$this->appId = "wx6e91ec813bcb7eec";
$this->key = "8DE6CAD0E48D4DF84CF0593AD01DB62FE89D137B";
$this->qiwei = [
"EncodingAESKey"=>"vaLPuAhQdPccZOAt7ijCMttlL50USxn7cvH4ESZankL",
"Token"=>"8BXwA"
];
}
public function qiweMessage(){
$postData = $this->request->post();
$getData = $this->request->get();
\think\Log::error('请求头: ' . json_encode($getData));
\think\Log::error('接收到消息: ' . json_encode($postData));
$this->redis->lpush("qiweMessage",json_encode($postData));
return "";
}
public function index()
{
return $this->view->fetch();
}
public function onMessage(){
$msg_signature = $this->request->get("msg_signature", '');
$timestamp = $this->request->get("timestamp", '');
$nonce = $this->request->get("nonce", '');
$echostr = $this->request->get("echostr", '');
\think\Log::error('echostr: ' . json_encode([
'echostr' => stripslashes($echostr),
]));
$token = $this->qiwei["Token"];
$AESKey = base64_decode($this->qiwei["EncodingAESKey"]."=");
$result= $this->verifyUrlQw($msg_signature, $timestamp, $nonce, $echostr, $token);
if(!$result){
return "";
}
\think\Log::error('1.解密前: ' . $result);
$rand_msg = $this->aes_decrypt($result,$AESKey);
$content = substr($rand_msg, 16);
$lenBytes = substr($content, 0, 4);
$msg_len = unpack('N', $lenBytes)[1];
\think\Log::error('1.解密结果: ' . $msg_len);
$msg = substr($content, 4, $msg_len+4);
$receiveid = substr($content,$msg_len+4);
\think\Log::error('2.解密结果: ' . $msg);
\think\Log::error('3.解密结果: ' . $receiveid);
return $msg;
}
public function Authorization()
{
try {
// 获取参数
$signature = $this->request->get("signature", '');
$timeStamp = $this->request->get("timestamp", '');
$nonce = $this->request->get("nonce", '');
$openid = $this->request->get("openid", '');
$encrypt_type = $this->request->get("encrypt_type", '');
$msg_sign = $this->request->get("msg_signature", '');
// 获取原始POST数据
$from_xml = file_get_contents('php://input');
// 原文(含GET参数)转发一份到测试环境
//$this->forwardToTest('/Authorization', $from_xml);
// 记录日志用于调试
\think\Log::info('微信回调参数: ' . json_encode([
'signature' => $signature,
'timestamp' => $timeStamp,
'nonce' => $nonce,
'msg_signature' => $msg_sign,
'encrypt_type' => $encrypt_type
]));
\think\Log::info('原始XML数据: ' . $from_xml);
// 如果是URL验证(首次配置)
$echostr = $this->request->get("echostr", '');
if ($echostr) {
return $this->verifyUrl($signature, $timeStamp, $nonce, $echostr, $this->token);
}
// 检查是否有加密数据
if (empty($from_xml)) {
\think\Log::error('接收到的XML数据为空');
return "fail";
}
// 修复XML中的全角字符
$from_xml = $this->fixXmlEncoding($from_xml);
$pc = new \app\index\library\wechat\open\WXBizMsgCrypt($this->token, $this->encodingAesKey, $this->appId);
$errCode = $pc->decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg);
\think\Log::info('解密结果错误码: ' . $errCode);
if ($errCode == 0) {
\think\Log::info('解密成功,消息内容: ' . $msg);
// 解析XML
$xml = simplexml_load_string($msg, 'SimpleXMLElement', LIBXML_NOCDATA);
// 转换为数组
$json = json_encode($xml, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
$arr = json_decode($json, true);
\think\Log::info('解析后的数组: ' . json_encode($arr));
// 处理不同类型的消息
$infoType = $arr['InfoType'] ?? '';
switch ($infoType) {
case 'component_verify_ticket':
// 保存ComponentVerifyTicket
$appId = $arr['AppId'] ?? '';
$ticket = $arr['ComponentVerifyTicket'] ?? '';
if ($appId && $ticket) {
$key = "ComponentVerifyTicket";
$this->redis->set($key, $ticket, 600); // 设置10分钟过期,微信10分钟推送一次
\think\Log::info('已保存ComponentVerifyTicket,AppId: ' . $appId);
}
break;
case 'authorized':
// 授权成功通知
$authorizerAppid = $arr['AuthorizerAppid'] ?? '';
$authorizationCode = $arr['AuthorizationCode'] ?? '';
$authorizationCodeExpiredTime = $arr['AuthorizationCodeExpiredTime'] ?? '';
\think\Log::error('授权成功通知: ' . json_encode($arr));
// 保存授权码到Redis
$authCodeKey = "App:{$authorizerAppid}:authorization_code";
$this->redis->set($authCodeKey, $authorizationCode, 600);
// 拉取权限集合
$func_info = [];
$this->getAuthorizerRefreshToken($authorizerAppid, $func_info);
\think\Log::error('权限集合: ' . json_encode($func_info));
// 保存到数据库
$exit = $this->AppModel->where('app_id', $authorizerAppid)->find();
\think\Log::error('是否存在记录: ' . json_encode($exit));
if($exit){
$exit->update([
"authorization_code" => $authorizationCode,
"is_use" => 1,
"func_info" => json_encode($func_info),
"authorization_code_expired_time" => $authorizationCodeExpiredTime,
"update_time" => time()
]);
}else{
$result = $this->AppModel->create([
"app_id"=> $authorizerAppid,
"authorization_code" => $authorizationCode,
"is_use" => 1,
"func_info" => json_encode($func_info),
"authorization_code_expired_time" => $authorizationCodeExpiredTime,
"update_time" => time()
]);
\think\Log::error('不存在记录新增: ' . json_encode($result));
}
break;
case 'updateauthorized':
$authorizerAppid = $arr['AuthorizerAppid'] ?? '';
$authorizationCode = $arr['AuthorizationCode'] ?? '';
$authorizationCodeExpiredTime = $arr['AuthorizationCodeExpiredTime'] ?? '';
\think\Log::error('授权更新通知: ' . json_encode($arr));
// 保存授权码到Redis
$authCodeKey = "App:{$authorizerAppid}:authorization_code";
$this->redis->set($authCodeKey, $authorizationCode, 600);
$func_info = [];
$this->getAuthorizerRefreshToken($authorizerAppid, $func_info);
$exit = $this->AppModel->where('app_id', $authorizerAppid);
if($exit){
$exit->update([
"authorization_code" => $authorizationCode,
"is_use" => 1,
"func_info" => json_encode($func_info),
"authorization_code_expired_time" => $authorizationCodeExpiredTime,
"update_time" => time()
]);
}else{
$this->AppModel->create([
"app_id"=> $authorizerAppid,
"authorization_code" => $authorizationCode,
"is_use" => 1,
"func_info" => json_encode($func_info),
"authorization_code_expired_time" => $authorizationCodeExpiredTime,
"update_time" => time()
]);
}
break;
case 'unauthorized':
$authorizerAppid = $arr['AuthorizerAppid'] ?? '';
\think\Log::error('取消授权通知: ' . json_encode($arr));
// 清理Redis中的相关数据
$keys = [
"App:{$authorizerAppid}:authorization_code",
"App:{$authorizerAppid}:authorizer_refresh_token",
"App:{$authorizerAppid}:AuthorizerAccessToken"
];
foreach ($keys as $key) {
$this->redis->del($key);
}
$this->AppModel->where('app_id', $authorizerAppid)
->update([
"is_use" => 0,
"func_info" => "",
"update_time" => time()
]);
break;
default:
\think\Log::info('未知的InfoType: ' . $infoType);
break;
}
echo 'success';
return;
} else {
\think\Log::error('解密失败,错误码: ' . $errCode);
echo "fail";
return;
}
} catch (\Exception $e) {
\think\Log::error('微信回调处理异常: ' . $e->getMessage());
echo "fail";
return;
}
}
/**
* 验证URL有效性(首次配置时使用)
*/
private function verifyUrl($signature, $timestamp, $nonce, $echostr, $token)
{
$tmpArr = [$token, $timestamp, $nonce];
\think\Log::error('URL验证: ' . json_encode([
'signature' => $token,
'tmpStr' => $timestamp,
'match' => $nonce,
'echostr'=>$echostr
]));
sort($tmpArr, SORT_STRING);
$tmpStr = implode($tmpArr);
$tmpStr = sha1($tmpStr);
\think\Log::error('URL验证: ' . json_encode([
'signature' => $signature,
'tmpStr' => $tmpStr,
'match' => $tmpStr == $signature
]));
if ($tmpStr == $signature) {
return $echostr;
} else {
return "验证失败";
}
}
private function verifyUrlQw($signature, $timestamp, $nonce, $echostr, $token)
{
$tmpArr = [$token, $timestamp, $nonce,$echostr];
sort($tmpArr, SORT_STRING);
$tmpStr = implode($tmpArr);
$tmpStr = sha1($tmpStr);
\think\Log::error('URL验证: ' . json_encode([
'signature' => $signature,
'tmpStr' => $tmpStr,
'match' => $tmpStr == $signature
]));
if ($tmpStr == $signature) {
return $echostr;
} else {
return -1;
}
}
private function create_preauthcode()
{
$preauthcode = $this->redis->get("preauthcode");
if (!$preauthcode) {
$component_token = $this->component_token();
if (!$component_token) {
throw new Exception("component_token获取失败");
}
$body = [
'component_appid' => $this->appId
];
$url = "https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token={$component_token}";
$options = [
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => ['Content-Type: application/json']
];
$req = Http::sendRequest($url, json_encode($body), 'POST', $options);
$result = json_decode($req['msg'], true);
if (isset($result['pre_auth_code'])) {
$this->redis->set("preauthcode", $result['pre_auth_code'], $result['expires_in']);
return $result['pre_auth_code'];
} else {
throw new Exception("创建预授权码失败: " . json_encode($result));
}
}
return $preauthcode;
}
private function component_token()
{
try {
$component_token = $this->redis->get("component_access_token");
if ($component_token) {
return $component_token;
}
$ComponentVerifyTicket = $this->redis->get("ComponentVerifyTicket");
if (!$ComponentVerifyTicket) {
throw new Exception("ComponentVerifyTicket不存在,请等待10分钟后再试");
}
$body = [
'component_appsecret' => $this->appSecret,
'component_appid' => $this->appId,
'component_verify_ticket' => $ComponentVerifyTicket
];
$url = "https://api.weixin.qq.com/cgi-bin/component/api_component_token";
$options = [
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => ['Content-Type: application/json']
];
$req = Http::sendRequest($url, json_encode($body), 'POST', $options);
$result = json_decode($req['msg'], true);
if (isset($result['component_access_token'])) {
$this->redis->set("component_access_token", $result['component_access_token'], $result['expires_in'] - 300);
return $result['component_access_token'];
} else {
throw new Exception("获取component_token失败: " . json_encode($result));
}
} catch (Exception $e) {
throw new Exception($e->getMessage());
}
}
private function getAuthUrl($type, $view, $state = '')
{
$component_token = $this->component_token();
$preauthcode = $this->create_preauthcode();
// 回调地址需携带 auth 传入的 state:微信只额外回传 auth_code/expires_in,
// 不带 state 时 authNotic 无法定位授权上下文
$redirectUri = "https://ye4s.wms.gztbyc.com/index/index/authNotic";
if (!empty($state)) {
$redirectUri .= '?state=' . urlencode($state);
}
$redirect_uri = urlencode($redirectUri);
switch ($view) {
case 'pc':
$url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid={$this->appId}&pre_auth_code={$preauthcode}&redirect_uri={$redirect_uri}&auth_type={$type}";
break;
case 'mobile':
$url = "https://open.weixin.qq.com/wxaopen/safe/bindcomponent?action=bindcomponent&no_scan=1&component_appid={$this->appId}&pre_auth_code={$preauthcode}&redirect_uri={$redirect_uri}&auth_type={$type}#wechat_redirect";
break;
default:
$url = "";
}
return $url;
}
public function authNotic($state=null) {
try {
\think\Log::info('授权回调 authNotic: ' . json_encode([
'state' => $state,
'auth_code' => $this->request->get('auth_code', '')
]));
// 1. 基础验证
if (empty($state) || empty($this->request->get('auth_code'))) {
return view('error', ['msg' => '参数不完整']);
}
// 2. 从Redis获取state信息(跨系统共享)
$stateKey = 'auth_state:' . $state;
$stateInfo = $this->redis->get($stateKey);
if (!$stateInfo) {
// state已过期或不存在
return view('error', ['msg' => '授权链接已过期,请重新发起授权']);
}
$stateData = json_decode($stateInfo, true);
$storeId = $stateData['store_id'] ?? 0;
$userId = $stateData['user_id'] ?? 0;
// 3. 检查是否已设置开始时间(防重入)
$startTimeKey = $stateKey . '_start';
$startTime = $this->redis->get($startTimeKey);
if (!$startTime) {
$this->redis->setex($startTimeKey, 600, time()); // 10分钟过期
$startTime = time();
}
// 4. 检查超时(10分钟)
if ((time() - $startTime) > 600) {
$this->redis->del($stateKey, $startTimeKey); // 清理过期数据
return view('error', ['msg' => '授权已超时,请重新授权']);
}
$authCode = $this->request->get('auth_code');
$expiresIn = $this->request->get('expires_in', 3600);
// 5. 查找待绑定的应用记录
$appRecord = $this->AppModel->where([
'authorization_code' => $authCode,
'store_id' => null // 仅查找未绑定的
])->find();
if ($appRecord) {
// 6. 执行绑定
$appRecord->save([
'store_id' => $storeId,
'user_id' => $userId,
'bind_time' => time(),
'update_time' => time()
]);
// 7. 清理state和开始时间
$this->redis->del($stateKey, $startTimeKey);
// 8. 存储成功标识供前端轮询
$successKey = 'auth_success:' . $state;
$this->redis->setex($successKey, 300, json_encode([
'status' => 'success',
'app_id' => $appRecord->app_id,
'store_id' => $storeId,
'time' => time()
]));
// 直接跳转到成功页
$this->redirect(url('index/index/authResult', ['state' => $state, 'status' => 'success']));
return;
}
// 9. 应用记录不存在(事件推送未到)
// 存储待匹配信息
$pendingKey = 'auth_pending:' . $authCode;
$pendingData = [
'state' => $state,
'store_id' => $storeId,
'user_id' => $userId,
'auth_code' => $authCode,
'expires_in' => $expiresIn,
'created_at' => time()
];
$this->redis->setex($pendingKey, 600, json_encode($pendingData));
// 10. 存储前端轮询标识
$pollingKey = 'auth_polling:' . $state;
$this->redis->setex($pollingKey, 600, json_encode([
'status' => 'pending',
'start_time' => $startTime,
'auth_code' => $authCode,
'store_id' => $storeId
]));
// 11. 传递参数到等待页
$this->assign([
'state' => $state,
'auth_code' => $authCode,
'start_time' => $startTime,
'timeout' => 600,
'polling_interval' => 5000 // 5秒轮询一次
]);
return $this->view->fetch('auth_waiting');
} catch (\Exception $e) {
\think\Log::error('授权回调处理异常:' . $e->getMessage() . ' @ ' . $e->getFile() . ':' . $e->getLine() . "\n" . $e->getTraceAsString());
// 调试期直接输出异常信息
return view('error', ['msg' => $e->getMessage() . ' @ ' . basename($e->getFile()) . ':' . $e->getLine()]);
}
}
public function auth($state)
{
// 获取参数
$type = $this->request->get('type', 3); // 默认授权所有权限
$view = $this->request->get('view', 'pc'); // 默认PC端
$appid = $this->request->get('appid', ''); // 可选:指定要授权的公众号appid
$storeId = (int)$this->request->get('store_id', 0); // 门店ID,由跳转方通过URL带入
$userId = (int)$this->request->get('user_id', 0); // 用户ID,由跳转方通过URL带入
// 写入授权上下文,供 authNotic 回跳时读取(跨系统共享)
$stateKey = 'auth_state:' . $state;
$stateData = [
'store_id' => $storeId,
'user_id' => $userId,
'create_time' => time()
];
$this->redis->setex($stateKey, 600, json_encode($stateData, JSON_UNESCAPED_UNICODE));
\think\Log::info('授权页写入 auth_state: ' . $stateKey . ' => ' . json_encode($stateData, JSON_UNESCAPED_UNICODE));
if (empty($storeId) && empty($userId)) {
\think\Log::error('授权页缺少 store_id/user_id 参数,authNotic 绑定将无法定位门店: state=' . $state);
}
// 生成授权链接(把 state 带入回调地址,微信回跳 authNotic 时才能还原上下文)
$authUrl = $this->getAuthUrl($type, $view, $state);
if (empty($authUrl)) {
$this->error('获取授权链接失败,请检查配置');
}
// 如果是移动端,显示页面让用户点击
$this->assign([
'authUrl' => $authUrl,
'appid' => $appid,
'type' => $type,
'view' => $view,
'state' => $state
]);
return $this->view->fetch('auth');
}
private function getAuthorizerRefreshToken($appid, &$func_info)
{
$key2 = "App:{$appid}:authorizer_refresh_token";
$authorizer_refresh_token = $this->redis->get($key2);
if ($authorizer_refresh_token) {
return $authorizer_refresh_token;
}
try {
$component_access_token = $this->component_token();
$key = "App:{$appid}:authorization_code";
$authorization_code = $this->redis->get($key);
if (!$authorization_code) {
$app = $this->AppModel->where('app_id', $appid)->find();
if($app){
$authorization_code = $app['authorization_code'];
}else{
throw new Exception("授权码不存在");
}
}
$body = [
'component_appid' => $this->appId,
'authorization_code' => $authorization_code
];
$url = "https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token={$component_access_token}";
$options = [
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => ['Content-Type: application/json']
];
$req = Http::sendRequest($url, json_encode($body), 'POST', $options);
$result = json_decode($req['msg'], true);
if (isset($result['authorization_info'])) {
$authorization_info = $result['authorization_info'];
$func_info = $authorization_info['func_info'] ?? [];
$this->redis->set($key2, $authorization_info["authorizer_refresh_token"], 30 * 24 * 3600);
$this->redis->set("App:{$appid}:AuthorizerAccessToken",
$authorization_info["authorizer_access_token"],
$authorization_info["expires_in"] - 300);
return $authorization_info["authorizer_refresh_token"];
} else {
throw new Exception("获取authorizer_refresh_token失败: " . json_encode($result));
}
} catch (Exception $e) {
throw new Exception($e->getMessage());
}
}
private function getAuthorizerAccessToken($appid)
{
$key = "App:{$appid}:AuthorizerAccessToken";
$AuthorizerAccessToken = $this->redis->get($key);
if ($AuthorizerAccessToken) {
return $AuthorizerAccessToken;
}
try {
$component_access_token = $this->component_token();
$refresh_token_key = "App:{$appid}:authorizer_refresh_token";
$authorizer_refresh_token = $this->redis->get($refresh_token_key);
if (!$authorizer_refresh_token) {
// 如果refresh_token不存在,重新获取
$func_info = [];
$authorizer_refresh_token = $this->getAuthorizerRefreshToken($appid, $func_info);
}
$body = [
'component_appid' => $this->appId,
'authorizer_appid' => $appid,
'authorizer_refresh_token' => $authorizer_refresh_token
];
$url = "https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token={$component_access_token}";
$options = [
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => ['Content-Type: application/json']
];
$req = Http::sendRequest($url, json_encode($body), 'POST', $options);
$result = json_decode($req['msg'], true);
if (isset($result['authorizer_access_token'])) {
$this->redis->set($key, $result["authorizer_access_token"], $result["expires_in"] - 300);
$this->redis->set($refresh_token_key, $result["authorizer_refresh_token"], 30 * 24 * 3600);
return $result["authorizer_access_token"];
} else {
throw new Exception("获取authorizer_access_token失败: " . json_encode($result));
}
} catch (Exception $e) {
throw new Exception($e->getMessage());
}
}
/**
* 转发原始请求到多个环境(默认:qimen + 测试环境)
* @param string $path 目标路径
* @param string $rawBody 原始报文(POST body)
* @param array|string $hosts 目标域名(可传单个字符串)
* @return array 每个目标地址的转发结果
*/
private function forwardToTest($path, $rawBody = '', $hosts = [
'http://qimen.wms.gztbyc.com',
'http://test_wms.o.gztbyc.com',
])
{
if (is_string($hosts)) {
$hosts = [$hosts];
}
// 原始GET参数(所有环境共用)
$query = $this->request->get();
$results = [];
foreach ($hosts as $host) {
$url = rtrim($host, '/') . '/' . ltrim($path, '/');
if (!empty($query)) {
$url .= (stripos($url, '?') !== false ? '&' : '?') . http_build_query($query);
}
try {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $rawBody);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Expect:', 'Content-Type: text/xml']);
$response = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
\think\Log::error('转发失败: ' . $url . ' 错误: ' . $error);
$results[$url] = false;
continue;
}
\think\Log::info('转发成功: ' . $url . ' 返回: ' . $response);
$results[$url] = true;
} catch (\Exception $e) {
\think\Log::error('转发异常: ' . $url . ' 错误: ' . $e->getMessage());
$results[$url] = false;
}
}
return $results;
}
/**
* 修复XML编码问题
*/
private function fixXmlEncoding($xml)
{
// 1. 去除首尾空白
$xml = trim($xml);
// 2. 替换全角字符
$xml = str_replace(['<', '>', '"', ''', '&'], ['<', '>', '"', "'", '&'], $xml);
// 3. 修复转义的斜杠
$xml = str_replace('<\/', '</', $xml);
$xml = str_replace('\/', '/', $xml);
// 4. 确保以<xml>开头
if (substr($xml, 0, 5) != '<xml>') {
$start = stripos($xml, '<xml>');
if ($start !== false) {
$xml = substr($xml, $start);
} else {
$xml = '<xml>' . $xml . '</xml>';
}
}
return $xml;
}
/**
* 处理小程序/公众号事件推送
*/
public function events($appid)
{
try {
// 验证请求
$signature = $this->request->get('signature', '');
$timestamp = $this->request->get('timestamp', '');
$nonce = $this->request->get('nonce', '');
// 获取原始POST数据
$postData = file_get_contents('php://input');
// 验证消息体签名
$msg_signature = $this->request->get('msg_signature', '');
// 首次验证
$echostr = $this->request->get('echostr', '');
if ($echostr) {
return $this->verifyEventUrl($signature, $timestamp, $nonce, $echostr, $appid);
}
// 处理事件推送
if (empty($postData)) {
\think\Log::error('事件推送数据为空: ' . $appid);
return "success";
}
// 解密消息
$xml = $this->fixXmlEncoding($postData);
$pc = new \app\index\library\wechat\open\WXBizMsgCrypt($this->token, $this->encodingAesKey, $this->appId);
$errCode = $pc->decryptMsg($msg_signature, $timestamp, $nonce, $xml, $msg);
if ($errCode == 0) {
// 解析XML
$xmlObj = simplexml_load_string($msg, 'SimpleXMLElement', LIBXML_NOCDATA);
$json = json_encode($xmlObj, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
$data = json_decode($json, true);
// 记录日志
\think\Log::error('事件推送数据[' . $appid . ']: ' . json_encode($data));
// 处理不同事件类型
$msgType = $data['MsgType'] ?? '';
$event = $data['Event'] ?? '';
switch ($msgType) {
case 'event':
$this->handleEvent($appid, $event, $data);
break;
case 'text':
$result = $this->handleTextMessage($appid, $data,$nonce);
if($result["reply"]){
\think\Log::error('回复信息: '.$result["msg"]);
return $result["msg"];
}else{
return "";
}
break;
case 'image':
$this->handleImageMessage($appid, $data);
break;
// 可以继续添加其他消息类型的处理
}
} else {
\think\Log::error('事件消息解密失败[' . $appid . ']: ' . $errCode);
}
// 返回success表示处理成功
return "success";
} catch (Exception $e) {
\think\Log::error('事件推送处理异常[' . $appid . ']: ' . $e->getMessage());
return "success";
}
}
/**
* 验证事件推送URL
*/
private function verifyEventUrl($signature, $timestamp, $nonce, $echostr, $appid)
{
// 获取对应小程序的配置信息
$appInfo = $this->AppModel->where('app_id', $appid)->find();
if (!$appInfo) {
return "appid not found";
}
\think\Log::info('URL验证: ' . json_encode([
'signature' => $signature,
'tmpStr' => $tmpStr,
'match' => $tmpStr == $signature
]));
// 使用小程序的token验证
$token = $appInfo['token'] ?? $this->token;
$tmpArr = [$token, $timestamp, $nonce];
sort($tmpArr, SORT_STRING);
$tmpStr = implode($tmpArr);
$tmpStr = sha1($tmpStr);
if ($tmpStr == $signature) {
return $echostr;
} else {
return "验证失败";
}
}
/**
* 处理事件类型消息
*/
private function handleEvent($appid, $event, $data)
{
switch ($event) {
case 'subscribe':
// 关注事件
$this->handleSubscribeEvent($appid, $data);
break;
case 'unsubscribe':
// 取消关注事件
$this->handleUnsubscribeEvent($appid, $data);
break;
case 'SCAN':
// 扫码事件
$this->handleScanEvent($appid, $data);
break;
case 'CLICK':
// 菜单点击事件
$this->handleClickEvent($appid, $data);
break;
case 'VIEW':
// 菜单跳转事件
$this->handleViewEvent($appid, $data);
break;
case 'TEMPLATESENDJOBFINISH':
// 模板消息发送完成
$this->handleTemplateSendJobFinish($appid, $data);
break;
// 可以添加更多事件处理
}
}
/**
* 处理关注事件
*/
private function handleSubscribeEvent($appid, $data)
{
$openid = $data['FromUserName'] ?? '';
$eventKey = $data['EventKey'] ?? ''; // 二维码参数
// 记录用户关注
$this->recordUserAction($appid, $openid, 'subscribe', [
'event_key' => $eventKey,
'time' => $data['CreateTime'] ?? time()
]);
// 可以发送欢迎消息
$this->sendWelcomeMessage($appid, $openid);
}
/**
* 处理取消关注事件
*/
private function handleUnsubscribeEvent($appid, $data)
{
$openid = $data['FromUserName'] ?? '';
// 记录用户取消关注
$this->recordUserAction($appid, $openid, 'unsubscribe', [
'time' => $data['CreateTime'] ?? time()
]);
}
/**
* 处理文本消息
*/
private function handleTextMessage($appid, $data,$nonce)
{
$openid = $data['FromUserName'] ?? '';
$appName = $data['ToUserName'] ?? '';
$content = $data['Content'] ?? '';
// 记录用户消息
$this->recordUserAction($appid, $openid, 'text', [
'content' => $content,
'time' => $data['CreateTime'] ?? time()
]);
\think\Log::error('handleTextMessage处理消息: '.json_encode($data));
// 可以添加自动回复逻辑
$result = $this->autoReply($appid,$appName, $openid, $content,$nonce);
return $result;
}
/**
* 处理图片消息
*/
private function handleImageMessage($appid, $data)
{
$openid = $data['FromUserName'] ?? '';
$picUrl = $data['PicUrl'] ?? '';
$mediaId = $data['MediaId'] ?? '';
// 记录用户消息
$this->recordUserAction($appid, $openid, 'image', [
'pic_url' => $picUrl,
'media_id' => $mediaId,
'time' => $data['CreateTime'] ?? time()
]);
}
/**
* 记录用户行为
*/
private function recordUserAction($appid, $openid, $action, $data = [])
{
try {
// 这里可以保存到数据库
$key = "UserAction:{$appid}:{$openid}:" . time();
$this->redis->setex($key, 86400, json_encode([
'appid' => $appid,
'openid' => $openid,
'action' => $action,
'data' => $data,
'time' => time()
]));
// 也可以保存到MySQL
// $userActionModel = new \app\common\model\UserAction();
// $userActionModel->save([
// 'app_id' => $appid,
// 'openid' => $openid,
// 'action' => $action,
// 'data' => json_encode($data),
// 'create_time' => time()
// ]);
} catch (Exception $e) {
\think\Log::error('记录用户行为失败: ' . $e->getMessage());
}
}
/**
* 发送欢迎消息
*/
private function sendWelcomeMessage($appid, $openid)
{
try {
$accessToken = $this->getAuthorizerAccessToken($appid);
$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$accessToken}";
$message = [
'touser' => $openid,
'msgtype' => 'text',
'text' => [
'content' => '欢迎关注!感谢您的支持!'
]
];
$options = [
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => ['Content-Type: application/json']
];
Http::sendRequest($url, json_encode($message), 'POST', $options);
} catch (Exception $e) {
\think\Log::error('发送欢迎消息失败: ' . $e->getMessage());
}
}
private function sendMessage($appid, $openid,$content)
{
try {
$accessToken = $this->getAuthorizerAccessToken($appid);
$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$accessToken}";
$message = [
'touser' => $openid,
'msgtype' => 'text',
'text' => [
'content' => $content
]
];
$options = [
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => ['Content-Type: application/json']
];
\think\Log::error('发送客服消息报文: ' . json_encode($message));
$request = Http::sendRequest($url, json_encode($message), 'POST', $options);
\think\Log::error('接收发送客服消息报文: ' . json_encode($request));
} catch (Exception $e) {
\think\Log::error('发送消息失败: ' . $e->getMessage());
}
}
/**
* 自动回复
*/
private function autoReply($appid, $appName, $openid, $content,$nonce)
{
\think\Log::error('触发自动回复: '.$content);
$noReply = false;
try {
$accessToken = $this->getAuthorizerAccessToken($appid);
$replyContent = '';
// 简单的关键词回复
if (strpos($content, '你好') !== false || strpos($content, 'hello') !== false) {
$replyContent = '你好!有什么可以帮您的吗?';
} elseif (strpos($content, '帮助') !== false || strpos($content, 'help') !== false) {
$replyContent = '输入以下关键词获取帮助:\n1. 功能 - 查看功能列表\n2. 关于 - 了解更多信息';
} elseif(strpos($content,'TESTCOMPONENT_MSG_TYPE_TEXT')!== false){
$replyContent = "TESTCOMPONENT_MSG_TYPE_TEXT_callback";
} elseif(strpos($content,'QUERY_AUTH_CODE')!== false){
$replyContent = "";
$noReply = true;
$new_content = str_replace('QUERY_AUTH_CODE:', '', $content);
$this->sendMessage($appid, $openid,$new_content."_from_api");
}else {
// 默认回复
$replyContent = '收到您的消息:' . $content . '\n我会尽快回复您!';
}
$pc = new \app\index\library\wechat\open\WXBizMsgCrypt($this->token, $this->encodingAesKey, $this->appId);
$timeStamp = time();
$text = "<xml>
<ToUserName><![CDATA[{$openid}]]></ToUserName>
<FromUserName><![CDATA[{$appName}]]></FromUserName>
<CreateTime>{$timeStamp}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[{$replyContent}]]></Content>
</xml>";
$errCode = $pc->encryptMsg($text, $timeStamp, $nonce, $encryptMsg);
if($errCode!==0){
\think\Log::error('加密出错: ' . $errCode);
}
$result = [
"reply"=>$errCode==0&&!$noReply,
"msg"=>$encryptMsg
];
return $result;
} catch (Exception $e) {
\think\Log::error('自动回复失败: ' . $e->getMessage());
}
}
/**
* 获取授权的小程序/公众号列表
*/
public function getAuthorizerList()
{
try {
$component_access_token = $this->component_token();
$offset = $this->request->get('offset', 0);
$count = $this->request->get('count', 100);
$body = [
'component_appid' => $this->appId,
'offset' => $offset,
'count' => $count
];
$url = "https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_list?component_access_token={$component_access_token}";
$options = [
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => ['Content-Type: application/json']
];
$req = Http::sendRequest($url, json_encode($body), 'POST', $options);
$result = json_decode($req['msg'], true);
if (isset($result['list'])) {
return json([
'code' => 0,
'msg' => 'success',
'data' => $result['list'],
'total' => $result['total_count'] ?? 0
]);
} else {
return json([
'code' => 1,
'msg' => '获取失败: ' . json_encode($result)
]);
}
} catch (Exception $e) {
return json([
'code' => 1,
'msg' => '获取异常: ' . $e->getMessage()
]);
}
}
/**
* 获取授权的小程序/公众号信息
*/
public function getAuthorizerInfo($appid)
{
try {
$component_access_token = $this->component_token();
$body = [
'component_appid' => $this->appId,
'authorizer_appid' => $appid
];
$url = "https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token={$component_access_token}";
$options = [
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => ['Content-Type: application/json']
];
$req = Http::sendRequest($url, json_encode($body), 'POST', $options);
$result = json_decode($req['msg'], true);
if (isset($result['authorizer_info'])) {
return json([
'code' => 0,
'msg' => 'success',
'data' => $result
]);
} else {
return json([
'code' => 1,
'msg' => '获取失败: ' . json_encode($result)
]);
}
} catch (Exception $e) {
return json([
'code' => 1,
'msg' => '获取异常: ' . $e->getMessage()
]);
}
}
public function create_qrcode($appid){
try {
$component_access_token = $this->getAuthorizerAccessToken($appid);
$body = [
'expire_seconds' => 600,
'action_name' => "QR_STR_SCENE",
'action_info'=>["scene"=>["scene_id"=>123,"scene_str"=>"12462"]]
];
$url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={$component_access_token}";
$options = [
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => ['Content-Type: application/json']
];
$req = Http::sendRequest($url, json_encode($body), 'POST', $options);
$result = json_decode($req['msg'], true);
return json($result);
} catch (Exception $e) {
return json([
'code' => 1,
'msg' => '获取异常: ' . $e->getMessage()
]);
}
}
public function getMiniCode($appid){
try {
$component_access_token = $this->getAuthorizerAccessToken($appid);
$body = [
'expire_seconds' => 600,
'action_name' => "QR_STR_SCENE",
'action_info'=>["scene"=>["scene_id"=>123,"scene_str"=>"12462"]]
];
$url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$component_access_token}";
$options = [
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => ['Content-Type: application/json']
];
$req = Http::sendRequest($url, json_encode($body), 'POST', $options);
$result = json_decode($req['msg'], true);
return json($result);
} catch (Exception $e) {
return json([
'code' => 1,
'msg' => '获取异常: ' . $e->getMessage()
]);
}
}
public function services($page){
try {
$articleModel = new \app\common\model\Bwg;
// 查询文章
$article = $articleModel->find($page);
if (!$article) {
// 文章不存在,跳转到错误页面或列表页
return redirect('/404')->with('error', '文章不存在');
}
// 将文章数据赋值给模板
$this->assign([
'article' => $article,
'title' => $article->title
]);
return $this->view->fetch();
} catch (\Exception $e) {
// 异常处理
return $this->view->fetch('error', [
'msg' => '系统错误:' . $e->getMessage()
]);
}
}
function aes_decrypt($encryptedMsg, $aesKey) {
try {
// 1. 对密文进行 Base64 解码
$aesMsg = base64_decode($encryptedMsg);
if ($aesMsg === false) {
throw new Exception('Base64 解码失败');
}
// 2. 使用 AESKey 进行 AES 解密
// 微信使用的是 AES-256-CBC 模式,PKCS#7 填充
$decrypted = openssl_decrypt(
$aesMsg,
'AES-256-CBC',
$aesKey,
OPENSSL_NO_PADDING, // 注意这里:先不要自动去除填充,我们手动处理
'' // IV 是空的,因为微信使用的是全零 IV
);
if ($decrypted === false) {
throw new Exception('OpenSSL 解密失败');
}
// 3. 手动去除 PKCS#7 填充
$pad = ord(substr($decrypted, -1));
$padLength = $pad;
// 验证填充长度是否有效
if ($padLength < 1 || $padLength > 32) {
$padLength = 0;
}
$decrypted = substr($decrypted, 0, strlen($decrypted) - $padLength);
return $decrypted;
} catch (Exception $e) {
// 错误处理
\think\Log::info('AES 解密失败: ' . $e->getMessage());
return false;
}
}
}