i want to store response data like private property to variable when called method
use Illuminate\Support\Facades\Http;
public function myMethod(){
$result = [];
$response = Http::asForm()->withHeaders([
'origin' => 'https://example.com',
'content-type' => 'application/x-www-form-urlencoded',
'referer' => 'https://example.com',
])->post('https://example.com', [
'email' => 'example#gmail.com',
'pass' => 'mypassword',
'login' => 'Log+In',
'withCredentials' => true,
]);
$result = $response;
}
Result :
but i can't use keys in this result
Related
I am working on an API and MySQL project that will save some of the data in MySQL and some in the API
Controller (index function):
{
$response = Http::post('http://example.com/authenticate', [
'Username' => 'ADMIN',
'Password' => 'ADMIN',
'Token' => 'FK98D...',
]);
$token = json_decode($response, true);
$apiURL = 'http://example.com/api/SalesOrder/';
$headers = [
'Content-Type' => 'application/json',
'Authorization' => $token,
];
$response2 = Http::withHeaders($headers)->get($apiURL);
$data = $response2->json();
$jobdetail = JobDetail::all();
return view('api.auth.orders.index', compact('data','jobdetail'));
}
the above function is working correctly
Controller (store function):
public function store(Request $request)
{
$response = Http::post('http://example.com/authenticate', [
'Username' => 'ADMIN',
'Password' => 'ADMIN',
'Token' => 'FK98D...',
]);
$token = json_decode($response, true);
$request->validate([
'job_order_no' => 'required',
'sap_no' => 'required',
'pic_name' => 'required',
]);
JobDetail::create($request->all());
$store = Http::withHeaders([
'Content-Type' => 'application/json',
'Authorization' => $token,
])->post('http://example.com/api/SalesOrder/', [
'DocNo' => $request->job_order_no,
'TotalQty' => $request->TotalQty,
'TotalTransferredAOQty' => $request->TotalTransferredAOQty,
'SODTL' => array([
'DtlKey' => "",
'ItemCode' => $request->ItemCode,
])
]);
return $store;
}
and the above function is storing data to API and MySQL
note: that 'DocNo' is using the 'job_order_no' request so both will be the same value to be able to call it for show function (i am not sure if this is the best approach)
Controller (show function):
public function show($DocNo,JobDetail $company)
{
$client = new Client();
$headers = [
'Content-Type' => 'application/x-www-form-urlencoded'
];
$options = [
'form_params' => [
'Username' => 'ADMIN',
'Password' => 'ADMIN',
'Token' => 'FK98DL...'
]
];
$request = new Psr7Request('POST', 'http://example.com/authenticate', $headers);
$res = $client->sendAsync($request, $options)->wait();
$token = json_decode($res->getbody(),true);
$client = new Client();
$headers = [
'Authorization' => $token,
'Content-Type' => 'application/x-www-form-urlencoded'
];
$options = [
'form_params' => [
'DocNo' => $DocNo
]
];
$request = new Psr7Request('GET', 'http://example/api/SalesOrder/GetSalesOrder/', $headers);
$res = $client->sendAsync($request, $options)->wait();
$data = json_decode($res->getBody(),true);
return view('api.auth.orders.show', compact('data','company'));
}
view (to redirect to show page):
<td class="text-center"></td>
how to redirect the above "a" tag to get the data from API and MySQL from 'DocNo' ('DocNo' is 'job_order_no' in MySQL as i mentioned above in store function)
is there a query that i need to add to show function to get data from database where the DocNo from the API equals DocNo from MySQL?
SOLUTION:
i used query to get the same value from MySQL as showing below:
$jobs = DB::table('jobdetails')->where('job_order_no', $DocNo)->first();
I am trying to update data through sending an http put request to ServiceDesk plus api. When using the console that comes with the system, it works well but when I try to send a request to the same api from Laravel it does not work.
request from the console below
I am trying to send a request to the same url using the code below.
private function openTicket($notification)
{
$data = json_encode(['input_data' => ['request' => ['subject' => $notification->subject,
'description' => $notification->description,
'status' => ['name' => 'Open']]]]);
$request_id = $notification->request_id;
$response = Http::withHeaders([
'technician_key' => 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXX',
'Accept' => 'application/json'
])->put('http://localhost:8082/api/v3/requests/' . $request_id, $data);
dd($response);
}
and im getting an error 400 bad request.
You should not do json_encode, laravel Http module will automatically do it for you. I think your data is json_encoded twice right now.
$data = [
'input_data' => [
'request' => [
'subject' => $notification->subject,
'description' => $notification->description,
'status' => ['name' => 'Open']
]
]
]);
$request_id = $notification->request_id;
$response = Http::withHeaders([
'technician_key' => 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXX',
'Accept' => 'application/json'
])->put('http://localhost:8082/api/v3/requests/' . $request_id, $data);
dd($response);
I just noticed. From the documentation you provided in the screenshot, the input_data nesting level in the array should not exist
$data = [
'request' => [
'subject' => $notification->subject,
'description' => $notification->description,
'status' => ['name' => 'Open']
]
]);
I managed to find a solution and it is as follows,
private function openTicket($notification): bool
{
$data = json_encode(['request' => ['subject' => $notification->subject,
'description' => $notification->description,
'status' => ['name' => 'Open']]]);
$request_id = $notification->request_id;
$response = Http::withHeaders([
'technician_key' => 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX',
'Content-Type' => 'application/x-www-form-urlencoded'
//added asForm() before put
])->asForm()->put('http://localhost:8082/api/v3/requests/' . $request_id, [
'input_data' => $data
]);
if ($response->status() == 200) {
return true;
}
return false;
}
I added asForm() before the put function. This is because asForm() indicates that the request contains form parameters. I also modified the $data object from
$data = json_encode(['input_data' => ['request' => ['subject' => $notification->subject,
'description' => $notification->description,
'status' => ['name' => 'Open']]]]);
to
$data = json_encode(['request' => ['subject' => $notification->subject,
'description' => $notification->description,
'status' => ['name' => 'Open']]]);
Then it worked as i had expected.
I have a simple registration form that the user can register in my app, now I want to send submitted data to another service.
First I test my request using postman as follows using a raw option in a postman panel.
Api url : app3.salesmanago.pl/api/contact/upsert
JSON DATA:
{
"clientId":"w2ncrw06k7ny45umsssc",
"apiKey":"ssssj2q8qp4fbp9qf2b8p49fz",
"requestTime":1327056031488,
"sha":"ba0ddddddb543dcaf5ca82b09e33264fedb509cfb4806c",
"async" : true,
"owner" : "adam#rce.com",
"contact" : {
"email" : "test-1#konri.com",
"name" : "Test",
"address":{
"streetAddress":"Brzyczynska 123",
}
}
}
UPDATE I get the following success result
{
"success": true,
"message": [],
"contactId": "b52910be-9d22-4830-82d5-c9dc788888ba",
"externalId": null
}
Now using guuzle htpp request in laravel
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
$client = new client();
$current_timestamp = Carbon::now()->timestamp;
try {
$request = $client->post('app3.salesmanago.pl/api/contact/upsert', [
\GuzzleHttp\RequestOptions::HEADERS => array(
'debug' => true,
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'clientId' => 's255hncrw06k7ny45umc',
'apiKey' => 'sj2q8rt5qp4fbp9qf2b8p49fz',
'sha' => 'ba0br45543dcaf5ca82b09e33264fedb509cfb4806c',
'requestTime' => $current_timestamp,
'owner' => 'adwamtrw#fere.com',
'http_error' => true
),
\GuzzleHttp\RequestOptions::JSON => [
'form_params' => [
'name' => $data['name'],
'email' => $data['email'],
],
],
]);
}
catch (GuzzleHttp\Exception\ClientException $e) {
$response = $e->getResponse();
$responseBodyAsString = $response->getBody()->getContents();
}
$status = $request->getStatusCode();
$response = $request->getBody();
$r = json_decode($response);
dd($r);
dd($status, $r );
return $user;
}
When I run my app and send the form data I get this using the same data as in postman I get this
{#306 ▼
+"success": false
+"message": array:1 [▼
0 => "Not authenticated"
]
+"contactId": null
+"externalId": null
}
It seems like my API key and other header data are not passed to the header as required,
Can someone tell me what am I doing wrong here?
Maybe something like this. Notice that according to the API some values should be passed as headers (Accept, and Content-Type -commonly used as headers, btw-), and other values as part of the body. This is the case of the authentication values like clientId and apiKey.
I don't have guzzle 6 installed at hand but you can try and modify the code to include that data not in the headers section of the request but in the body:
$request = $client->post('app3.salesmanago.pl/api/contact/upsert', [
\GuzzleHttp\RequestOptions::HEADERS => array(
'debug' => true,
'Accept' => 'application/json',
'Content-Type' => 'application/json',
),
\GuzzleHttp\RequestOptions::JSON => [
'form_params' => [
'name' => $data['name'],
'email' => $data['email'],
'clientId' => 's255hncrw06k7ny45umc',
'apiKey' => 'sj2q8rt5qp4fbp9qf2b8p49fz',
'sha' => 'ba0br45543dcaf5ca82b09e33264fedb509cfb4806c',
'requestTime' => $current_timestamp,
'owner' => 'adwamtrw#fere.com',
'http_error' => true
],
],
]);
I'm not sure about the 'form_params' in under the RequestOptions::JSON, but mabye you can put the values directly under RequestOptions::JSON.
Just FYI, not sure what Laravel you're using but there's now The Laravel HTTP client which make this sooo much easier.
$response = Http::withHeaders([
'Accept' => 'application/json, application/json',
'Content-Type' => 'application/json',
'clientId' => 'dd2ncrw06k7ny45umce',
'apiKey' => 'ddjdd2q8qp4fbp9qf2b8p49fdzd',
'sha' => ' wba0b543dcaf5ca82b09e33264fedb4509cfb4806ec',
"requestTime" => $current_timestamp,
"owner" => "testemail#wp.com",
])->post('app3.salesmanago.pl/api/contact/upsert', [
'name' => $data['name'],
'email' => $data['email'],
]);
if($response->successful()){
dd($response->json())
}else{
// handle yo errors
}
I am using Laravel to call an external API.
This is my Client:
<?php
use GuzzleHttp\Client;
$client = new Client();
$response = $client->request('POST',
'https://example.org/oauth/token', [
'headers' => [
'cache-control' => 'no-cache',
'Content-Type' => 'application/x-www-form-urlencoded',
],
'form_params' => [
'client_id' => '2',
'client_secret' => 'client-secret',
'grant_type' => 'password',
'username' => 'username',
'password' => 'password',
],
]);
$accessToken = json_decode((string)$response->getBody(),
true)['access_token'];
Now I can use this to fetch something:
<?php
$response = $client->request('GET',
'https://example.org/api/items/index', [
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer '.$accessToken,
],
]);
So now I don't want to initiate the client on every method again. So maybe there's a cool/Laravel-like way to provide the $client to the controller on specific routes?
I thought about an app service provider or an middleware, but I'd love to see an example :-)
Perhaps you can use singleton? Wrap your implementation in a class lets say YourHttpClient then in your AppServiceProviders register method add:
$this->app->singleton('YourHttpClient', function ($app) {
return new YourHttpClient();
});
Then you should be able to typehint it in your controller constructors like this
class SomeController {
private $client;
public function __construct(YourHttpClient $client) {
$this->client = $client;
}
}
I have this code for sending parameters for a POST request, which works:
$client = new GuzzleHttp\Client();
$request = $client->createRequest('POST', 'http://example.com/test.php');
$body = $request->getBody();
$request->getBody()->replaceFields([
'name' => 'Bob'
]);
However, when I change POST to PUT, I get this error:
Call to a member function replaceFields() on a non-object
This is because getBody is returning null.
Is it actually correct to send PUT parameters in the body? Or should I do it in the URL?
According to the manual,
The body option is used to control the body of an entity enclosing
request (e.g., PUT, POST, PATCH).
The documented method of put'ing is:
$client = new GuzzleHttp\Client();
$client->put('http://httpbin.org', [
'headers' => ['X-Foo' => 'Bar'],
'body' => [
'field' => 'abc',
'other_field' => '123'
],
'allow_redirects' => false,
'timeout' => 5
]);
Edit
Based on your comment:
You are missing the third parameter of the createRequest function - an array of key/value pairs making up the post or put data:
$request = $client->createRequest('PUT', '/put', ['body' => ['foo' => 'bar']]);
when service ise waiting json raw data
$request = $client->createRequest('PUT', '/yourpath', ['json' => ['key' => 'value']]);
or
$request = $client->createRequest('PUT', '/yourpath', ['body' => ['value']]);
If you're using Guzzle version 6 you can make PUT request this way:
$client = new \GuzzleHttp\Client();
$response = $client->put('http://example.com/book/1', [
'query' => [
'price' => '50',
]
]);
print_r($response->getBody()->getContents());
In Guzzle 6, if you want to pass JSON data to your PUT request then you can achieve it as below:
$aObj = ['name' => 'sdfsd', 'language' => 'En'];
$headers = [
"User-Agent" => AGENT,
"Expect" => "100-continue",
"api-origin" => "LTc",
"Connection" => "Keep-Alive",
"accept" => "application/json",
"Host" => "xyz.com",
"Accept-Encoding"=> " gzip, deflate",
"Cache-Control"=> "no-cache",
"verify" => false,
"Content-Type" => "application/json"
];
$client = new GuzzleHttp\Client([
'auth' => ['testUsername', 'testPassword'],
'timeout' => '10000',
'base_uri' => YOUR_API_URL,
'headers' => $headers
]);
$oResponse = $client->request('PUT', '/user/UpdateUser?format=json', ['body' => json_encode( $aObj, JSON_UNESCAPED_SLASHES)]);
$oUser = json_decode( $oResponse->getBody());