pagination is not working properly for Twilio in Laravel - laravel

I am trying to paginate the records for Twilio and after taking the reference from here
I have added the next page and previous page url and its showing successfully but when I am opening the url, its showing the error i.e.
"code": 20003,
"detail": "Your AccountSid or AuthToken was incorrect.",
"message": "Authentication Error - No credentials provided",
"more_info": "https://www.twilio.com/docs/errors/20003",
"status": 401
Here is my code :
public function listcallsapp(Request $request){
$calls = $this->twilio->calls->page([], 50);
$data = [];
$i = 0;
foreach($calls as $call){
$data[$i]['sid'] = $call->sid;
$data[$i]['from'] = $call->from;
$data[$i]['to'] = $call->to;
$data[$i]['direction'] = $call->direction;
$data[$i]['status'] = $call->status;
$data[$i]['duration'] = $call->duration;
$i++;
}
return response()->json([
'message'=>'Call Logs!',
'code'=>200,
'prev' => $calls->getPreviousPageUrl(),
'next' => $calls->getNextPageUrl(),
'data'=>$data,
'status'=>'success'
]);
}
Where I am missing, please help me out. Also, If any other way, please suggest.

Related

how to send api response array in code codeigniter?

I am creating api in codeigniter in which i am checking both email and mobilenumber field for updating & in that check it for both field. my single message is go to response but in both casess how can i send both email and mobile number is exists
if((isset($postData['email'])) && $postData['email']!="")
{
$message["email_unique"]='Email already exists';
return $this->response(array("status" => "400", "message" =>$message), 400);
}
if((isset($postData['mobileNumber'])) && $postData['mobileNumber']!="")
{
$mobilenumber=$postData['mobileNumber'];
$message["mobilenumber_unique"]='Mobile Number already exists';
return $this->response(array("status" => "400", "message" =>$message), 400);
}
Check this code
"400",
"message" =>$message
]);
exit;
} else {
$message['success'] = "Successful"; // success messsage if needed
$data = null; // whatever data you need to pass in success resposne - either fetch from Database or hardcoded
// validated flow
echo json_encode([
"status" => "200",
"message" =>$message,
"data" => $data
]);
}
?>
==================================
Success resposne:
{"status":"200","message":{"success":"Successful"},"data":null}
Failed response:
{"status":"400","message":{"error_email":"Email address required.","error_mobile":"Mobile number required."}}
If email exists and mobile number empty then
Failed response:
{"status":"400","message":{"error_mobile":"Mobile number required."}}

Uploading file to onedrive using microsoft graph api

I am trying to uploading a video file to onedrive using the microsoft graph api with the php sdk implementation in laravel.
Code details as below
// Get the access token from the cache
$tokenCache = new TokenCache();
$accessToken = $tokenCache->getAccessToken();
$file_name = 'new_video.mp4';
$media_path = storage_path('video.mp4');
// Create a Graph client
$graph = new Graph();
$graph->setAccessToken($accessToken);
//create post request
$postData = json_encode([ 'items' =>
[
"#odata.type" => "microsoft.graph.driveItemUploadableProperties",
"#microsoft.graph.conflictBehavior" => "rename",
"name" => $file_name
]
]);
//dd(json_encode($postData));
try {
$post = $graph->createRequest('POST', '/drive/root/:{item-path}:/createUploadSession')->attachBody($postData)->upload($media_path);
} catch (\Illuminate\Http\Client\RequestException $e) {
dd($e);
}
Not sure what should go into the item path too, i tried using the folder name but got error and i also tried excluding the item path but still got an error.
This is the error I am getting
Client error: `POST https://graph.microsoft.com/v1.0/drive/root/createUploadSession` resulted in a `400 Bad Request` response: {
"error": {
"code": "BadRequest",
"message": "Unable to read JSON request payload. Please ensure Content-T (truncated...)
Json Encode of the request data is also as below and I cant figure out the problem...
{"items":
{
"#odata.type":"microsoft.graph.driveItemUploadableProperties",
"#microsoft.graph.conflictBehavior":"rename",
"name":"new_video.mp4"
}
}
According to this example given on msgraph-sdk-php repository you don't need to json_econde your body data. The sdk will do it for you.
So your code should looks like this:
// Get the access token from the cache
$tokenCache = new TokenCache();
$accessToken = $tokenCache->getAccessToken();
$file_name = 'new_video.mp4';
$media_path = storage_path('video.mp4');
// Create a Graph client
$graph = new Graph();
$graph->setAccessToken($accessToken);
//create post request
$postData = [ 'items' =>
[
"#odata.type" => "microsoft.graph.driveItemUploadableProperties",
"#microsoft.graph.conflictBehavior" => "rename",
"name" => $file_name
]
];
try {
$post = $graph->createRequest('POST', '/drive/root/:{item-path}:/createUploadSession')->attachBody($postData)->upload($media_path);
} catch (\Illuminate\Http\Client\RequestException $e) {
dd($e);
}

Error adding new event to google calender Google_Service_Exception (401) { "error": "unauthorized_client", "error_description": "Unauthorized" }

When i try to submit a new event to my google calender in a laravel project I always face this error:
Google_Service_Exception (401)
{ "error": "unauthorized_client", "error_description": "Unauthorized" }
I created new OAuth credentials for calendar api and added it to .env file as shown:
I am also using google+ api so that each user can access his calender to update his events via OAuth 2
I tried to add new OAuth credentials but the problem still persist I also tried to delegate domain-wide authority to my service account by adding client id added to the .env file & scope and authorize them but nothing changed I also waited for 24 hours waiting the changes to take place but also nothing changed
Here is the function am using to create new events:
public function doCreateEvent(Event $evt, Request $request)
{
$this->validate($request, [
'title' => 'required',
'calendar_id' => 'required',
'datetime_start' => 'required|date',
'datetime_end' => 'required|date'
]);
$title = $request->input('title');
$calendar_id = $request->input('calendar_id');
$start = $request->input('datetime_start');
$end = $request->input('datetime_end');
$start_datetime = Carbon::createFromFormat('Y/m/d H:i', $start);
$end_datetime = Carbon::createFromFormat('Y/m/d H:i', $end);
$cal = new \Google_Service_Calendar($this->client);
$event = new \Google_Service_Calendar_Event();
$event->setSummary($title);
$start = new \Google_Service_Calendar_EventDateTime();
$start->setDateTime($start_datetime->toAtomString());
$event->setStart($start);
$end = new \Google_Service_Calendar_EventDateTime();
$end->setDateTime($end_datetime->toAtomString());
$event->setEnd($end);
// Create new conference
$conference = new \Google_Service_Calendar_ConferenceData();
$entryPoint = new \Google_Service_Calendar_EntryPoint();
$entryPoint->setAccessCode('wx12z3s');
$entryPoint->setEntryPointType('video');
$entryPoint->setLabel('meet.google.com/wx12z3s');
$entryPoint->setMeetingCode('wx12z3s');
$entryPoint->setPasscode('wx12z3s');
$entryPoint->setPassword('wx12z3s');
$entryPoint->setPin('wx12z3s');
$entryPoint->setUri('https://meet.google.com/wx12z3s');
$conference->setEntryPoints($entryPoint);
$conferenceSolution = new \Google_Service_Calendar_ConferenceSolution();
$conferenceSolution->setIconUri(null);
$conferenceSolution->setKey(new \Google_Service_Calendar_ConferenceSolutionKey());
$conference->setConferenceSolution($conferenceSolution);
$conferenceRequest = new \Google_Service_Calendar_CreateConferenceRequest();
$conferenceRequest->setRequestId($request->_token);
$conferenceSolutionKey = new \Google_Service_Calendar_ConferenceSolutionKey();
$conferenceSolutionKey->setType("hangoutsMeet");
$conferenceRequest->setConferenceSolutionKey($conferenceSolutionKey);
$conferenceRequest->setStatus(new \Google_Service_Calendar_ConferenceRequestStatus());
$conference->setCreateRequest($conferenceRequest);
$event->setConferenceData($conference);
//attendee
if ($request->has('attendee_name')) {
$attendees = [];
$attendee_names = $request->input('attendee_name');
$attendee_emails = $request->input('attendee_email');
foreach ($attendee_names as $index => $attendee_name) {
$attendee_email = $attendee_emails[$index];
if (!empty($attendee_name) && !empty($attendee_email)) {
$attendee = new \Google_Service_Calendar_EventAttendee();
$attendee->setEmail($attendee_email);
$attendee->setDisplayName($attendee_name);
$attendees[] = $attendee;
}
}
$event->attendees = $attendees;
}
$created_event = $cal->events->insert($calendar_id, $event);
$evt->title = $title;
$evt->calendar_id = $calendar_id;
$evt->event_id = $created_event->id;
$evt->datetime_start = $start_datetime->toDateTimeString();
$evt->datetime_end = $end_datetime->toDateTimeString();
$evt->save();
return redirect('/event/create')
->with('message', [
'type' => 'success',
'text' => 'Event was created!'
]);
}
I am using a G suite account so that I can add events and assign hangout meet conferences to it but the problem keeps showing when i try to add newly created event to the user calender
The problem was the access token I am trying to use to access user calendar is wrong. When I deleted all user data and of course his access token saved to the database and tried to login again so that a new record created to the user with a new access token the problem solved and I can now access his calendar and create new events

Updates records more than one time on laravel

I am trying to update values in laravel. I have a userupdate profile api which I can update the values first time with given parameters and their values but 2nd time when I update same values it gives me user profile does not exist.
My Code is :
public function UpdateUserProfile(Request $request)
{
$id = $request->input('id');
$client_gender = $request->input('client_gender');
$client_age = $request->input('client_age');
$client_weight = $request->input('client_weight');
$client_height = $request->input('client_height');
$client_dob = $request->input('client_dob');
$profile= DB::table('clients')
->where('id',$id)
->update(['client_gender'=>$client_gender,'client_age'=>$client_age,'client_height'=>$client_height,'client_weight'=>$client_weight,'client_dob'=>$client_dob]);
if($profile)
{
$resultArray = ['status' => 'true', 'message' => 'User profile updated Successfully!'];
return Response::json( $resultArray, 200);
}
$resultArray = ['status' => 'false', 'message' => 'User profile does not exist!'];
return Response::json($resultArray, 400);}
first time when I update the value it gives me the response like this:
{
"status": "true",
"message": "User profile updated Successfully!"
}
and when I hit the update request through a postman it gives a 400 Bad request and response is :
{
"status": "false",
"message": "User profile does not exist!"
}
I'd recommend rewriting that function to look like the following; mostly because it reads better and uses the Model methods that are more commonly found in Laravel
public function UpdateUserProfile(Request $request)
{
// this code fails if there is no client with this id
$client = App\Client::findOrFail($request->id);
// attach new values for all of the attributes
$client->client_gender = $request->input('client_gender');
$client->client_age = $request->input('client_age');
$client->client_weight = $request->input('client_weight');
$client->client_height = $request->input('client_height');
$client->client_dob = $request->input('client_dob');
// save
$client->save();
return ['status' => 'true', 'message' => 'User profile updated Successfully!'];
}

Laravel unauthorized page when ajax send request

I'm making web based game. The game need to login first, so I use laravel auth::register and auth::login as usual, and add middleware auth to every pages except login&register page.
Then check the game status using smartupdater if ready or not.
$("section").smartupdater({
url : urlCheckStatus,
data : data,
dataType : 'json',
minTimeout: 2000
}, function(response){
var gameStatus = response.data.status;
if(gameStatus === 'start')
{
gameOn();
}
else if(gameStatus === 'active')
{
pleaseWait();
}
else if(gameStatus === 'stop')
{
backToMenu();
}
});
Register and login function
public function register(Request $request)
{
$name = $request->input('username');
$user = new User;
$user->name = $request->input('username');
$user->email = $name.'#abc.com';
$user->password = bcrypt(Carbon\Carbon::now());
$user->grade = $request->input('grade');
$user->numb = $request->input('numb');
$user->save();
Auth::login($user, true);
return redirect('menu');
}
check game status function
public function checkGameStatus()
{
$game_id = Request::input('game_id');
$data = Game::find($game_id);
return response()->json([
'data' => $data
]);
}
But sometimes I was thrown to login page, because error 401 Unauthorized. Trying to console log like the image above.
Thanks
I see you are using Javascript for authorization with Laravel, as per Laravel documentation for API Authentication with Javascript:
If you are using a different JavaScript framework, you should make
sure it is configured to send the X-CSRF-TOKEN and X-Requested-With
headers with every outgoing request.
Can you ensure X-CSRF-TOKEN and X-Requested-With are always present in your headers.

Resources