Skip to content
Advertisement

2ba web API post request with php curl

Im using 2ba its API to receive product information which I later on want to store inside my database. I am trying to create a post request for receiving the data I need. This is the request I want to get to working. And this is my code:

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();

My API key does for sure work since I have done alot of different GET requests already, also im not getting an access denied error.

The error I get with this code is: The requested URL returned error: 500 Internal Server Error I also receive a “Bad request” 400 error when I remove the curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($parameters)); part

Is there anyone who knows what im doing wrong?

PS: It’s not really possible to try this code yourself unless you have a 2ba account with working key’s etc.

Advertisement

Answer

Okey I fixed it already…

I had to add some extra headers and change the $parameters values like this:

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);
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement