How to invoke a function that accepts Request Object from another function? - php

In a PHP OAuth Implementation, there is a function as below:
/**
* Processes POST requests to /oauth/token.
*/
public function token(ServerRequestInterface $request) {
// Extract the grant type from the request body.
$body = $request->getParsedBody();
$grant_type_id = !empty($body['grant_type']) ? $body['grant_type'] : 'implicit';
/*.. CODE TRIMMED ..*/
catch (OAuthServerException $exception) {
watchdog_exception('simple_oauth', $exception);
$response = $exception->generateHttpResponse(new Response());
}
return $response;
}
I think its an instance of:
Psr\Http\Message\ServerRequestInterface;
I want to call this function, and pass the body params to this function from another function. Something as below:
public function call_token(){
//Something like this??
$request = new ServerRequestInterface();
$request->setUrl('https://some.url/oauth/token');
$request->setMethod("POST");
$request->setHeader(array(
'Content-Type' => 'application/x-www-form-urlencoded',
));
$request->addPostParameter(array(
'grant_type' => 'password',
'client_id' => '828472a8-f2c5-4e79-a158-ab041d3b313a',
'client_secret' => 'secret',
'username' => 'admin',
'password' => '123'
));
$response = $token($request);
}
I am not able to figure out how we can call this function.
This is the full source code where the token code is implemented. I am trying to call this function from another class.
Below is a working CURL request of how requests are made to this endpoint. I however want to emulate the request from within the application.
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://some.url/oauth/token',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => 'grant_type=password&client_id=828472a8-f2c5-4e79-a158-ab041d3b313a&client_secret=secret&username=admin&password=123',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/x-www-form-urlencoded',
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;

Related

how to add variable php parameters to urlencoded strings from Postman

I am testing an api on postman. The request body should be in x-www-form-url-encoded. My requests are being passed successfully, and am able to generate a snippet which I have shared here. However, some of the parameters that am adding to the body (Amount, and phone number) will not be static when the api is employed on my site. These parameters will vary by user. I have tried to define those parameters at the top of the code as you cane see $Airtime_amount and
$Recieving_mobile, but how can I pass them to the x-www-form-url-encoded CURLOPT_POSTFIELDS in the code below? See how am trying to pass them, but without success...
In other words, I have a url encoded string from postman, but the parameters in that string are static. i would like to make them dynamic..Like get user phone number from wordpress, and insert it in the urlencoded string
//Wordpress hook to call the api begins here
add_action('hrw_withdrawal_request_notification','disburse_airtime',7);
function disburse_airtime() {
$Airtime_amount = "KES 230";
$Recieving_mobile = "+254757777777";
//Snippet generated from postman begins here
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.sandbox.africastalking.com/version1/airtime/send',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => 'username=sandbox&recipients=%5B%7B%22phoneNumber%22%3D%3E%24Recieving_mobile%2C%22amount%22%3D%3E%24Airtime_amount%7D%5D',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/x-www-form-urlencoded',
'apiKey: 61449ca078574078a6d0eaaa01cfb751f803797c99714f74d8541a25e2a612ef',
'Accept: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
}
You should probably build the POSTFIELDS string using the http_build_query function.
Your existing string has what looks like a JSON string for the value of the recipients parameter, so we can build that up using arrays, then encode it when we set it in the params.
function disburse_airtime()
{
$Airtime_amount = "KES 230";
$Recieving_mobile = "+254757777777";
$recipients = [
[
'phoneNumber' => $Recieving_mobile,
'amount' => $Airtime_amount
]
];
$params = [
'username' => 'sandbox',
'recipients' => json_encode($recipients)
];
$postFields = http_build_query($params);
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => 'https://api.sandbox.africastalking.com/version1/airtime/send',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $postFields,
CURLOPT_HTTPHEADER => [
'Content-Type: application/x-www-form-urlencoded',
'apiKey: 61449ca078574078a6d0eaaa01cfb751f803797c99714f74d8541a25e2a612ef',
'Accept: application/json'
],
]);
$response = curl_exec($curl);
curl_close($curl);
echo $response;
}
Side note, if you want to "reverse engineer" the data that is in the encoded string in order to build it up in your own code, you can do so with using urldecode and parse_str:
$str = 'username=sandbox&recipients=%5B%7B%22phoneNumber%22%3D%3E%24Recieving_mobile%2C%22amount%22%3D%3E%24Airtime_amount%7D%5D';
parse_str(urldecode($str), $params);
print_r($params);
Result:
Array
(
[username] => sandbox
[recipients] => [{"phoneNumber"=>$Recieving_mobile,"amount"=>$Airtime_amount}]
)

How to pass client certificate through HTTP Client in php laravel 8

How to pass client certificate (2 files .key and .pem) through http client request?
I need to include those files in the below http post request to be able to talk with the server.
$response = Http::post('https://domainname.com/api/client/session', array('xxx' => array('xx' => 'xxxx')));
I am able to do it using phpCurl like below:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => $type,
CURLOPT_POSTFIELDS => $body,
CURLOPT_HTTPHEADER => $header,
CURLOPT_SSLKEY => $pemPath,
CURLOPT_SSLCERT => $crtPath,
// CURLOPT_NOSIGNAL => 1
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
echo (json_encode($response));
echo ("\n\n");
if ($err) {
return ["success" => false, "message" => $err];
} else {
return ["success" => true, "data" => json_decode($response)];
}
But I need to do it using Http Client for many other purposes. Any suggestion?
You can use Guzzle options provided by http client
$response = Http::withOptions([
'ssl_key' => ['/path/to/cert.pem', 'password.key']
])->post('https://domainname.com/api/client/session');
It would be same as using ssl_key request option for guzzle http client instance directly.
use GuzzleHttp\Client;
$client = new Client();
$client->request('POST', 'https://domainname.com/api/client/session', [
'ssl_key' => ['/path/to/cert.pem', 'password.key']
]);

cURL post request php to spring

I have to send array of a file to a spring server using PHP and cURL.
This is spring controller:
#RequestMapping(value = "/upload/teacher" ,method = RequestMethod.POST)
public HttpStatus uploadFiles(#RequestParam("files") MultipartFile[] inputFiles,
#RequestParam("assignmentID") String assignmentID) throws IOException { ... }
PHP cURL:
<?php
$filenames = array(pathfile1, pathfile2);
$postparameters = array(
'files' => array(
new CURLFile($filenames[0], "text/plain", pathinfo($filenames[0], PATHINFO_BASENAME)),
new CURLFile($filenames[1], "text/plain", pathinfo($filenames[1], PATHINFO_BASENAME))
),
'assignmentID' => "0008"
);
print_r($postparameters);
//init curl
$url = "http://localhost:8090/upload/teacher";
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postparameters,
CURLOPT_HTTPHEADER => array(
"Content-Type: multipart/form-data"
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
but with this code the backend does not receive anything.
if I send the curl request from the terminal, it works:
curl -F files=#"pathfile1","pathfile2" -F assignmentID="1" http://localhost:8090/upload/teacher
it also works on postman:
https://i.stack.imgur.com/Mo3yg.png]1
can someone tell me why if the backend does not receive the files when I run the request from php?
What happens if you annotate your spring controller method with #CrossOrigin ?
#CrossOrigin
#RequestMapping(value = "/upload/teacher" ,method = RequestMethod.POST)
public HttpStatus uploadFiles(#RequestParam("files") MultipartFile[] inputFiles,
#RequestParam("assignmentID") String assignmentID) throws IOException { ... }

cUrl in Laravel same port is not working in my code

I'm setting new fitur Login API in my website using cUrl.
When I run in Postman, is working (screnshoot 2). but when i run in my website using cUrl is not working and still loading. if i not set timeout, it will continue to load until infinite time like in screnshoot 1.
image 1 : when i run in my website
image 2 : when i run in Postman
This is my code
Login Controller for proses login from API/cUrl Request
public function login()
{
if (Auth::attempt(['email' => request('email'), 'password' => request('password')])) {
$user = Auth::user();
return response()->json(['result' => true, 'message' => "heyho" ], 200);
// $token = $user->createToken('nApp')->accessToken;
// return response()->json(['result' => true, 'message' => $token ], $this->successStatus);
} else {
return response()->json(['result'=> false, 'message' => 'Unauthorised'], 401);
}
}
This is my code cUrl Process/Request.
public function tes()
{
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_PORT => "8001",
CURLOPT_URL => "http://localhost:8001/api/login",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"email\"\r\n\r\email#gmail.com\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"password\"\r\n\r\bbbbb\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
"postman-token: 3546ebed-2016-df32-6d9d-91cdfd43066a"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
// return url('/')."/api/login";
}
Your request is "POST" then how you can see the result in web page
Only "GET" request only show the results on the web page
"GET" : In this case we can pass the parameter in the url
like : https//:localhost:8000/api/user/1
"POST" : In this case we pass the body in the request body so we need postman to pass the request body"
For more info you can check https://www.w3schools.com/tags/ref_httpmethods.asp

How can I get response from guzzle 6 in Laravel 5.3?

I read from here : http://www.phplab.info/categories/laravel/consume-external-api-from-laravel-5-using-guzzle-http-client
I try like this :
...
use GuzzleHttp\Client as GuzzleHttpClient;
use GuzzleHttp\Exception\RequestException;
...
public function testApi()
{
try {
$client = new GuzzleHttpClient();
$apiRequest = $client->request('POST', 'https://myshop/api/auth/login', [
// 'query' => ['plain' => 'Ab1L853Z24N'],
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'auth' => ['test#gmail.com', '1234'], //If authentication required
// 'debug' => true //If needed to debug
]);
$content = json_decode($apiRequest->getBody()->getContents());
dd($content);
} catch (RequestException $re) {
//For handling exception
}
}
When executed, the result is null
How can I get the response?
I try in postman, it success get response
But I try use guzzle, it failed
Update :
I check on the postman, the result works
I try click button code on the postman
Then I select php curl and I copy it, the result like this :
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://myshop/api/auth/login",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"email\"\r\n\r\ntest#gmail.com\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"password\"\r\n\r\n1234\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
"postman-token: 1122334455-abcd-edde-aabe-adaddddddddd"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
If it use curl php, the code like that
How can I get the response if it use guzzle?
I see at least one syntax mistake. The third argument of the request() method should look like this:
$requestContent = [
'headers' = [],
'json' = []
];
In your case it could be:
public function testApi()
{
$requestContent = [
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json'
],
'json' => [
'email' => 'test#gmail.com',
'password' => '1234',
// 'debug' => true
]
];
try {
$client = new GuzzleHttpClient();
$apiRequest = $client->request('POST', 'https://myshop/api/auth/login', $requestContent);
$response = json_decode($apiRequest->getBody());
dd($response);
} catch (RequestException $re) {
// For handling exception.
}
}
There are other parameters instead of json for your data, for example form_params. I suggest you take a look at the Guzzle documentation.

Categories