php - 尝试通过 ActiveCampain API (Laravel) 添加联系人
问题描述
我正在尝试将 ActiveCampaing 的 RESTFUL API 集成到我的 Laravel 环境中,但我没有那么幸运,我正在使用 GuzzleHttp 发出请求,这是错误图像和我的代码:
$client = new \GuzzleHttp\Client([‘base_uri’ => ‘https://myaccount.api-us1.com/api/3/’]);
$response = $client->request('POST', 'contacts', [
'headers' => [
'Api-Token' => 'xxx',
'api_action' => 'contact_add',
],
'json' => [
'email' => 'test2021@test.com',
'first_name' => 'Julian',
'last_name' => 'Carax',
]
]);
echo $response->getStatusCode(); // 200
echo $response->getBody();
希望你能帮助我!:D
解决方案
您没有以正确的格式发送数据,来自文档https://developers.activecampaign.com/reference#contact
{
"contact": {
"email": "johndoe@example.com",
"firstName": "John",
"lastName": "Doe",
"phone": "7223224241",
"fieldValues":[
{
"field":"1",
"value":"The Value for First Field"
},
{
"field":"6",
"value":"2008-01-20"
}
]
}
}
所以创建一个带有关键联系人的数组。
$contact["contact"] = [
"email" => "johndoe@example.com",
"firstName" => "John",
"lastName" => "Doe",
"phone" => "7223224241",
"fieldValues" => [
[
"field"=>"1",
"value"=>"The Value for First Field"
],
[
"field"=>"6",
"value"=>"2008-01-20"
]
]
];
使用 try catch 块,这样你就可以捕捉到你的错误
try{
$client = new \GuzzleHttp\Client(["base_uri" => "https://myaccount.api-us1.com/api/3/"]);
$response = $client->request('POST', 'contacts', [
'headers' => [
'Api-Token' => 'xxx',
'api_action' => 'contact_add',
],
'json' => $contact
]);
if($response->getStatusCode() == "200" || $response->getStatusCode() == "201"){
$arrResponse = json_decode($response->getBody(),true);
}
} catch(\GuzzleHttp\Exception\ClientException $e){
$error['error'] = $e->getMessage();
if ($e->hasResponse()){
$error['response'] = $e->getResponse()->getBody()->getContents();
}
// logging the request
\Illuminate\Support\Facades\Log::error("Guzzle Exception :: ", $error);
// take other actions
} catch(Exception $e){
return response()->json(
['message' => $e->getMessage()],
method_exists($e, 'getStatusCode') ? $e->getStatusCode() : 500);
}
推荐阅读
- bash - 如何使用 BASH 将 JSON Web 密钥集 (JWKS) 公钥转换为 PEM 文件?
- c# - ASP WEB APP(.net 框架) - 未调用 repo 中的方法
- reactjs - 在 Material UI 日期选择器中突出显示周末(周六和周日)
- swift - 未找到 Microsoft 身份验证库 [MSALPublicClientApplicationConfig]
- mongodb - 在 mongoDB 中使用嵌套数组查询文档
- node.js - 如何为安装节点依赖项创建 package.json?
- azure-functions - 超出最小实例的 Azure Functions 预热触发器
- python - 使用 psycopg2 批量插入数据帧(错误:'dict' 对象不支持索引)
- c# - 使用 IP 获取远程计算机
- javascript - 我有一个 WIX 网站,我正在尝试使用来自 Authorize.net 的“接受托管”api,但我被困在尝试重定向到付款页面