Missing argument 1 for App\Http\Controllers\CustomerController::postOptOut() - php

I'm looking for some advice as to how I might clean up these two methods and resolve this error? Right now, the getOptOut() is making a GET request to the API to obtain an email_token and returning the view and postOptOut() is making a POST request, with the email_token from the GET, and allowing a "customer" to opt out of the mailing list and then redirecting to customer home.
public function getOptOut(EmailOptingRequest $request)
{
$customer = Customer::find(Auth::id());
$email = $customer['attributes']['Email'];
$token = "9asdfj48asdj48adja4r8";
$client = new Client();
$res = $client->request('GET',
'https://www.example.com/api/Services/Email/Opting', [
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer ' . $token
],
'email' => $email,
'http_errors' => false // add this to return errors in json
]);
$emailToken = json_decode($res->getBody()->getContents(), true);
$this->postOptOut($emailToken);
return view('customer.email-opting', array(
'customer' => $customer,
'email' => $email,
'token' => $token,
'client' => $client,
'res' => $res,
'emailToken' => $emailToken
));
}
public function postOptOut($emailToken)
{
$customer = Customer::find(Auth::id());
$email_token = $emailToken[0]['token'];
$client = new Client();
$res = $client->request('POST', 'https://www.example.com/api/Services/Email/Opting', [
'email_token' => $email_token,
'category' => 'promotional',
'status' => false
]);
return view('customer.show', array(
'customer' => $customer,
'email_token' => $email_token,
'client' => $client,
'res' => $res ))
->with('success', 'You were removed from our mailing list.');
}
And my routes:
Route::get( 'customer/email-opting', 'CustomerController#getOptOut');
Route::post( 'customer/post-opt-out', 'CustomerController#postOptOut');
The hard coded token is temporary. I'm running into issues with the timing of the GET and POST calls and when the views are returning. Thanks!

public function postOptOut(Request $request)
{
$customer = Customer::find(Auth::id());
$email_token = $request->emailToken[0]['token']; // this way you will get token
$client = new Client();
$res = $client->request('POST', 'https://www.example.com/api/Services/Email/Opting', [
'email_token' => $email_token,
'category' => 'promotional',
'status' => false
]);
return view('customer.show', array(
'customer' => $customer,
'email_token' => $email_token,
'client' => $client,
'res' => $res ))
->with('success', 'You were removed from our mailing list.');
}
Try this

Related

How to display data from API and Database in the same page in laravel?

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();

How to update woocommerce product via api with Symfony and Guzzle

Question: How to update the price of a woocommerce product via API using Guzzle and guzzle/oauth-subscriber
I've used This Question as my reference to get oauth1 working for requesting data, which works well. Just haven't been able to workout out to send post variables.
Most tutorials and the guzzle docs use the $client->request('GET', 'http://httpbin.org', [ 'query' => ['foo' => 'bar'] ]); but that isn't working either:
$response = $client->request('POST', $endpoint, [
'auth' => 'oauth',
'form_params' => [
'price' => '21'
]
]);
This is my current code, with the get $client->get() commented out what successfully returns a product.
$endpoint = 'products/12';
$handler = new \GuzzleHttp\Handler\CurlHandler();
$stack = \GuzzleHttp\HandlerStack::create($handler);
$middleware = new \GuzzleHttp\Subscriber\Oauth\Oauth1([
'consumer_key' => $this->consumer_key,
'consumer_secret' => $this->consumer_secret,
'token_secret' => '',
'token' => '',
'request_method' => Oauth1::REQUEST_METHOD_QUERY,
'signature_method' => Oauth1::SIGNATURE_METHOD_HMAC
]);
$stack->push($middleware);
$client = new \GuzzleHttp\Client([
'base_uri' => $this->url . $this->api,
'handler' => $stack
]);
$response = $client->post( $endpoint, [ 'auth' => 'oauth' ], ['price' => '21'] );
var_dump($response);
//$response = $client->get( $endpoint, [ 'auth' => 'oauth' ] );
//return array(
// 'status' => $response->getStatusCode(),
// 'header' => $response->getHeaderLine('content-type'),
// 'body' => json_decode($response->getBody())
//);
There were three issues with my code:
Using POST to update, not PUT. As stated POST is to create, not update.
Reading Woocommerce docs I found that 'price' is read only, so no combination of parameters I was trying were going to work. regular_price is the correct parameter to use here.
None of the options I was passing to $client-> were working, it needs to be a query string. Which I appended to the $endpoint variable.
$endpoint .= "?stock_quantity=456";
$response = $client->put( $endpoint, [ 'auth' => 'oauth' ] );

How do i send a PUT request in Laravel

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.

How do I pass apikey and other keys to header in guzzle 6.3?

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
}

Bearer Token in Guzzle HTTP 6.1 not working

I have a problem with my Bearer-Authorization in Guzzle-HTTP.
I use it to test my PHP-REST-API with PHPUnit.
here is my test method:
public function testGetMe()
{
$client = new Client([
'base_uri' => $this->apiBaseURL
]);
$data = ['email' => $email, 'password' => '12345'];
$client->post('register', [
'form_params' => $data]
);
$responseJson = json_decode($response->getBody());
$myToken = $responseJson->data->token;
$response = $client->request('GET', 'users', [
'headers' => [
'Authorization' => 'Bearer '.$myToken
],
'debug' => true
]);
}
But if I set the token hard coded like this:
public function testGetMe()
{
$client = new Client([
'base_uri' => $this->apiBaseURL
]);
$data = ['email' => $email, 'password' => '12345'];
$client->post('register', [
'form_params' => $data]
);
$responseJson = json_decode($response->getBody());
$myToken = eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpYXQiOjE0NjQ5NzExMzQsImp0aSI6IjByR3FpOW15Rm1rRGo2TU9sMVhkK3dRU3p1V0pWejM1UEhiU2dTMmg5SEU9IiwiaXNzIjoiQXBwTmFtZSIsIm5iZiI6MTQ2NDk3MTE0NCwiZXhwIjoxNDY0OTczMTQ0LCJzdWIiOiJ0ZXN0QG1haWwuZGUifQ.yA4a_S6ILCeqENm00H712g9uF5g9eSz_BmnaMDdZ2r4p5e1q88g0T09IG2WKCi1oExoBfQ8VTmKeX6ZQv0RydQ;
$response = $client->request('GET', 'users', [
'headers' => [
'Authorization' => 'Bearer '.$myToken
],
'debug' => true
]);
}
and also with Postman, it is working.
It's the same token which I receive from my REST-API.
Do you have any ideas what's wrong?

Categories