尝试通过 ActiveCampain API (Laravel) 添加联系人

问题描述

我正在尝试将 ActiveCampaing 的 RESTFUL API 集成到我的 Laravel 环境中,但我没有那么幸运,我使用 GuzzleHttp 发出请求,这是 error image 和我的代码

 $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);
}
,

您可以在 API docs 处检查字段 emailfirst_namelast_name 是否位于 contact 节点下。

所以创建一个 contact 数组,把这些字段放在里面,你应该没问题。

名字和姓氏的字段写成行 firstNamelastName - camelCase,而不是像你那样的 snake_case。

官方php客户端

您可能应该使用官方的 ActiveCampaign php api client - 这会让您的生活更轻松。