对PHP代码的cURL命令返回错误

时间:2018-03-09 03:43:57

标签: php json rest api curl

我正在尝试发布数据以使用Rotessa API创建客户。我正在使用我在Rotessa API参考中找到的curl命令。但是我在返回响应中遇到错误而不是JSON字符串。如果我得到这方面的帮助,将会非常有帮助。感谢

curl命令:

 curl -X POST -H 'Content-Type: application/json' -H "Authorization: Token 
 token=\"<api_key>\"" -d '{"custom_identifier": "test api", "email": 
 "test@rotessa.com", "name": "Mike Smith", "bank_name": "Scotiabank", 
 "transit_number": "11111", "institution_number": "111", "account_number": 
 "11111111", "address": { "address_1": "123 Main Street", "address_2": "Unit 
 4", "city": "Toronto", "province_code": "ON", "postal_code": "M1B 0B7" }}' 
 <rotessa_endpoint>/customers.json  

并转换了php代码:

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://api.rotessa.com/v1/customers.json");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"custom_identifier\": \"test api\", 
                                   \"email\": \"test@rotessa.com\", 
                                   \"name\": \"Mike Smith\", 
                                   \"bank_name\": \"Scotiabank\", 
                                   \"transit_number\": \"11111\", 
                                   \"institution_number\": \"111\", 
                                   \"account_number\": \"11111111\", 
                                   \"address\": { \"address_1\": \"123 Main
                                                                   Street\", 
                                                  \"address_2\": \"Unit 4\", 
                                                  \"city\": \"Toronto\", 
                                                  \"province_code\": \"ON\", 
                                                  \"postal_code\": \"M1B 
                                                               0B7\" }}");

    curl_setopt($ch, CURLOPT_POST, 1);

    $headers = array();
    $headers[] = "Content-Type: application/json";
    $headers[] = "Authorization: Token token=\"<api_key>\"";
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $result = curl_exec($ch);
    if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
    }


    curl_close ($ch);

    echo $result;

它出现以下错误:

    {"errors":[{"error_code":"unauthorized","error_message":"Not Found."}]}

为了解决进一步的混乱,我在测试中使用了真正的api_key。只是没有在这里发布。

2 个答案:

答案 0 :(得分:1)

上方有端点网址/customers.json, 下面你有/customers

答案 1 :(得分:0)

通常API需要API密钥,应该通过curl发送。

curl "<rotessa_endpoint>/customers.json" -H "Authorization: Token token=\"<api_key>\""

而不是<api_key>应输入您的API密钥。

rotessa API KEY