
本文详解 Xero PHP SDK 中 getContacts() 方法的搜索参数用法,指出常见误区——误加 SearchTerm= 前缀导致全量返回,并提供正确调用方式、完整代码示例及关键注意事项。
本文详解 xero php sdk 中 getcontacts() 方法的搜索参数用法,指出常见误区——误加 searchterm= 前缀导致全量返回,并提供正确调用方式、完整代码示例及关键注意事项。
在使用 xero-php-oauth2 SDK 调用 Xero Accounting API 搜索联系人时,一个高频错误是:手动拼接 SearchTerm= 查询参数。SDK 的 getContacts($xeroTenantId, $searchTerm) 方法已内置参数序列化逻辑,会自动将 $searchTerm 作为 searchTerm 查询参数加入 URL(即 ?searchTerm=xxx)。若你在 $searchTerm 中显式写成 "SearchTerm=john@example.com",最终请求 URL 将变为:
.../Contacts?searchTerm=SearchTerm%3Djohn%40example.com
Xero API 无法识别该非法值,因而忽略搜索条件,退化为无条件获取全部联系人(分页默认 100 条,但看似“全量”)。
✅ 正确做法是:直接传入纯搜索字符串(如邮箱、姓名或电话),无需任何前缀:
$searchTerm = "[email protected]"; // ✅ 纯字符串,不带 SearchTerm= $result = $apiInstance->getContacts($xeroTenantId, $searchTerm);
完整可运行示例(含错误处理与结果提取):
立即学习“PHP免费学习笔记(深入)”;
$storage = new StorageClass();
$xeroTenantId = (string) $storage->getSession()->tenant_id;
$config = XeroAPI\XeroPHP\Configuration::getDefaultConfiguration()
->setAccessToken((string) $storage->getSession()->token);
$apiInstance = new XeroAPI\XeroPHP\Api\AccountingApi(
new GuzzleHttp\Client(),
$config
);
$searchTerm = "[email protected]"; // 注意:此处仅为示例,请替换为实际用户邮箱
try {
$response = $apiInstance->getContacts($xeroTenantId, $searchTerm);
// 获取匹配的联系人列表(注意:即使只匹配1个,也返回 ContactCollection 对象)
$contacts = $response->getContacts();
if ($contacts && count($contacts) > 0) {
foreach ($contacts as $contact) {
echo "Found: " . $contact->getName() . " (" . $contact->getEmail() . ")\n";
}
} else {
echo "No contacts found matching '$searchTerm'.\n";
}
} catch (XeroAPI\XeroPHP\ApiException $e) {
error_log("Xero API Error: " . $e->getMessage());
echo "Failed to search contacts: " . $e->getMessage();
} catch (Exception $e) {
error_log("General Error: " . $e->getMessage());
echo "Unexpected error: " . $e->getMessage();
}⚠️ 关键注意事项:
-
搜索范围限定:Xero 的
searchTerm仅在Name、EmailAddress、ContactNumber字段中进行模糊匹配(不区分大小写),不支持精确匹配或字段限定语法(如Email:[email protected]); -
大小写无关,但需完整邮箱:
[email protected]可匹配,但[email](@example.com)(缺少用户名)通常无法命中; -
分页与性能:即使指定
searchTerm,Xero 仍按默认分页(page=1,pageSize=100)返回;如需更多结果,需配合page参数循环请求; -
认证与租户有效性:确保
$storage->getSession()->token未过期,且$xeroTenantId有效(多租户场景下易出错); -
调试建议:启用 SDK 日志(设置
debug => true在 Guzzle Client 配置中),查看实际发出的 HTTP 请求 URL 和响应体,快速定位参数问题。
遵循以上规范,即可精准检索目标联系人,避免无效全量拉取,提升 WordPress 插件(如集成 PMPro)的性能与用户体验。



















