2ba web API post request with php curl - php

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.

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

Related

Pulling in optional parameters for Emma API using php

I am trying to get additional parameters from Emma's API using php. If anyone can point me in the right direction, I would greatly appreciate it. I know that my problem is terminology and thnk I am struggling with the basics and just need to "get over the hump."
I have been able to successfully test getting the basic fields that Emma provides by using get curl https://api.e2ma.net/account_id/mailings and --header 'Authorization: Basic {{public_api_key}}:{{private_api_key}}'
My problem is that according to their documentation (url below), I should be able to include extra parameters (I need to get the with_html_body parameter).
http://api.myemma.com/api/external/mailings.html
The code below gives me the following error:
Error getting member: {"error": "Unable to parse JSON request"}
I know the $data array is the problem.
Any idea if this is my only problem?
I figure I need to pull in the with_html_body field as an array and then CURLOPT_POSTFIELDS the variable ($data).
Amy I way off base?
Thanks in advance for any help pointing me in the right direction.
<?php
// Authentication Variables
$account_id = "1111111";
$public_api_key = "99999999";
$private_api_key = "99898989";
// Set URL
$url = "https://api.e2ma.net/" . $account_id . "/mailings";
// Open connection
$ch = curl_init();
$data = array('with_html_body' => 'true');
// Make the curl call
curl_setopt($ch, CURLOPT_USERPWD, $public_api_key . ":" . $private_api_key);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$head = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//curl_close($ch);
// check for errors
if($http_code > 200) {
print "Error getting member:\r\n";
print_r($head);
} else {
/*
print "Member information:\r\n";
print_r($head);
*/
$decoded = json_decode($head, true);
echo "<pre>";
print_r($head);
echo "</pre>";
/*
*/
}
curl_close($ch);
?>
Typical me, I over-complicated the issue!
All I needed to do was adjust the $url to below.
$url = "https://api.e2ma.net/" . $account_id . "/mailings?with_html_body=true";
Yes, I feel like an idiot!
But making progress.
Now to put this code in a better form to use on a project.

How to connect with 2ba it's API using PHP

Im trying to connect to the API services of 2ba. Somehow I just can't connect. I get the error: error: "invalid_client"
I dont know what to try, it feels like I need to hash my cliend_secret or complete url but I dont see that in the documentation.
This is my code (PHP):
<?php
// ---- GET TOKEN ----
// Base url for all api calls.
$baseURL = 'https://authorize.2ba.nl';
// Specified url endpoint. This comes after the baseUrl.
$endPoint = '/OAuth/Token';
// Parameters that are required or/and optianal for the endPoint its request.
$parameters = 'grant_type=password&username=abc#abc.com&password=123abc&client_id=myClientID&client_secret=myClientSecret';
// All parts together.
$url = $baseURL . $endPoint . '?' . $parameters;
//Init session for CURL.
$ch = curl_init();
// Options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
// Init headers for access to the binance API signed data.
$headers = array();
$headers[] = 'Content-type: application/x-www-form-urlencoded';
$headers[] = 'Content-Length: 0';
// Setting headers
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Execute request.
$data = curl_exec($ch);
// If there is an error. Show whats wrong.
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
// Ends the CURL session, frees all resources and deletes the curl (ch).
curl_close($ch);
$result = json_encode($data);
echo($data);
exit();
?>
The authentication is oauth2 and I want to use the "Password Grant" flow since I can login automaticly this way. Also I see in the example code in C# that they encode the url, something im not doing yet but did try. It did not work.
// Using $encodedUrl like this: curl_setopt($ch, CURLOPT_URL, $encodedUrl); but does not work.
$encodedUrl = urlencode($url);
Alright so I fixed it. I now got my access token and am able to recieve data from the API. This is what I did:
// ---- GET TOKEN - FLOW: USER PSW ----
// No changes
$baseURL = 'https://authorize.2ba.nl';
// No changes
$endPoint = '/OAuth/Token';
// $parameters is now an array.
$parameters = array(
'grant_type' => 'password',
'username' => 'myUsername',
'password' => 'myPassword',
'client_id' => 'myClientID',
'client_secret' => 'myClientSecret'
);
// Removed the $parameter part
$url = $baseURL . $endPoint;
//Init session for CURL.
$ch = curl_init();
// Init headers for access to the binance API signed data.
$headers = array();
$headers['Content-Type'] = "application/x-www-form-urlencoded";
// NOTE: http_build_query fixed it.
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($parameters)); // Automaticly encodes parameters like client_secret and id.
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Execute request.
$data = curl_exec($ch);
// If there is an error. Show whats wrong.
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
// Ends the CURL session, frees all resources and deletes the curl (ch).
curl_close($ch);
$result = json_encode($data);
echo($data);
exit();

cURL_init() stops the program from running

I have added the .php files on my server to send the notifications using FCM, but the code stops running when I create the actual message. I have a constructor for push and when I call it in sendSinglePush, it does not do anything.
The rest is working properly. I get the parameters ok, and the devicetoken. I just need to create that push and it should work. I've used the same sendSinglePush.php for testing on localhost, and it works. When I add it on server it just stops.
EDIT: As per #ADyson, who helped me understand abit about logging my errors, I started to log every variable from the start to the point where it crashes. The $push it's alright, the problem it's on Firebase.php:
<?php
class Firebase {
public function send($registration_ids, $message) {
$fields = array(
'registration_ids' => array($registration_ids),
'data' => $message,
);
//print_r($fields);
return $this->sendPushNotification($fields);
}
/*
* This function will make the actuall curl request to firebase server
* and then the message is sent
*/
private function sendPushNotification($fields) {
//importing the constant files
require_once 'Config.php';
//firebase server url to send the curl request
$url = 'https://fcm.googleapis.com/fcm/send';
//building headers for the request
$headers = array(
'Authorization: key=' . FIREBASE_API_KEY,
'Content-Type: application/json'
);
//Initializing curl to open a connection
$ch = curl_init();
print_r(curl_error($ch));
//Setting the curl url
curl_setopt($ch, CURLOPT_URL, $url);
//setting the method as post
curl_setopt($ch, CURLOPT_POST, true);
//adding headers
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//disabling ssl support
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//adding the fields in json format
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
//finally executing the curl request
$result = curl_exec($ch);
print_r($result);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
print_r(curl_error($ch));
}
//Now close the connection
curl_close($ch);
//and return the result
return $result;
}
}
And the methods are called from sendSinglePush.php, where all the variables are sent correctly:
$mPushNotification = $push->getPush();
//print_r($mPushNotification);
//getting the token from database object
$devicetoken = $db->getTokenByEmail($_POST['email']);
//print_r($devicetoken);
//creating firebase class object
$firebase = new Firebase();
//sending push notification and displaying result
$firebase->send($devicetoken, $mPushNotification);
I have added different print_r() to check the output using POSTMAN and, from that code, the $headers are fine, after the $ch = curl_init(); nothing else shows up. I tried to add print_r(curl_error($ch)); but it does not show enything. Also, I tried with print_r(1); under the $ch = curl_init();to see if the code keeps running, but on postman there was no answer, only a blank screen and 500 Internal Server Error.

Slack Slash Command - Getting user icon URL with username (PHP)

I am new at programming Slash commands in Slack. For one of my commands, I have a username and need to retrieve the user icon URL. I am using PHP to code them.
I was planning on using users.profile.get, since the tutorial here shows that one of the fields returned is the user icon URL.
However, I am trying to find examples on how to make a call to this method and have not found any. Could anybody give me a quick example of the call, including how to send the parameters?
This is how far I got:
$slack_profile_url = "https://slack.com/api/users.profile.get";
$fields = urlencode($data);
$slack_call = curl_init($slack_profile_url);
curl_setopt($slack_call, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($slack_call, CURLOPT_POSTFIELDS, $fields);
curl_setopt($slack_call, CURLOPT_CRLF, true);
curl_setopt($slack_call, CURLOPT_RETURNTRANSFER, true);
curl_setopt($slack_call, CURLOPT_HTTPHEADER, array(
"Content-Type: application/x-www-form-urlencoded",
"Content-Length: " . strlen($fields))
);
$profile = curl_exec($slack_call);
curl_close($slack_call);
I basically have $token and $user_name and need to get the profile picture URL. How do I format $token and $username as $data? Is the call correct?
If anybody recommends doing this a different way, I would appreciate any advice as well.
Thank you so much!
To get data into the right format to post to Slack is pretty straight forward. There's two options (POST body or application/x-www-form-urlencoded).
The query string for application/x-www-form-urlencoded is formatted like a get URL string.
https://slack.com/api/users.profile.get?token={token}&user={user}
// Optionally you can add pretty=1 to make it more readable
https://slack.com/api/users.profile.get?token={token}&user={user}&pretty=1
Just request that URL and you will retrieve the data.
The POST body format will use a similar code to what you have above.
$loc = "https://slack.com/api/users.profile.get";
$POST['token'] = "{token}";
$POST['user'] = "{user}";
$ch = curl_init($loc);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $POST);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
if ($error = curl_errno($ch)) { echo $error; }
//close connection
curl_close($ch);
echo $result;

Apple news API. PHP code for Connect and send json data

I am able to connect with the help of apple news api but I can't able to send data in json format.
My code is below.
but when I try to attach json file. I am getting signature failure message.
<?php
$channel_id = 'xxxxxxxxxxxxxxxxxx';
$api_key_id = 'xxxxxxxxxxxxxxx';
$api_key_secret = 'xxxxxxxxxxxxxxxx';
// use the correct values above
$data = file_get_contents('article.json');
$Content_type="application/json";
$url = 'https://news-api.apple.com/channels/'.$channel_id;
$date = gmdate('Y-m-d\TH:i:s\Z');
$canonical_request = 'GET'.$url.$date.$Content_type;
$key = base64_decode($api_key_secret);
$hashed = hash_hmac('sha256', $canonical_request,$key,true);
$signature = base64_encode($hashed);
echo $signature;
//curl options
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$headers = array();
$headers[] = "Authorization: HHMAC; key={$api_key_id}; signature={$signature}; date={$date}";
$headers[] = "Content-Type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
//curl_setopt($ch, CURLOPT_POST, true);
//curl_setopt( $ch, CURLOPT_POSTFIELDS, $data);
//get result
$server_output = curl_exec ($ch);
curl_close ($ch);
print_r(json_decode($server_output));
?>
Since you are sending a GET request, you are incorrectly including the content type when building the canonical request.
This should work for you, then:
$canonical_request = 'GET'.$url.$date;
For reference, see Apple News API Reference: Setting Up MAC/HMAC Authentication:
Create a canonical version of the request as a byte-wise concatenation of the following:
The HTTP method (for example, GET or POST, in all caps)
The full URL of the request
The current date in ISO 8601 format
If the request is a POST request and it includes an entity, include the following:
The value of the Content-Type header
The full content of the entity

Categories