Create a filter using Gmail API - php

Google released recently a new version of its Gmail API which now makes possible to create filters.
However the documentation is quite limited and I'm facing issues to get it working. I'm using the latest version of their PHP client. Any help would be appreciated to construct the request body.
public $gmail;
public function createFilter($userId) {
try {
$filter = new Google_Service_Gmail_Resource_UsersSettingsFilters();
// Here, we should create the request body...
// https://developers.google.com/gmail/api/v1/reference/users/settings/filters#resource
// $filter->setCriteria() ??
$this->gmail->users_settings_filters->create($userId, $filter);
} catch (Exception $e) {
// Logging errors...
}
}
UPDATE (Working method)
public $gmail;
public function createFilter($userId) {
try {
$filter = new Google_Service_Gmail_Filter([
'criteria' => [
'from' => 'example#gmail.com'
],
'action' => [
'addLabelIds' => ['STARRED']
]
]);
$this->gmail->users_settings_filters->create($userId, $filter);
} catch (Exception $e) {
// Logging errors...
}
}

See https://github.com/google/google-api-php-client#making-requests for guidance on constructing request objects. You should be able to populate the filter properties using native PHP arrays or the autogenerated objects. Example:
$filter = new Google_Service_Gmail_Resource_UsersSettingsFilters([
'criteria' => [
'from' => 'somebody#example.com'
],
'action' => [
'addLabelIds' => ['STARRED']
]
]);

Related

How to retrieve the external api url instead of localhost?

I'm new in laravel and open api, if anyone can understand this question, I do some log to check if the code connect to the external api. How do I get the external api uri instead of the localhost? or does it means that I still cannot get through to the server?
link
Also this is the code that I try to make the log
public function handle(Request $request, Closure $next)
{
$response = $next($request);
if (app()->environment('local')) {
$log = [
'URI' => $request->getUri(),
'HEADER' => $request->header,
'METHOD' => $request->getMethod(),
'REQUEST_BODY' => $request->all(),
'RESPONSE' => $request->getContent(),
];
Log::info(json_encode($log));
}
return $response;
}

Laravel API Validation errors to be displayed

I am valdating the fields sent through api and need to display the errors.
I tried using try and catch no errors thrown. I have already have a code validating the login
try {
$request->validate([
'email' => 'required|string|email',
'password' => 'required|string',
'remember_me' => 'boolean',
]);
} catch (Exception $e) {
return response()->json(['error' => $e->getMessage()], 500);
}
I found no errors return has json instead it is redirecting to the login page
How to handle rerros in API and sent the message as json?None of the example show the way to handle errors. I tried with everything
And also how to handle errors while creating the model
try {
$company = Company::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'country_code' => $data['country_code']]);
} catch (Exception $e) {
return response()->json(['error' => $e->getMessage()], 500);
}
$request->validate() should automatically return a response to the browser with errors if it fails, it doesn't throw an exception.
If your request is json it should detect that and return the error in a json error response, you can catch this in your front-end javascript and interrogate the response to interpret the error message.
e.g. using axios:
this.$axios.post('your api url',{data})
.then(response=>{
// ALL Good
})
.error(error=>{
// Catch returned error and process as required
});
If as you say I found no errors return has json instead it is redirecting to the login page this probably means that Laravel thinks that the request is a standard request, in which case it will issue a response()->back()->withErrors() which is probably what's sending it back to your login.
Try checking the original request type and ensure it's json, it should have a header of Accept: application/json.
Alternatively you can define your own validator
https://laravel.com/docs/7.x/validation#manually-creating-validators, and process the validation on the server as you like.
If there is error into validation then it will automatilly handle by laravel. You don't need to catch exception for that. It doesn't through exception.
Look it sample function which I have used for store Region
public function createRegion(Request $request)
{
$data = $request->all();
// Create a new validator instance.
$request->validate([
'name' => 'required',
'details' => 'required'
]);
try {
$region = new Region();
$region->name = $data['name'];
$region->details = $data['details'];
$region->save();
$content = array(
'success' => true,
'data' => $region,
'message' => trans('messages.region_added')
);
return response($content)->setStatusCode(200);
} catch (\Exception $e) {
$content = array(
'success' => false,
'data' => 'something went wrong.',
'message' => 'There was an error while processing your request: ' .
$e->getMessage()
);
return response($content)->setStatusCode(500);
}
}

Laravel validation Error messages to string

I want to convert laravel validation error array to a comma separated string. This is to use in an api service for an ios application. So that the iOs developer can process error messages easily.
I tried,
$valArr = [];
foreach ($validator->errors() as $key => $value) {
$errStr = $key.' '.$value[0];
array_push($valArr, $errStr);
}
if(!empty($valArr)){
$errStrFinal = implode(',', $valArr);
}
But it is not working.
You should do like this :
$errorString = implode(",",$validator->messages()->all());
P.S. Assuming
$validator = Validator::make($dataToBeChecked,$validationArray,$messageArray)
The $validator->errors() returns a MessageBag,
see: https://laravel.com/api/5.3/Illuminate/Support/MessageBag.html.
You are close, you need to call the getMessages() function on errors(), so:
foreach ($validator->errors()->getMessages() as $key => $value) {
Hope this helps :)
You are not converting validation errors to array.Please use the below function and pass validation errors as parameter.
public function validationErrorsToString($errArray) {
$valArr = array();
foreach ($errArray->toArray() as $key => $value) {
$errStr = $key.' '.$value[0];
array_push($valArr, $errStr);
}
if(!empty($valArr)){
$errStrFinal = implode(',', $valArr);
}
return $errStrFinal;
}
//Function call.
$result = $this->validationErrorsToString($validator->errors());
If you are doing it like me without your validator and you are pulling messages from the exception you can use laravel helper Arr::flatten($array);
Link and code are for laravel 8.x but I tested this with 5.7 ;) It works.
From documentation:
use Illuminate\Support\Arr;
$array = ['name' => 'Joe', 'languages' => ['PHP', 'Ruby']];
$flattened = Arr::flatten($array);
// ['Joe', 'PHP', 'Ruby']
My code:
try {
$request->validate([
'test1' => 'required|integer',
'test2' => 'required|integer',
'test3' => 'required|string',
]);
} catch (ValidationException $validationException) {
return response()->json([
'type' => 'error',
'title' => $validationException->getMessage(),
'messages' => Arr::flatten($validationException->errors())
], $validationException->status);
} catch (\Exception $exception) {
return response()->json([
'type' => 'error',
'title' => $exception->getMessage(),
], $exception->getCode());
}
As you can see I am pulling the message and setting it as my title. Then I am using Arr::flatten($validationException->errors()) to get the validation messages and but to flatten my array for SweetAlert2 on the frontend.
I know I am late but I hope it will help someone that comes across these problems.
Greetings! :)

How to add ContentType to AWS PHP SDK MultiPartUploader

I have searched high and low for how to add a simple ContentType metadata to a MultiPartUploader in AWS PHP SDK. The docs specifically mention how to do it for PutObject, but have no mention of how to do it with a MultiPartUploader.
I have tried every method I could find online, but nothing is working and my file is always getting set to application/octet-stream.
Does anyone have any experience with this? Here is my code:
$uploader = new MultipartUploader($this->s3, $local_path, [
'bucket' => env('AWS_BUCKET'),
'key' => $path .'/'. $filename,
'contentType' => 'video/mp4', // have tried this
'metaData' => [ // have tried this (all well as all variations of caps)
'contentType' => 'video/mp4',
]
]);
do
{
try
{
$result = $uploader->upload();
}
catch (MultipartUploadException $e)
{
$uploader = new MultipartUploader($this->s3, $local_path, [
'state' => $e->getState(),
]);
}
}
while (!isset($result));
After reading through the MultiPartUploader class, it looks like the ContentType should be automatically set, but it is not being set.
I am using v3 of the SDK
Any advice would be greatly appreciated!
I figured it out right after I posted this question! I will post the answer so that if anyone else hits this problem, they can look here.
The page I linked in the question has the answer, just not specifically related to ContentType!
Here is the working code:
$uploader = new \Aws\S3\MultipartUploader($this->s3, $local_path, [
'bucket' => env('AWS_BUCKET'),
'key' => $path .'/'. $filename,
'before_initiate' => function(\Aws\Command $command) use ($mime_type) // HERE IS THE RELEVANT CODE
{
$command['ContentType'] = $mime_type; // video/mp4
}
]);
do
{
try
{
$result = $uploader->upload();
}
catch (\Aws\Exception\MultipartUploadException $e)
{
$uploader = new \Aws\S3\MultipartUploader($this->s3, $local_path, [
'state' => $e->getState(),
]);
}
}
while (!isset($result));
return $result ? $result['ObjectURL'] : null;
I hope this helps someone else in the future!

Getting a weird error when working with Laravel 4 and the php league OAuth2

I'm trying to get a Social login with Facebook in place using Laravel and The league OAuth2 client but I'm getting this error:
Required option not passed: access_token Array ( [{"error":{"message":"Error_validating_client_secret_","type":"OAuthException","code":1}}] => )
I've followed the instructionns in the package github page, but I can't get it to work.
My controller action code:
$facebook = $this->socialRepository->facebookLogin();
$code = \Input::get("code");
if(!isset($code)) {
$authURL = $facebook->getAuthorizationUrl();
return \Redirect::away($authURL);
} else {
$token = $facebook->getAccessToken('authorization_code', ['code' => $code]);
try {
$userDetails = $facebook->getUserDetails($token);
dd($userDetails);
} catch (\Exception $e) {}
}
And the repository code:
public function facebookLogin()
{
return new Facebook(
[
'clientId' => $this->config->get("social.facebook.clientID"),
'clientSecret' => $this->config->get("social.facebook.clientSercret"),
'redirectUri' => $this->config->get("social.facebook.redirectUri"),
'scopes' => $this->config->get("social.facebook.scopes"),
]
);
}
This normally happens when the redirect URL, app ID or secret are incorrect.
For example,
'clientSecret' => $this->config->get("social.facebook.clientSercret"),
Are you you meant social.facebook.clientSercret and not social.facebook.clientSecret (no extra r)

Categories