【问题标题】:2ba web API post request with php curl带有 php curl 的 2ba Web API 发布请求
【发布时间】:2026-02-01 00:45:01
【问题描述】:

我正在使用2ba 它的 API 来接收我稍后想要存储在我的数据库中的产品信息。我正在尝试创建一个发布请求以接收我需要的数据。 This 是我想要开始工作的请求。这是我的代码:

postApiData.php

<?php
/**
 * Posts API data based on given parameters at index.php.
 */

// Base url for all api calls.
$baseURL = 'https://api.2ba.nl';

// Version number and protocol.
$versionAndProtocol = '/1/json/';

// All parts together.
$url = $baseURL . $versionAndProtocol . $endPoint;

// Init session for CURL.
$ch = curl_init();

// Init headers. Security for acces data.
$headers = array();
$headers[] = "Authorization: Bearer " . $token->access_token;

// Options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($parameters));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_FAILONERROR, true);

// Execute request.
$data = curl_exec($ch);

// If there is an error. Show whats wrong.
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
    echo "<br>";
    echo "Error location: postApiData";
    exit();
}

// Ends the CURL session, frees all resources that belongs to the curl (ch).
curl_close($ch);

// String to array.
$data = json_decode($data);

?>

index.php

// Specified url endpoint. This comes after the baseUrl.
$endPoint = 'Product/forGLNAndProductcodes';

// Parameters that are required or/and optional for the endPoint its request.
$parameters = [
    'gln' => '2220000075756',
    'productcodes' => ['84622270']
];

// Get Supplier info
include("postApiData.php");

print_r($data);
exit();

我的 API 密钥确实有效,因为我已经完成了很多不同的 GET 请求,而且我没有收到拒绝访问错误。

我使用此代码得到的错误是:请求的 URL 返回错误:500 内部服务器错误 当我删除 curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($parameters)); 部分时,我还会收到“错误请求”400 错误

有谁知道我做错了什么?

PS:除非你有一个 2ba 帐户和工作密钥等,否则真的不可能自己尝试这个代码。

【问题讨论】:

    标签: php curl post


    【解决方案1】:

    好吧,我已经修好了……

    我必须添加一些额外的标题并像这样更改 $parameters 值:

    postApiData.php

    // Added this above the authorization.
    $headers[] = "Connection: close";
    $headers[] = "Accept-Encoding: gzip,deflate";
    $headers[] = "Content-Type: application/json";
    
    // Removed the http_build_query part.
    curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
    

    index.php

    // Encoded in a json way as asked by 2ba request.
    $parameters = json_encode($parameters);
    

    【讨论】: