Files
transmit/app/utils/Cf7InquiryClient.php
T

94 lines
2.6 KiB
PHP
Raw Normal View History

2025-12-15 02:22:19 +00:00
<?php
namespace app\utils;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
/**
* 通用的 CF7 + Advanced CF7 DB 询盘客户端
*
* 支持多站点使用:
* - 每个站点 new 一个实例(传入 baseUri + auth)
* - 调用 fetchForms / fetchEntries 获取对应站点的数据
*/
class Cf7InquiryClient
{
protected Client $client;
/** 站点基础地址,例如:https://hesupipe.com */
protected string $baseUri;
/** 构造函数:传入当前要访问的 WP 站点配置 */
public function __construct(string $baseUri, string $username, string $password, array $options = [])
{
$this->baseUri = rtrim($baseUri, '/');
$config = [
'base_uri' => $this->baseUri,
'auth' => [$username, $password],
'timeout' => $options['timeout'] ?? 10,
'verify' => $options['verify'] ?? false, // 正式环境建议改成 true
];
$this->client = new Client($config);
}
/**
* 获取当前站点的 CF7 表单列表(从 Advanced CF7 DB 推断)
* 对应插件里的 /acf7db/v1/forms
*
* @return array
* @throws GuzzleException
*/
public function fetchForms(): array
{
$response = $this->client->get('/wp-json/acf7db/v1/forms');
$body = (string)$response->getBody();
return json_decode($body, true) ?: [];
}
/**
* 获取 Advanced CF7 DB 询盘列表(存量 + 增量通用)
*
* @param int $cf7Id 表单 ID(可选,为 0 时表示所有表单)
* @param int $lastId 上次同步到的最大 submit_id
* @param int $perPage 每次拉取数量
* @param string|null $from 起始时间(可选,Y-m-d H:i:s)
* @param string|null $to 结束时间(可选)
*
* @return array ['data' => [...], 'meta' => [...]]
* @throws GuzzleException
*/
public function fetchEntries(
int $cf7Id = 0,
int $lastId = 0,
int $perPage = 200,
?string $from = null,
?string $to = null
): array {
$query = [
'last_id' => $lastId,
'per_page' => $perPage,
];
if ($cf7Id > 0) {
$query['cf7_id'] = $cf7Id;
}
if ($from) {
$query['from'] = $from;
}
if ($to) {
$query['to'] = $to;
}
$response = $this->client->get('/wp-json/acf7db/v1/entries', [
'query' => $query,
]);
$body = (string)$response->getBody();
return json_decode($body, true) ?: ['data' => [], 'meta' => []];
}
}