0

我正在尝试将 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

4

2 回答 2

1

您没有以正确的格式发送数据,来自文档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);
}
于 2021-01-26T07:32:00.820 回答
0

您可以在API 文档中检查字段emailfirst_namelast_name是否位于contact节点下。

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

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

官方php客户端

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

于 2021-01-25T23:37:44.553 回答