How to re-write this cURL request in Guzzle 6? - php

Example Code (provided by Channel Advisor):
https://developer.channeladvisor.com/authorization/updating-access-token/php-updating-access-token
<?php
$endpoint = "https://api.channeladvisor.com/oauth2/token";
$refresh_token="{{REFRESH_TOKEN}}";
$application_id= "{{APPLICATION_ID}}";
$shared_secret="{{SHARED_SECRET}}";
$url = $endpoint;
$client_id = base64_encode("$application_id:$shared_secret");
$body = "grant_type=refresh_token&refresh_token=$refresh_token";
$length = strlen($body);
$headers = array(
"Authorization: Basic $client_id",
"Content-Type: text/plain",
"Cache-Control: no-cache",
"Content-Length: $length"
);
echo "URL:".$url."\n";
echo "Body:$body\n";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($curl);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
print_r($httpcode);
echo"\n";
$json = json_decode($result, true);
var_dump($json);
?>
Attempting to rewrite as Guzzle HTTP request:
My question is am I setting the Basic authentication correctly?
$accessToken = {{ACCESS_TOKEN}};
$refresh_token = {{ACCESS_TOKEN}};
$application_id = {{APPLICATION_ID}};
$shared_secret = {{SHARED_SECRET}};
$base_uri = "https://api.channeladvisor.com/oauth2/token";
$client_id = 'Basic ' . base64_encode("$application_id:$shared_secret");
$client = new Client(
['headers' => [
'Content-Type' => 'application/x-www-form-urlencoded',
'Authorization' => $client_id
]
]
);
$result = $client->request('POST', $base_uri, [
'query' => [
'grant_type' => 'refresh_token',
'refresh_token' => $refresh_token
],
]);
$body = $response->getBody();
// Implicitly cast the body to a string and echo it
echo $body;

You're sending POST request, then I guess you should send FORM data, not QUERY data.
$response = $client->request('POST', $base_uri, [
'form_params' => [
'grant_type' => 'refresh_token',
'refresh_token' => $refresh_token
],
]);

Related

Request fails on curl but works on guzzle

Am using the following post request on guzzle to microsoft graph which works.
$client = new Client([
'headers' => [ 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ' . $token ]
]);
$url = "myurl";
$response = $client->post(
$url,
[
'body' => json_encode(
[
"startDateTime"=>$arr['start_date'],
"endDateTime"=>$arr['end_date'],
"meeting"=>$arr['subject']
]
)]
);
$payload = json_decode($response->getBody()->getContents());
var_dump($payload) //here has data
The am doing the same request via curl using
$post = [
"meeting"=>$arr['subject'],
"startDateTime"=>$arr['start_date'],
"endDateTime"=>$arr['end_date'],
];
$authorization = "Authorization: Bearer ".$token;
$headers = [
'Content-Type' => 'application/json',
$authorization
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$error = curl_errno($ch) ? curl_error($ch) : '';
curl_close($ch);
if ($error){
var_dump($error);
throw new Exception($error,500);
}
return $response;
But in curl the above in micorsoft graph throws an error Expected not null\r\nParameter name: meeting but the meeting parameter is not empty. I have also tried setting the value of meeting directly via
$post = [
"meeting"=>"Test meeting",
"startDateTime"=>$arr['start_date'],
"endDateTime"=>$arr['end_date'],
];
But still doesnt solve. I guess it has something to do with body parameter i have set on guzzle which works. How can i resolve this to have it work even on curl

Sending Firebase notification with PHP

everyone! I am having a problem using PHP to send FIrebase notification. When I send it from Firebase console, I get the notification, but when I send it from PHP, I don't receive any notification.
DO you have any idea what is the problem?
Here is my PHP code:
<?php
$message = 'ojlaasdasdasd';
$title = 'ojla';
$path_to_fcm = 'https://fcm.googleapis.com/fcm/send'; $server_key='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx5LnDZO2BpC2aoPMshfKwRbJAJfZL8C33qRxxxxxxxxxxxxL6';
$key = 'eqnlxIQ1SWA:APA91bGf1COAZamVzT4onl66_lEdE1nWfY7rIADcnt9gtNYnw7iWTwa7AYPYTHESFholkZ89ydCQS3QeL-lCIuiWTXiqoDREO0xhNdEYboPvqg8QsBYkrQVRlrCLewC4N-hHUja1NG4f';
$headers = array(
'Authorization:key=' .$server_key,
'Content-Type: application/json');
$fields = array
(
'to' => $key,
'notification' => array('title' => $title,'body' => $message)
);
$payload = json_encode($fields);
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, '$path_to_fcm' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt( $ch,CURLOPT_POSTFIELDS, $payload);
$result = curl_exec($ch);
echo $result;
curl_close($ch);
?>
I don't get any echo from the server
try this code.Its working fine for me.just change key and token
<?php
define('API_ACCESS_KEY','Api key from Fcm add here');
$fcmUrl = 'https://fcm.googleapis.com/fcm/send';
$token='235zgagasd634sdgds46436';
$notification = [
'title' =>'title',
'body' => 'body of message.',
'icon' =>'myIcon',
'sound' => 'mySound'
];
$extraNotificationData = ["message" => $notification,"moredata" =>'dd'];
$fcmNotification = [
//'registration_ids' => $tokenList, //multple token array
'to' => $token, //single token
'notification' => $notification,
'data' => $extraNotificationData
];
$headers = [
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$fcmUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fcmNotification));
$result = curl_exec($ch);
curl_close($ch);
echo $result;
I use the following function to send a HTTP Request to Firebase:
function request($url, $body, $method = "POST", $header = "Content-type: application/x-www-form-urlencoded\r\n")
{
switch ($method) {
case 'POST':
case 'GET':
case 'PUT':
case 'DELETE':
break;
default:
$method = 'POST';
break;
}
$options = array(
'http' => array(
'header' => "$header",
'method' => "$method",
'content' => $body
)
);
$context = stream_context_create($options);
$data = file_get_contents($url, false, $context);
$data = json_decode($data, true);
return $data;
}
To execute the function I use the following code:
$fcm_key = "";
$body = array("data" => $data, "to" => "$fcm_token");
$body = json_encode($body);
$json = request("https://fcm.googleapis.com/fcm/send", $body, "POST", "Authorization: key=$fcm_key\r\nContent-Type:application/json");
For me, this code works without any problems. Be sure that you use the right FCM device token ($fcm_token) and set the right FCM key ($fcm_key).
$tokenID = $valueTwo["TokenID"];
$cmMessage = array();
$cmMessage["type"] = 3;
$cmMessage["receiverMail"] = $receiverMail;
$cmMessage["ownerMail"] = $ownerMail;
$cmMessage["jsonData"] = $jsonData;
$url = "https://fcm.googleapis.com/fcm/send";
$title = "";
$body = "";
//$notification = array('title' => $title, 'body' => null, 'sound' => 'default', 'badge' => '1');
$arrayToSend = array('to' => $tokenID, 'priority' => 'high', 'data' => $cmMessage);
$json = json_encode($arrayToSend);
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: key=' . $serverKey;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
//Send the request
$response = curl_exec($ch);
//Close request
if ($response === FALSE) {
die('FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);
Get your server key and token id to send write them... Dont use notification tag...Like I did in code... Cuz if you write notification tag, Application in background is not got receive msg Cuz notification tag executes on foreground and in background automatic notification is displayed..
Send firebase push notification via php to android, ios
function sendPushNotification($to = '', $data = array()){
$api_key = '';
$fields = array('to' => $to, 'notification' => $data);
$headers = array(
'Content-Type:application/json',
'Authorization:key='.$api_key
);
$url = 'https://fcm.googleapis.com/fcm/send';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
$to = ''; //Device token
// You can get it from FirebaseInstanceId.getInstance().getToken();
$message = array(
'title' => 'Hai',
'body' => 'New Message');
echo sendPushNotification($to, $message);

I want to call call the mifinity api using php

I am using the following api:http://apidocs.mifinity.com/#/doc/2 but its not working??
My API key
$data = array(
'key' => "1234567777"
);
$url = 'https://demo.mifinitypay.com/';
$ch = curl_init($url);
$postString = http_build_query($data, '', '&');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);
$request = new HttpRequest();
$request->setUrl('https://demo.mifinitypay.com/api/oauth/token');
$request->setMethod(HTTP_METH_POST);
$request->setHeaders(array(
'postman-token' => '6396dfb7-540b-0e7d-7333-5d0eeff4d606',
'cache-control' => 'no-cache',
'authorization' => 'Basic username:password encoded using Base64',
'x-api-version' => '1',
'accept' => 'application/json',
'content-type' => 'application/x-www-form-urlencoded'
));
$request->setContentType('application/x-www-form-urlencoded');
$request->setPostFields(array(
'grant_type' => 'client_credentials'
));
try {
$response = $request->send();
echo $response->getBody();
} catch (HttpException $ex) {
echo $ex;
}

Api working on curl and not on GuzzleHttp

I'm trying to connect to the Talentlink Api. I'm able to do it on curl but I can't connect using GuzzleHttp. I'm using Guzzle through the m6web/guzzle-http-bundle on Symfony. My code is below. Does anybody have an idea?
CURL
$headers = [
'username: XXXXX',
'password: XXXXX'
];
$body = '{
"searchCriteriaSorting": {
"categoryListsSorting": "LABEL",
"customLovsSorting": "ORDER",
"standardLovsSorting": "ORDER"
}
}';
$tuCurl = curl_init();
curl_setopt($tuCurl, CURLOPT_URL, "https://api3.lumesse-talenthub.com/CareerPortal/REST/FoAdvert/advertisement-by-id?api_key=XXXXXX&lang=FR&postingTargetId=1");
curl_setopt($tuCurl, CURLOPT_VERBOSE, 1);
curl_setopt($tuCurl, CURLOPT_HEADER, 1);
curl_setopt($tuCurl, CURLINFO_HEADER_OUT, 1);
curl_setopt($tuCurl, CURLOPT_HTTPHEADER, $headers);
$head = curl_exec($tuCurl);
$httpCode = curl_getinfo($tuCurl, CURLINFO_HTTP_CODE);
curl_close($tuCurl);
GUZZLE
$headers = [
'username' => 'XXXXXX',
'password' => 'XXXXXX'
];
try {
$response = $client->request('GET',
'https://api3.lumesse-talenthub.com/CareerPortal/REST/FoAdvert/advertisement-by-id?api_key=XXXXX&lang=FR&postingTargetId=1',
array(
'debug' => true,
$headers
));
} catch (ClientException $e) {
die((string)$e->getResponse()->getBody()->getContents());
}
On Guzzle, I keep getting a page with a login form as if I wasn't connected. However, the status is always 200 so it's difficult to debug.
SOLUTION
It was a problem with the array I was sending. It should be like this wit the 'header' key:
$response = $client->request('GET',
'https://api3.lumesse-talenthub.com/CareerPortal/REST/FoAdvert/advertisement-by-id?api_key=XXXX&lang=FR&postingTargetId=1',
[
'headers' => $headers,
//'debug' => true
]);

cURL request Spotify API Unexpected status: 415

Here is my script for an auth request to Spotify but it returns an error. I tried changing the Content-Type, but that doesn't seem to cut it. Here is my code:
$spot_api_client = 'client';
$spot_api_secret = 'secret';
$spot_api_redirect = 'myurl';
if(isset($_GET['state']) && isset($_COOKIE['stateKey']) && $_COOKIE['stateKey'] == $_GET['state']){
$ch = curl_init();
$curlConfig = array(
CURLOPT_URL => "https://accounts.spotify.com/api/token",
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => array(
'grant_type' => 'authorization_code',
'code' => $_GET['code'],
'redirect_uri' => urlencode($spot_api_redirect),
),
CURLOPT_HTTPHEADER => array(
'Accept' => '*/*',
'User-Agent' => 'runscope/0.1',
'Authorization' => 'Basic '. base64_encode($spot_api_client.':'.$spot_api_secret),
'Content-Type'=>'application/json'
)
);
curl_setopt_array($ch, $curlConfig);
$result = curl_exec($ch);
curl_close($ch);
print_r($result);
}
Well, seems I found the answer based on this question :
$url = 'https://accounts.spotify.com/api/token';
$method = 'POST';
$spot_api_redirect = 'myurl';
$credentials = "client:secret";
$headers = array(
"Accept: */*",
"Content-Type: application/x-www-form-urlencoded",
"User-Agent: runscope/0.1",
"Authorization: Basic " . base64_encode($credentials));
$data = 'grant_type=authorization_code&code='.$_GET['code'].'&redirect_uri='.urlencode($spot_api_redirect);
if(isset($_GET['state']) && isset($_COOKIE['stateKey']) && $_COOKIE['stateKey'] == $_GET['state']){
unset($_COOKIE['stateKey']);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = json_decode(curl_exec($ch), true);
curl_close($ch);
print_r($response);
}
Just in case of node.js / request use, point out "WTF" tag :)
request(
{
method : "POST",
url : "https://accounts.spotify.com/api/token",
json : true,
headers :
{
"Content-Type" : "application/x-www-form-urlencoded", // WTF!
"Authorization" : "Basic " + new Buffer(client_id+":"+client_secret).toString('base64')
},
body : "grant_type=client_credentials"
},
function (err, response, body)
{
if (err)
{
cb(err);
}
else
{
if (body.hasOwnProperty("access_token"))
{
access_token = body.access_token;
cb(null);
}
else
{
cb(body);
}
}
}
);

Categories