CURL with JSON from laravel to API - php

I am trying to implement an API call from my system, and the API has an example that looks like this:
curl -u "<brugernavn>:<password>" -XPOST http://distribution.virk.dk/cvr-permanent/_search -d'
{ "from" : 0, "size" : 1,
"query": {
"term": {
"cvrNummer": 10961211
}
}
}
'
Now i want to turn this in to php code. Im thinking it will look something like this:
public function requestApiV2($vat){
// Start cURL
$ch = curl_init();
// Determine protocol
$protocol = 'http';
$parameters = json(
{ "from" : 0, "size" : 1,
"query": {
"term": {
"cvrNummer": $vat
}
}
}
);
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $protocol . '://distribution.virk.dk/cvr-permanent/_search' . http_build_query($parameters));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Parse result
$result = curl_exec($ch);
// Close connection when done
curl_close($ch);
// Parse from json to array
$data = json_decode($result, true);
}
I can't test this yet, as I still need to acquire username and password from the API, but I am also uncertain about how I send the username and password along with the request in the correct way. Is there a CURLOPT for this as well?
I am also uncertain about if my parameters are implemented the right way with the json like that.
thank you :)

use Guzzle library. Laravel has included the Guzzle library so you dont need to install it
With Guzzle, the below will do
use GuzzleHttp\Client;
public function requestApiV2($vat){
$client = new Client([
// Base URI is used with relative requests
'base_uri' => 'http://distribution.virk.dk/,
]);
$response = $client->post('cvr-permanent/_search', [
'auth' => ['username', 'password'],
'json' => [
'from' => 0,
'size' => 1,
'query' => [
'term' => [
'cvrNumber' => $vat
]
]
]
]);
$body = $response->getBody();
dd($body);
}

Related

Coinmarketcap API Call with PHP

I tried my first API call but something is still wrong. I added my API-Key, choose the symbol and tried to echo the price. But it is still not valid. But my echo is still 0. Maybe someone show me what i did wrong. Thank you!
<?php
$coinfeed_coingecko_json = file_get_contents('https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?symbol=ETH');
$parameters = [
'start' => '1',
'limit' => '2000',
'convert' => 'USD'
];
$headers = [
'Accepts: application/json',
'X-CMC_PRO_API_KEY: XXX'
];
$qs = http_build_query($parameters); // query string encode the parameters
$request = "{$url}?{$qs}"; // create the request URL
$curl = curl_init(); // Get cURL resource
// Set cURL options
curl_setopt_array($curl, array(
CURLOPT_URL => $request, // set the request URL
CURLOPT_HTTPHEADER => $headers, // set the headers
CURLOPT_RETURNTRANSFER => 1 // ask for raw response instead of bool
));
$response = curl_exec($curl); // Send the request, save the response
print_r(json_decode($response)); // print json decoded response
curl_close($curl); // Close request
$coinfeed_json = json_decode($coinfeed_coingecko_json, false);
$coinfeedprice_current_price = $coinfeed_json->data->{'1'}->quote->USD->price;
?>
<?php echo $coinfeedde = number_format($coinfeedprice_current_price, 2, '.', ''); ?>
API Doc: https://coinmarketcap.com/api/v1/#operation/getV1CryptocurrencyListingsLatest
There is a lot going on in your code.
First of all $url was not defined
Second of all you made two requests, one of which I have removed
Third; you can access the json object by $json->data[0]->quote->USD->price
Fourth; I removed the invalid request params
I have changed a few things to make it work:
$url = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest";
$headers = [
'Accepts: application/json',
'X-CMC_PRO_API_KEY: ___YOUR_API_KEY_HERE___'
];
$request = "{$url}"; // create the request URL
$curl = curl_init(); // Get cURL resource
// Set cURL options
curl_setopt_array($curl, array(
CURLOPT_URL => $request, // set the request URL
CURLOPT_HTTPHEADER => $headers, // set the headers
CURLOPT_RETURNTRANSFER => 1 // ask for raw response instead of bool
));
$response = curl_exec($curl); // Send the request, save the response
$json = json_decode($response);
curl_close($curl); // Close request
var_dump($json->data[0]->quote->USD->price);
var_dump($json->data[1]->quote->USD->price);

Pass whole incoming data to curl - Laravel

I wanted to pass the whole incoming data (that is, $request) to the curl not wanted to post to a particular field in the endpoint as subjectId=>1 as am running this curl request for different endPoint everytime. The below curl request will work if CURLOPT_URL => $url . $subjectId, was given. As my input changes for every end point, i've to pass everything that comes in the input to the curl , i can't pass it as an arary $subjectId. Is there any way to do this?
Currently, dd($Response); returns null
Am giving a postman input like this:
{
"subjectId":"1"
}
Curl
public function getContentqApiPost(Request $request)
{
$token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.ey";
$headers = [
"Accept: application/json",
"Authorization: Bearer " . $token
];
$url="http://127.0.0.1:9000/api/courses/course-per-subject";
$subjectId = "?subjectId=$request->subjectId";
$ch = curl_init();
$curlConfig = array(
// CURLOPT_URL => $url . $subjectId,
CURLOPT_URL => $url . $request,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers,
);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt_array($ch, $curlConfig);
$result = trim(curl_exec($ch));
$Response = json_decode($result, true);
if (curl_errno($ch)) {
$error_msg = curl_error($ch);
echo $error_msg;
}
curl_close($ch);
return $Response;
}
If you would like to pass all params of $request to curl:
$queryParams = '';
$delimeter = '?';
foreach($request->all() as $k => $v){
$queryParams .= "$delimeter$k=$v";
$delimeter = '&';
}
Also You can only pass the params you want:
foreach($request->only(['subjectId']) as $k => $v){
// code here
}
Finally you have:
CURLOPT_URL => $url . $queryParams,
Answer
Assuming you want to pass the entire GET query string as-is:
$query_string = str_replace($request->url(), "", $request->fullUrl());
$url = "http://localhost:9000/api/courses/course-per-subject" . $query_string;
This works because $request->url() returns the URL without the query string parameters, while $request->fullUrl() returns the URL with all the query string parameters, so we can use str_replace with an empty replacement to remove the non-query part. Note that $query_string will already start with a ? so there is no need to add that yourself.
Other suggestions
Unless your Laravel API is a 1:1 copy of the backend API, I strongly suggest writing a class that interfaces with the backend API, then provide it to your Laravel controllers using dependency injection. E.g.
class CourseCatalogApi {
public function getSubjectsInCourse(String $course){
... // your curl code here
}
}
Finally, since you are already using Laravel, there is no need to write such low level code using curl to make HTTP requests. Consider using guzzlehttp, which is already a dependency of Laravel.

Using curl to post request handle JSON data

I recently work with kraken.io API and I'm trying to integrate this API wuth my PHP CodeIgniter framework. So I followed the documentation but I got stuck when I used curl
This is my source code below ..
require_once(APPPATH.'libraries/kraken-php-master/Kraken.php');
$kraken = new Kraken("SOME_KEY", "SOME_SECRET");
$params = array(
"file" => base_url()."include/".$dataIn['logo'],
"wait" => true
);
$dataj='{"auth":{"api_key": "SOME_KEY", "api_secret": "SOME_SECRET"},"file":'.base_url()."include/".$dataIn['logo'].',wait":true}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.kraken.io/v1/upload");
curl_setopt($ch, CURLOPT_HTTPHEADER,array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataj);
$response = curl_exec($ch);
curl_close($ch);
$data = $kraken->upload($params);
print_r($response);exit();
And I got this result
"{"success":false,"message":"Incoming request body does not contain a valid JSON object"}1"
So can anyone please help me,
And thanks in advance,
DONT POST YOUR API_KEY AND API_SECRET
The error message is quite clear, your json object is not valid. For instance this would be a valid JSON object for your request:
{
"auth": {
"api_key": "SOME",
"api_secret": "SECRET"
},
"file": "somefile.txt",
"wait": true
}
In your php code you are setting up a $params array but then you don't use it. Try this:
$dataj='{"auth":{"api_key": "SOME_KEY", "api_secret": "SOME_SECRET"},"file":"' . $params["file"]. '", "wait":true}';
You can validate your JSON HERE
You should use json_encode function to generate your JSON data
$dataj = json_encode([
"auth" => [
"api_key" => "API_KEY",
"api_secret" => "API_SECRET"
],
"file" => base_url() . "include/" . $dataIn['logo'],
"wait" => true
]);
EDIT:
Here is an example from https://kraken.io/docs/upload-url so you don't need to use curl
require_once("Kraken.php");
$kraken = new Kraken("your-api-key", "your-api-secret");
$params = array(
"file" => "/path/to/image/file.jpg",
"wait" => true
);
$data = $kraken->upload($params);
if ($data["success"]) {
echo "Success. Optimized image URL: " . $data["kraked_url"];
} else {
echo "Fail. Error message: " . $data["message"];
}

Having Trouble in Generating Amazon AWS Signature With PHP

I was trying to make a HTTP POST Request to amazon's AGCOD Service API , I followed all the steps to make a signature and all the hashed keys matched the instructions here, but I still got a "The security token included in the request is invalid." ERROR.
<?php
define('PARTNER_ID','Test');
define('ACCESS_KEY','fake-aws-key');
define('SECRET_KEY','fake-secret-key');
define('TIME_STAMP_ISO_8601',date('Ymd\THisO'));
//define('TIME_STAMP_ISO_8601','20140205T171524Z');
//define('TIME_STAMP','20140205');
define('TIME_STAMP',date('Ymd'));
define('REGION_CODE','us-east-1');
define('SERVICE_NAME','AGCODService');
$secretKey = 'AWS4'.SECRET_KEY;
$hashedDateKey = hash_hmac('sha256', TIME_STAMP, $secretKey, true);//41b8dd5e0d1716ba90401d46b58b12d500accdd2ea9c2b22a2d275946c9d978e
$hashedRegionKey = hash_hmac('sha256', REGION_CODE, $hashedDateKey, true);//7b47360ce7afbe1b839e0b0e55834df99979a5414bc7f846b17c9374d230d45d
$hashedServiceKey = hash_hmac('sha256', SERVICE_NAME , $hashedRegionKey, true);//68136b0a64b2d01c8934370288b46500243645e468f521503e0d1fa73526d409
$signingKey = hash_hmac('sha256', 'aws4_request', $hashedServiceKey,true);//27cb9f5b991c2933f5faae716e99bd50c66a45811b1424128269312bdd570dff
$payload = "<CreateGiftCardRequest><creationRequestId>Test001</creationRequestId><partnerId>Test</partnerId><value><currencyCode>USD</currencyCode><amount>10</amount></value></CreateGiftCardRequest>";
$hashedPayload = hash('sha256',$payload);//50bf24a091a7463bb4a2661f93a7299c94774bc81f9fddf02af2925922b869dc
$CanonicalRequestStr = "POST\n/CreateGiftCard\n\naccept:charset=UTF-8\ncontent-type:charset=UTF-8\nhost:agcod-v2-gamma.amazon.com\nx-amz-date:".TIME_STAMP_ISO_8601."\nx-amz-target:com.amazonaws.agcod.AGCODService.CreateGiftCard\n\naccept;content-type;host;x-amz-date;x-amz-target\n".$hashedPayload;
$hashedCanonicalRequest = hash('sha256',$CanonicalRequestStr);//7d9f2765e4f23e85d3dce4ae264dac4f784c152f3746aff45ac7f3afd7fad649
$str2Sign = "AWS4-HMAC-SHA256\n".TIME_STAMP_ISO_8601."\n".TIME_STAMP."/".REGION_CODE."/".SERVICE_NAME."/aws4_request\n".$hashedCanonicalRequest;
$signature = hash_hmac('sha256', $str2Sign, $signingKey);//e32110cf663ed86460621dff12bb1139afe29d015584d208df09f149fa1b69d1
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,'https://agcod-v2-gamma.amazon.com/CreateGiftCard');
curl_setopt($ch, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);
//curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'accept:charset=UTF-8',
'content-type:charset=UTF-8',
'host:agcod-v2-gamma.amazon.com',
'x-amz-date:'.TIME_STAMP_ISO_8601,
'x-amz-target:com.amazonaws.agcod.AGCODService.CreateGiftCard',
'Authorization:AWS4-HMAC-SHA256 Credential='.ACCESS_KEY.'/'.TIME_STAMP.'/us-east-1/AGCODService/aws4_request, SignedHeaders=accept;content-type;host;x-amz-date;x-amz-target,Signature='.$signature,
));
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
$return = curl_exec($ch);
$return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
var_dump($return_code);
?>
The AWS SDK for PHP has a SignatureV4 implementation. There is no PHP client included for AGCOD, since it is not an AWS service, but the DynamoDB service works very similarly to how AGCOD works. I was able to hack the DynamoDB client to send requests to AGCOD instead.
<?php
require 'vendor/autoload.php'; // If installed via Composer.
// Instantiate DynamoDB client, but overwrite a bunch of the settings
// to work with the AGCOD service
$client = \Aws\DynamoDb\DynamoDbClient::factory([
'base_url' => 'https://agcod-v2-gamma.amazon.com',
'key' => 'AWS_ACCESS_KEY_ID',
'secret' => 'AWS_SECRET_ACCESS_KEY',
'region' => 'us-east-1',
'signature' => 'v4',
'signature.service' => 'AGCODService',
'signature.region' => 'us-east-1',
]);
// Add wire logger for debugging
$client->addSubscriber(\Guzzle\Plugin\Log\LogPlugin::getDebugPlugin());
$body = <<<JSON
{"requestId": "Awssb0327141418PM", "partnerId": "Awssb", "utcStartDate":
"2014-03-27T00:10:10Z", "utcEndDate": "2014-03-27T23:59:59Z", "pageIndex": 0,
"pageSize": 200, "showNoOps": "true"}
JSON;
try {
// Use underlying Guzzle feature to send request,
// to skip some of the DynamoDB-specific logic.
$response = $client->put('GetGiftCardActivityPage', [
'x-amz-target' => 'com.amazonaws.agcod.AGCODService.GetGiftCardActivityPage',
'accept' => 'application/json'
], $body)->send();
} catch (\Aws\Common\Exception\ServiceResponseException $e) {
echo $e; // This exception class has a __toString() method.
}
Note sure if this will help much, but it could be used as a starting point if you decide to cherry pick code from the AWS SDK for PHP.

Using curl instead of http request 2 in PHP

I'm trying to use curl instead of the http request 2 pear module in PHP to query the plivo api. They have an existing library for easily making calls to their API but it uses a pear module called http request2. I don't really know how to install a pear module on a server so I thought of just rewriting some parts of their library to just use curl.
Here's the part of their code that I specifically want to modify:
function __construct($auth_id, $auth_token, $url="https://api.plivo.com", $version="v1") {
if ((!isset($auth_id)) || (!$auth_id)) {
throw new PlivoError("no auth_id");
}
if ((!isset($auth_token)) || (!$auth_token)) {
throw new PlivoError("no auth_token");
}
$this->version = $version;
$this->api = $url."/".$this->version."/Account/".$auth_id;
$this->auth_id = $auth_id;
$this->auth_token = $auth_token;
}
private function request($method, $path, $params=array()) {
$url = $this->api.rtrim($path, '/').'/';
if (!strcmp($method, "POST")) {
$req = new HTTP_Request2($url, HTTP_Request2::METHOD_POST);
$req->setHeader('Content-type: application/json');
if ($params) {
$req->setBody(json_encode($params));
}
} else if (!strcmp($method, "GET")) {
$req = new HTTP_Request2($url, HTTP_Request2::METHOD_GET);
$url = $req->getUrl();
$url->setQueryVariables($params);
} else if (!strcmp($method, "DELETE")) {
$req = new HTTP_Request2($url, HTTP_Request2::METHOD_DELETE);
$url = $req->getUrl();
$url->setQueryVariables($params);
}
$req->setAdapter('curl');
$req->setConfig(array(
'timeout' => 30,
'ssl_verify_peer' => FALSE,
));
$req->setAuth($this->auth_id, $this->auth_token, HTTP_Request2::AUTH_BASIC);
$req->setHeader(array(
'Connection' => 'close',
'User-Agent' => 'PHPPlivo',
));
$r = $req->send();
$status = $r->getStatus();
$body = $r->getbody();
$response = json_decode($body, true);
return array("status" => $status, "response" => $response);
}
public function get_account($params=array()) {
return $this->request('GET', '', $params);
}
And here's the code that I have so far:
<?php
$curl = curl_init();
$curl_options = array(
CURLOPT_URL => 'https://api.plivo.com/v1/Account/',
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_USERPWD => 'auth_id:auth_token',
CURLOPT_HTTPHEADER => array("Connection: close", "User-Agent: PHPPlivo"),
CURLOPT_TIMEOUT => 30
);
curl_setopt_array($curl, $curl_options);
$response = curl_exec($curl);
curl_close($curl);
?>
I don't really know what's going on behind the scenes but this specific code is telling me that its using basic authentication using the values for the auth id and auth token:
$req->setAuth($this->auth_id, $this->auth_token, HTTP_Request2::AUTH_BASIC);
So I also set it using curl:
CURLOPT_USERPWD => 'auth_id:auth_token',
I'm pretty much stuck. All I get as a respose is the following:
{
"error": "not found"
}
It doesn't really make much sense into what I have missed or done wrong. Please help. Thank you in advance!
Below are the things you need to handle to sync your new code with old one:
If you are using GET method
CURLOPT_URL => 'https://api.plivo.com/v1/Account/'.http_build_query($params),
CURLOPT_HTTPHEADER => array("User-Agent: PHPPlivo"),
If you are using POST method
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query($params),
CURLOPT_HTTPHEADER => array("Content-type: application/json", "User-Agent: PHPPlivo"),
Yea... The PEAR dependency is definitely overkill for Plivo's wrapper. So that was one of the first modifications I made to the code.
Check out:
https://github.com/ashbeats/Plivo-Curl-Based-Wrapper/
Only difference is the RestAPI::request() method.

Categories