Understanding API and how to send proper CURL request - php

I am trying to figure out how to use Pin Payments API, function get charge.
https://pin.net.au/docs/api/charges#get-charge
As you can see they provide an example of the request using CURL
curl https://test-api.pin.net.au/1/charges/ch_bZ3RhJnIUZ8HhfvH8CCvfA -u your-secret-api-key:
I am just not sure how do I convert that to PHP, how do I pass my API key and how to pass charge ID so that the URL understood by the server.
Please help me comple the code below:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://test-api.pin.net.au/1/charges/ch_bZ3RhJnIUZ8HhfvH8CCvfA',
));
$resp = curl_exec($curl);
curl_close($curl);

Look up the u command line parameter: http://curl.haxx.se/docs/manpage.html
It represents the username and the password being used for the request.
Look up curl_setopt(). CURLOPT_USERPWD is the option for setting these credentials:
curl_setopt($curl, CURLOPT_USERPWD, 'apikey:');
// or
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://test-api.pin.net.au/1/charges/ch_bZ3RhJnIUZ8HhfvH8CCvfA',
CURLOPT_USERPWD => 'apikey:'
));
Please pay attention to the trailing colon! It separates the username from the password, which is empty in this case.

Related

PHP Curl Authentication Issue using API

I am trying to get data from a REST api that uses a token for authentication in the URL. I can pass the relevant parameters in a web browser and get the data with no problem, however as soon as I try to do it in a PHP script with curl, I get a 401 error saying http authentication is required.
Have tried many different options but cannot get it to work, any help would be appreciated. My code is below, have removed site id and changed api_key
API documentation says:
The API can be accessed via HTTPS protocol only. SolarEdge monitoring server supports both HTTPS/1.0 and HTTPS/1.1 protocols.
All APIs are secured via an access token:
Every access to the API requires a valid token as a URL parameter named api_key.
For example: api_key= L4QLVQ1LOKCQX2193VSEICXW61NP6B1O
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_SSL_VERIFYHOST => 0,
CURLINFO_HEADER_OUT => 1,
CURLOPT_POST => 1,
CURLOPT_HTTPAUTH, CURLAUTH_ANY,
CURLOPT_URL => 'https://monitoringapi.solaredge.com/site/?????/energyDetails',
CURLOPT_USERPWD, 'api_key:6X0kjehfdgksdljsgksdjhfksdhfglksd',
CURLOPT_HTTPHEADER=>array(
"timeUnit:DAY",
"meters=PRODUCTION,CONSUMPTION",
"startTime:2017-12-09 00:00:00",
"endTime:2017-12-09 23:59:59"),
));
$resp = curl_exec($curl);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close request to clear up some resources
curl_close($curl);
echo $resp;
echo "<br>$status_code";
//var_dump ($resp);
//print_r ($resp);
?>
Check the documentation again. Search for (Basic) Authentication.
You should look for something like this:
Authorization: <type> <credentials>
e.g. Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l
The HTTP 401 Unauthorized client error status response code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource.
This status is sent with a WWW-Authenticate header that contains information on how to authorize correctly.
This status is similar to 403, but in this case, authentication is possible.
Try your code again like this (add your API key) and report back the results:
$curl = curl_init();
curl_setopt_array($curl, array(
// CURLOPT_PORT=> 443,
// CURLOPT_RETURNTRANSFER => 1,
// CURLOPT_SSL_VERIFYPEER => 0,
// CURLOPT_SSL_VERIFYHOST => 0,
CURLINFO_HEADER_OUT => 1,
CURLOPT_POST => 1,
CURLOPT_HTTPAUTH, CURLAUTH_ANY,
CURLOPT_URL => 'https://monitoringapi.solaredge.com/site/?????/energyDetails',
CURLOPT_USERPWD, 'api_key:6X0kjehfdgksdljsgksdjhfksdhfglksd',
CURLOPT_HTTPHEADER=>array(
"timeUnit:DAY",
"meters=PRODUCTION,CONSUMPTION",
"startTime:2017-12-09 00:00:00",
"endTime:2017-12-09 23:59:59"),
));
$resp = curl_exec($curl);
$status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
echo $resp;
echo "<br>$status_code";

Google Analytics request validates correctly, but returns error when sent from CURL

I'm sending the following request to Google Analytics:
http://www.google-analytics.com/collect?v=1&tid=UA-72579327-1&cid=61baecac-8f8c-4dce-bf07-a7efa24a4e47&t=transaction&ti=qcY6pvpWGmP9fHyi&tr=10.00&cd1=Acme Racing&cd2=http://www.domain.co.uk/affiliate/idevaffiliate.php/id=314&tid1=12044762460674420322&url=http://www.nitrotek.co.uk&cd3=A1&cd4=Upgrades&cd5=Acme-Tech &cd6={device}&cd7=&cd8=0&cd9=&cd10=&cd11=&cd12=Nitrotek DSA&cd13=g&cd14=50&cd15=1&cd16=85&cd17=12044762460674420322&cd18=&cd19=http://www.domain.co.uk&cd20=61baecac-8f8c-4dce-bf07-a7efa24a4e47&gclid=
When you go to Google's hit builder and validate the request, it comes out valid.
However, when I send the same request through CURL POST, I just get "400. That’s an error. Your client has issued a malformed or illegal request. That’s all we know.".
POST is the correct method for this request (though I have tried GET just in case) and the Content-Length header is the length of the sent data (string). Here is the code:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $transaction_url, //the same URL string given above
CURLOPT_POST => 1,
CURLOPT_USERAGENT => 'cURL Request'
));
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Length: '.strlen($transaction_url) //length of URL string
));
$trans_resp = curl_exec($curl);
var_dump($trans_resp);
curl_close($curl);

CartoDB - SQL API - Post request with php

In my app I'd like to send some small amount of data to my cartodb-table with my php-script.
I would like to use the SQL-API. My app parse the data in the form like:
https://{account}.cartodb.com/api/v2/sql?q=INSERT INTO test_table (column_name, column_name_2, the_geom) VALUES ('this is a string', 11, ST_SetSRID(ST_Point(-110, 43),4326))&api_key={Your API key}
I tried several functions http_get, file_get_contents, http_request but nothing pass the data to my account. Put when I copy/paste the URL and open in the browser, everything is added.
What's the right function? There so many different ones... PHP-HTTP-Functions
EDIT
With the code from this solution I get this error, when I print out the response:
{"error":["syntax error at end of input"]}
within the browser I get this:
{"rows":[],"time":0.038,"fields":{},"total_rows":1}
my request code right now:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $fullurl);
// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Get the response and close the channel.
$response = curl_exec($ch);
curl_close($ch);
print($response);
Found the result: with CURLOPT_POST => 1 it works!
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => "https://".$cartodb_key.".cartodb.com/api/v2/sql",
CURLOPT_USERAGENT => 'Sample cURL Request',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array(
api_key => $api_key,
q => "INSERT INTO spot (".implode (", ", array_keys($data)).") VALUES (".implode (", ", $data).")"
)
));
$response = curl_exec($ch);
curl_close($ch);

Create HTTP GET Header Request

I am using php and I want to create a HTTP request to access some API data. I have a document that says, I need to place the following request
GET /abc/api/Payment HTTP/1.1
Content-Type: application/x-www-form-urlencoded
X-PSK: [App Key]
X-Stamp: [UTC Timestamp]
X-Signature: [HMACSHA256 base 64 string]
Body:
var1, var1
I have app key, I can get UTC Timestamp and I can create signature. I am not sure how to start creating this request? I am using codeingiter. If someone can help with example to set the header and body?
I also tried this url https://www.hurl.it/ to place requests but can't make it work. Any suggestions?
You want to use cURL's CURLOPT_HTTPHEADER option.
http://php.net/manual/en/function.curl-setopt.php
This should get you started
function request($url) {
$ch = curl_init();
$curlOpts = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array(
"Content-Type: application/x-www-form-urlencoded",
"X-PSK: [App Key]",
"X-Stamp: [UTC Timestamp]",
"X-Signature: [HMACSHA256 base 64 string]"
),
CURLOPT_FOLLOWLOCATION => true
);
curl_setopt_array($ch, $curlOpts);
$answer = curl_exec($ch);
// If there was an error, show it
if (curl_error($ch)) die(curl_error($ch));
curl_close($ch);
return $answer;
}

Make session work with Curl (ZF2)

I'm working with REST in my Zend Framework 2 application. In order to test my rest calls, I use Curl to send REST requests as follows:
$client = new Http\Client();
$client->setAdapter(new Http\Client\Adapter\Curl());
$request = new Http\Request();
$request->setUri($url);
$request->setMethod($method);
$response = $client->dispatch($request);
$jsonString = $response->getContent();
Everthing works fine except that the Curl requests seem to ignore the session. I need access to the logged-in user in my rest request handling to e.g. make Acl work. When I send REST request using AngularJS, the session actually works. Here's how I set up the session:
$storage = new SessionArrayStorage();
$manager = new SessionManager($config, $storage);
$session = new Session('surveylab', $manager);
How can I pass the session information to Curl, so I get access to the session in the Curl requests?
Checkout the cURL options for:
CURLOPT_COOKIEFILE
CURLOPT_COOKIEJAR
look for examples for the cURL usage of them:
curl_setopt($ch, CURLOPT_COOKIEFILE, "/tmp/cookie.txt");
curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/cookie.txt");
Send your login credentials as post to your login url, extract the cookies from the result and send them with the next request. I don't know if your application updates the cookies over time but you should update them if necessary.
Some example code:
curl_setopt_array($ch, array(
CURLOPT_URL => "http://your/url",
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_HTTPHEADER => array('Cookie: ' . $cookies . '"'),
CURLOPT_HEADER => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_POST => count($postData),
CURLOPT_POSTFIELDS => $post_string
));

Categories