Ошибка добавления нового события в календарь Google Google_Service_Exception (401) {"error": "unauthorized_client", "error_description": "Unauthorized"} - PullRequest
0 голосов
/ 26 июня 2019

Когда я пытаюсь отправить новое событие в свой календарь Google в проекте laravel, я всегда сталкиваюсь с этой ошибкой:

Google_Service_Exception (401) {"error": "unauthorized_client", "error_description": "Unauthorized"}

Я создал новые учетные данные OAuth для календаря API и добавил их в файл .env, как показано:

.env

Я также использую google + api, чтобы каждый пользователь мог получить доступ к своему календарю для обновления своих событий через OAuth 2

Я пытался добавить новые учетные данные OAuth, но проблема все еще не устранена. Я также попытался делегировать общедоменные полномочия моей учетной записи службы, добавив идентификатор клиента, добавленный в файл и область действия .env, и авторизовав их, но ничего не изменилось. Я также ждал 24 часа в ожидании изменений, но также ничего не изменилось

Вот функция, которую я использую для создания новых событий:

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!'
                ]);
}

Я использую учетную запись G Suite, чтобы я мог добавлять в нее события и назначать ей видеовстречи, но проблема продолжает появляться, когда я пытаюсь добавить вновь созданное событие в пользовательский календарь

1 Ответ

0 голосов
/ 04 июля 2019

Проблема в том, что маркер доступа, который я пытаюсь использовать для доступа к календарю пользователя, неверен.Когда я удалил все пользовательские данные и, конечно, его токен доступа, сохраненный в базе данных, и попытался снова войти в систему, чтобы создать новую запись для пользователя с новым токеном доступа, проблема была решена, и теперь я могу получить доступ к его календарю и создавать новые события

...