Невозможно получить доступ и обновить токен после аутентификации с помощью Google API

Я последовал заэтот удивительный урок чтобы получить доступ и обновить токены, как только пользователь вошел в систему со своей учетной записью Google, но я всегда получаю этот ответ, когда звонюGetAccessCode():

{
   "error": "invalid_request"
}

Вот мой код:

var url = window.location.href;

if (url.indexOf("code=") > 0) { //Once the user signed in with Google
    var code_starts = url.indexOf("code=");
    var code = url.substring((code_starts + 5), url.length);
    alert("Code= " + code);
    GetAccessTokens(code);
} else if (url.indexOf("access_token=") > 0) { //Get the tokens, but I never get this far
    var at_starts = url.indexOf("access_token=");
    var exp_starts = url.indexOf("expires_in=");
    var access_token = url.substring((at_starts + 13), exp_starts);
    alert("AT= " + access_token);

    var rt_starts = url.indexOf("refresh_token=");
    var id_starts = url.indexOf("id_token=");
    var refresh_token = url.substring((rt_starts + 14), id_starts);
    alert("RT= " + refresh_token);
} else {
    GetAccessCode(); //If user opens the page, show him the consent screen
}

function GetAccessCode() {
   window.location = 'https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=https://mywebsite.com/quickstart.html' + '&response_type=code' + '&client_id=' + clientId + '&scope=' + scopes + '&approval_prompt=force' + '&access_type=offline';
}

function GetAccessTokens(code) {
    window.location = 'https://accounts.google.com/o/oauth2/token?code=' + code + '&client_id=' + clientId + '&client_secret=' + clientSecret + '&redirect_uri=https://mywebsite.com/quickstart.html' + '&grant_type=authorization_code';
}

Здесь я получаю ошибку invalid_request.

Я попытался получить токены с помощью ajax-запроса, чтобы не перенаправлять страницу снова (плохой UX):

    var red = 'https://mywebsite.com/quickstart.html';
    var options = {
       url: 'https://accounts.google.com/o/oauth2/token',
       type: "POST",
       dataType: "json",
       data: "code=code&client_id=clientId&client_secret=clientSecret&redirect_uri=red&grant_type=authorization_code",
        complete: function (e) {
            alert(e);
            alert(e.status);
        },
    };
    $.ajax(options);
}

Я тоже пробовал с заголовками:

headers: { "Content-type": "application/x-www-form-urlencoded"},

И я тоже так попробовал:

$.ajax({
    url: "https://accounts.google.com/o/oauth2/token",
    type: "post",
    datatype:"json",
    contentType: "application/x-www-form-urlencoded; charset=utf-8",
    async : true,
    data: {code:code, client_id:clientId, client_secret:clientSecret, redirect_uri:'https://mywebsite.com/quickstart.html', grant_type:'authorization_code'},
    success: function(response){
        alert(response); //I never get this
        var json = $.parseJSON(response);
    } 
})
.fail(function(err) {
    alert("error" + err); //I get [Object object]
});

И еще несколько других вещей. Да, и все параметры имеют правильное значение.

Есть идеи?

Ps:детская площадка показывает, что URL-адрес corrent-токенаhttps://www.googleapis.com/oauth2/v4/token но когда я использую его, я получаюNot found в браузере.

Ответы на вопрос(1)

Ваш ответ на вопрос