PHP Curl request with http authentication and POST - php

I'm having trouble trying to get my code running. I'm trying to use cUrl with a post and http authentication but I'm unable to get it to work.
I'm using the following code:
public function index(){
$call = $this->call("URL_TO_CALL", $this->getCredentials(), $this->getJson());
}
private function getCredentials(){
return "API_KEY_HERE";
}
private function getJson(){
return $json;
}
private function call($page, $credentials, $post){
$url = "URL_TO_CALL";
$page = "/shipments";
$headers = array(
"Content-type: application/vnd.shipment+json;charset=utf-8",
"Authorization: Basic :" . base64_encode($credentials)
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Apply the POST to our curl call
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$data = curl_exec($ch);
if (curl_errno($ch)) {
print "Error: " . curl_error($ch);
} else {
// Show me the result
var_dump($data);
curl_close($ch);
}
}
The response I'm getting is:
{"errors":[{"code":3001}],"message":"Permission Denied. (insertShipment)"}
I was expecting a list of shipments. Am I doing something obviously wrong here?

Looking at your code, you stipulate the URL in a variable then stipulate the exact page, however when you set the URL for the curl, you are merely using the URL variable as opposed to URL + PAGE variables.

Related

Issuing with making a post request with php curl

I'm trying to make a post request with php using curl however the json is not getting delivered to the REST API. Here is my code. In the webservice all I get is null value. I'm not sure where I'm going wrong.
$email_json_data = json_encode($email_data);
$header[] = "Content-type: application/json";
$ch = curl_init($api_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $email_json_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
return $response;
Webservice code:
$email_json_data = $this->post('email_json_data');
$email_data = json_decode($email_json_data);
Check PHP: curl_errno
There's probably a problem connecting to the server, and it's probably in one of your $header. To find out more, you need to show (in production, LOG it) the curl error.
In the future, please try to include a complete code sample, rather than just snippets
Code added from PHP: curl_strerror
class CurlAdapter
{
private $api_url = 'www.somewhere.com/api/server.php';
private $error = "";
private function jsonPost($data)
{
// init curl
$ch = curl_init($this->api_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// curl header
$header[] = "Content-type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
// build post data
$post_data = json_encode($data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
// execute
if (empty($response = curl_exec($ch)) {
// Check for errors and display the error message
if($errno = curl_errno($ch)) {
$error_message = curl_strerror($errno);
$this->error = "cURL error ({$errno}):\n {$error_message}";
// #todo log curl error
}
}
// Close the handle
curl_close($ch);
return $response;
}
public function post( mixed $data )
{
if (empty($this->jsonPost($data))) {
return $this->error;
}
return $response;
}
}
$ca = new CurlAdapter();
echo $ca->post(['data' => 'testdata']);
Figured out a way to make this work.
Replaced $email_json_data = $this->post('email_json_data');
with $email_json_data = file_get_contents("php://input");

Hubstaff - retrieve data with php cURL

I'm trying to connect with hubstaff api, has anyone ever tried it? I'm a newbie in php-cURL, how do you convert this to PHP Curl?
curl -H "App-Token: BMyQnju-4tknuBQMsN0ujr6NWF5ohQaP9de8AWMJXik" -H "Auth-Token: X-vfv2c7jf_0NKoHLbX1t4yftK-TI-jZ4d7roNegw24" "http://api.hubstaff.com/v1/users"
It also would not show any result of I do this:
// Standard data
$data['app_token'] = $this->app_token;
// Debugging output
$this->debug = array();
$this->debug['HTTP Method'] = $http_method;
// Create a cURL handle
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'App-Token: ' . $this->app_token,
'Content-Type: application/xml'
));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
// Send data
if (!empty($data)) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
// Debugging output
$this->debug['Posted Data'] = $data;
}
// Execute cURL request
$curl_response = curl_exec($ch);
// Save CURL debugging info
$this->debug['Last Response'] = $curl_response;
$this->debug['Curl Info'] = curl_getinfo($ch);
// Close cURL handle
curl_close($ch);
// Parse response
$response =$curl_response;// $this->parseAsciiResponse($curl_response);
// Return parsed response
return $response;
Im just trying to get my Auth-Token
Any help would be greatly appreciated.
#Michal I have solved my own problem and created this simple class to help anyone else in connecting with hubstaff fast. feel free for any suggestions and optimizations
class HubstaffApi {
private $app_token = '';
private $auth_token = '';
private $debug = [];
public function __construct($app_token, $auth_token) {
$this->app_token = $app_token;
$this->auth_token = $auth_token;
}
private function sendRequest($api_method, $http_method = 'GET', $data = null) {
// Standard data
$data['app_token'] = $this->app_token;
$request_url = "https://api.hubstaff.com/v1/";
// Debugging output
$this->debug = array();
$this->debug['Request URL'] = $request_url . $api_method;
// Create a cURL handle
$ch = curl_init();
// Set the request
curl_setopt($ch, CURLOPT_URL, $request_url . $api_method);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'App-Token: ' . $this->app_token,
'Auth-Token: ' . $this->auth_token
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $http_method);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
// Send data
if (!empty($data)) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
// Debugging output
$this->debug['Posted Data'] = $data;
}
// Execute cURL request
$curl_response = curl_exec($ch);
// Save CURL debugging info
$this->debug['Last Response'] = $curl_response;
$this->debug['Curl Info'] = curl_getinfo($ch);
// Close cURL handle
curl_close($ch);
// Parse response
$response = $curl_response;
// Return parsed response
return $response;
}
public function users(array $parameters = array()) {
return $this->sendRequest('users', 'GET', $parameters);
}
public function activities(array $parameters = array()) {
return $this->sendRequest('activities', 'GET', $parameters);
}
public function screenshots(array $parameters = array()) {
return $this->sendRequest('screenshots', 'GET', $parameters);
}
}
You can simply use this by:
$Hubstaff = new HubstaffApi(
YOUR_APP_TOKEN,
YOUR_AUTH_TOKEN); //simply get auth token in developer.hubstaff 's generator, it doesn't expire anyway.
$response = $Hubstaff->activities([
"start_time" => "2015-09-10T00:00:00+08:00:00",
"stop_time" => "2015-09-10T24:00:00+08:00:00",
"users" => YOUR_HUBSTAFF_ID
]);
echo $response;

json post with cURL from a while loop

I am trying to post json data with cURL. The idea is: In case the url is not accessible ( for example failure of internet connection) keep trying to post the json while you succeed. It works but when I put it in while loop it executes only once. What am I doing wrong:
$jsonDataEncoded = json_encode($event);
echo $jsonDataEncoded;
echo "\n";
$send_failure = true;
while ($send_failure) {
$url = "a";// intentionally inaccessible url
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($jsonDataEncoded)));
$result = curl_exec($ch);
if(curl_errno($ch)){
throw new Exception(curl_error($ch));
} else {$send_failure = false;}
return $result;
}
You must print and check the value in $result using var_dump($result); .
If there is any connection error it returns the error code which you can check manual in IF condition. Hope this might help you.

How to assign result fro curl to a variable?

I need to do a simple POST request and parse the result. For this i use curl in php. The problem is that i cant assign the result to a variable - it just prints .
My method:
private function sendRequest($data)
{
$ch = curl_init(self::IP . ':' . self::PORT);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch); // HERE IT PRINTS
curl_close($ch);
$parsed_result = #simplexml_load_string(trim($result)); // OR HERE IT
die(var_dump(isset($parsed_result->request_error)));
if (isset($parsed_result->request_error))
$this->AJAXResult(TRUE, (string) $parsed_result->request_error->text);
}
You must add:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1)
if you want curl_exec to return the result of the post request.

Make GET request using cURL

I'm trying to make a simple GET request using cURL directly but I'm not able to get the response.
public function getSiteLicenses($page = 1) {
$url = 'https://testdomain.com';
$header = array('Key:somekey');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
The alternate way for me is to use some HTTP library, which works fine but I want to avoid using the library and use cURL directly.
public function getSiteLicenses($page = 1) {
$url = 'https://testdomain.com';
$siteLicenses = \Httpful\Request::get($url)
->addHeader("KEY", $this->apikey)
->send();
$siteLicensesArray = json_decode($siteLicenses, true);
return $siteLicensesArray;
}
What am I missing for requesting GET method using cURL directly? Thanks

Categories