Displaying cURL JSON response with Dingo API (Laravel) - php

I'm sending a requests via cURL to an external webservice and I'm receiving a response in JSON format. Something like this:
public function store(Request $request)
{
$loggedInUser = app('Dingo\Api\Auth\Auth')->user();
if (!$loggedInUser instanceof User) {
$this->response->errorUnauthorized();
}
$data = $request->all();
$url = env('WEBSERVICE_URL');
$payload = json_encode(['n' => $data['n']]);
$auth = 'Authorization: ' . env('API_KEY');
$headers = [
'Content-Type:application/json',
$auth
];
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
The problem is that the response of function is like this
{
"code": 200,
"status": "success",
"data": "{\"message\":\"n saved successfully!\"}"
}
And not like this (the json I received from the webservice)
{"message": "n saved successfully!"}
I'm not really an expert with Dingo API but I can imagine that this probably has to do with some kind of default response format Dingo applies to the returned values in the functions.
Anyways, in this case I would like it to return the second response above mentioned. Is there any way to disable the default response format Dingo applies in particular cases? Or do you think this is caused by something else?

Related

PHP post failed cloudflare api

i'm trying to update my DNS domain record through cloudflare api using PHP Post, but the cloudflare api send response that POST method is not allowed for the api_token authentication scheme, i already tried the the api using postman and it works, but somehow in PHP the api does not work, is PHP does not support POST using token ?, some variable is stored inside env.php and i hide it because it sensitive information.
PHP code :
include("../../env.php");
//variable input by POST
$domain = $_POST['domain'];
$recordID = $_POST['recordID'];
$content = $_POST['content'];
$zoneID = $_POST['zoneID'];
//for update record
$linkRecord = "https://api.cloudflare.com/client/v4/zones/$zoneID/dns_records/$recordID";
$header = array(
"Content-Type: application/json",
"Authorization: Bearer $authToken"
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $linkRecord);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
$bodyArray = array("type"=>"A","name"=>$domain,"content"=>$content,"proxied"=>true);
$body = json_encode($bodyArray);
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
$resp = curl_exec($curl);
print_r($resp);
linkRecord Variable Value:
https://api.cloudflare.com/client/v4/zones/{{my_secret_zone_id}}/dns_records/{{id_of_the_record}}
Cloudflare response of POST :
{
"success": false,
"errors": [
{
"code": 10000,
"message": "POST method not allowed for the api_token authentication scheme"
}
]
}

Google Mybusiness API getLocatiosn returns empty

I got a verified location in google mybusiness but when i use the API, it returns an empty array [] I am using this endpoint. I am using laravel 6 and curl library for HTTP requests in this project.
'https://mybusiness.googleapis.com/v4/accounts/117177930435384486747/locations'
Here is my whole controller function
public function getLocations(Request $request){
$url = 'https://mybusiness.googleapis.com/v4/accounts/'.$request->account_id.'/locations:batchGet';
$headers = array(
'Content-Type: application/json',
'Authorization: Bearer '.$request->bearer_token
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close ($ch);
return response()->json(json_decode($result,true));
}
What did I miss? I already got the account info by using this endpoint
https://mybusiness.googleapis.com/v4/accounts and it got me a response of
{
"accounts": [
{
"name": "accounts/117177930435384486747",
"accountName": "Michael koh",
"type": "PERSONAL",
"state": {
"status": "UNVERIFIED",
"vettedStatus": "NOT_VETTED"
},
"profilePhotoUrl": "//lh6.googleusercontent.com/-Jv5Xr7SXjuE/AAAAAAAAAAI/AAAAAAAAAAA/QryQ_2-Mjqo/s132-mo/photo.jpg"
}
]
}
In the response, it says not verified. But when i go to google mybusiness UI. I got this when i click manage location. Seems weird because it shows verified.
PS:
I tried getting the location by calling this endpoint GET https://mybusiness.googleapis.com/v4/{parent=accounts/*}/locations but I got an empty array

How can I handle data returned from an API endpoint (django application) in a php laravel application route

I have a Django API application using Django rest framework which works just fine. I have another PHP laravel application that is supposed to consume the API. When I post data to the API endpoint using curl, the data is stored and an object is returned.
I am supposed to grab this object and use the data. However, the object that is returned is printed on the page when I visit the route that executes the post request.
When I do dd($data) with the variable that is supposed to contain the returned data, I get a boolean (true when the data was posted successfully and false if something went wrong).
Route::get('test-create-client', function (){
try {
$data = ApiController::createClient('John D', '0711111111', '', 'Male', '1980'.'-'.date('m-d'));
} catch (Exception $exception) {
return $exception->getMessage();
}
dd($data); // I get a boolean from here
});
//creatClient from the ApiController
public static function createClient($name, $phone, $care_of, $gender, $date_of_birth)
{
$url = "client/clients/";
$client = '{
"name": "'.$name.'",
"telephone_number": "'.$phone.'",
"alternative_telephone_number": "'.$alt_phone.'",
"care_of": "'.$care_of.'",
"gender": "'.$gender.'",
"date_of_birth": "'.$date_of_birth.'",
}';
return ServicesApiController::RunCurlPostServices($url, $client);
}
//CurlRequest
public static function RunCurlPostServices($url, $json)
{
$ch = curl_init(env('SERVICES_API_URL').$url);
curl_setopt($ch, CURLOPT_POST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/json",
"authorization: token *******"));
return curl_exec($ch);
}
I need $data to have the data returned by the API endpoint and not a boolean value.
In order for curlpost to return the content returned by an API request, I had to set CURLOPT_RETURNTRANSFER to true. For some reason I had missed it out.
So updating my curl request to
public static function RunCurlPostServices($url, $json)
{
$ch = curl_init(env('SERVICES_API_URL').$url);
curl_setopt($ch, CURLOPT_POST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/json",
"authorization: token *******"));
return curl_exec($ch);
}
Fixed the issue.
This helped.
Thanks for the effort #Rezrazi
Laravel does not have a built in http client, for that you need to use a tool or a package.
I recommend guzzle and its documentation
You can use it this way in your GET method
$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'https://myapplication.com/endpoint');
$data = $res->getBody();

Calling cloudconvert API inside my REST API

I have created a test function in my REST API (using the SLIM framework) for testing my implementation of a wrapper class for the cloudconvert API.
$app->get('/test', 'authenticate', function() use ($app) {
$response = array();
$converter = new CloudConverter();
$url = $converter->createProcess("docx","pdf");
$response["url"] = $url;
echoRespnse(201, $response);
});
My createProcess function inside CloudConverter class looks like this:
public function createProcess($input_format,$output_format)
{
$this->log->LogInfo("CreateProcess Called");
$headers = array('Content-type: application/json');
$curl_post_data = array('apikey' => API_KEY,'inputformat' => $input_format,'outputformat' => $output_format);
$curl = curl_init(CLOUD_CONVERT_HTTP);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($curl_post_data));
$curl_response = curl_exec($curl);
if ($curl_response === false)
{
$info = curl_getinfo($curl);
curl_close($curl);
die('error occured during curl exec. Additioanl info: ' . var_export($info));
$this->log->LogInfo('error occured during curl exec. Additioanl info: ' . var_export($info));
}
curl_close($curl);
$decoded = json_decode($curl_response,true);
return $decoded['url'];
}
I have tested my API using Chrome Advanced Rest Client and i see a successful response from my call to the cloudconvert API but that is not what i was expecting as can be seen in the code above. I was expecting to extract the url and return THAT in my response.
My Questions is:
HOW can i extract the url from the response from cloudconvert and return that in my own response.
You need to use
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true)
to return response as a string: curl docs.

Executing Curl in PHP to do a Stripe subscription

The Stripe API allows for Curl calls to be made. For example, the command:
curl https://api.stripe.com//v1/customers/cus_5ucsCmNxF3jsSY/subscriptions -u sk_test_REDACTED:
returns the subscription of customer cus_5ucsCmNxF3jsSY.
How can I use PHP to call this curl command (I am trying to avoid using the PHP Stripe libraries).
I am trying the following:
<?php
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "https://api.stripe.com//v1/customers/cus_5ucsCmNxF3jsSY/subscriptions -u sk_test_REDACTED:");
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
print($output);
// close curl resource to free up system resources
curl_close($ch);
?>
However, it seems that curl does not take the -u parameter of the URL. I get the following error:
{ "error": { "type": "invalid_request_error", "message": "You did not provide an API key. You need to provide your API key in the Authorization header, using Bearer auth (e.g. 'Authorization: Bearer YOUR_SECRET_KEY'). See https://stripe.com/docs/api#authentication for details, or we can help at https://support.stripe.com/." }
How can I pass the -u sk_test_REDACTED: parameter to my curl call?
I ran into the same issue. I wanted to use PHP's CURL functions instead of using the official stripe API because singletons make me nauseous.
I wrote my own very simple Stripe class which utilizes their API via PHP and CURL.
class Stripe {
public $headers;
public $url = 'https://api.stripe.com/v1/';
public $method = null;
public $fields = array();
function __construct () {
$this->headers = array('Authorization: Bearer '.STRIPE_API_KEY); // STRIPE_API_KEY = your stripe api key
}
function call () {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers);
switch ($this->method){
case "POST":
curl_setopt($ch, CURLOPT_POST, 1);
if ($this->fields)
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->fields);
break;
case "PUT":
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
if ($this->fields)
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->fields);
break;
default:
if ($this->fields)
$this->url = sprintf("%s?%s", $this->url, http_build_query($this->fields));
}
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec($ch);
curl_close($ch);
return json_decode($output, true); // return php array with api response
}
}
// create customer and use email to identify them in stripe
$s = new Stripe();
$s->url .= 'customers';
$s->method = "POST";
$s->fields['email'] = $_POST['email'];
$customer = $s->call();
// create customer subscription with credit card and plan
$s = new Stripe();
$s->url .= 'customers/'.$customer['id'].'/subscriptions';
$s->method = "POST";
$s->fields['plan'] = $_POST['plan']; // name of the stripe plan i.e. my_stripe_plan
// credit card details
$s->fields['source'] = array(
'object' => 'card',
'exp_month' => $_POST['card_exp_month'],
'exp_year' => $_POST['card_exp_year'],
'number' => $_POST['card_number'],
'cvc' => $_POST['card_cvc']
);
$subscription = $s->call();
You can dump $customer and $subscription via print_r to see the response arrays if you want to manipulate the data further.

Categories