Hi,
As a part of the google OAuth process, I’m trying to exchange an authorization code for a refresh token.
When I try the code only in the frontend (in the last example here), it works great, but when i divide it to front and back, the function on the backend returns undefined.
Here’s the code for the frontend part:
import wixLocation from 'wix-location';
import {tokenSwap} from 'backend/tokenswap.jsw';
$w.onReady(function () {
//creating a variable from the url query which has the authorization //code from google.
const code = wixLocation.query.code;
tokenSwap(code)
.then((confirm) => {
console.log(confirm);
})
})
Here’s the code for the backend:
import {fetch} from 'wix-fetch';
export function tokenSwap(authCode) {
//swapping the token using the authcode from the frontend
fetch("https ://oauth2.googleapis .com/token", {
"method": "POST",
"headers": {
"Content-Type": "application/x-www-form-urlencoded"
},
"body": "code=" + authCode + "&grant_type=authorization_code&client_id=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&client_secret=xxxxxxxxxxxxxxxxxxxxxxxxxx&redirect_uri=https ://example.wixsite. com/example/success"
})
//returning the response to the frontend
.then((httpResponse) => {
httpResponse.json()
.then((result) => {
return result.refresh_token;
})
})
}
Here the code that worked perfectly using only the frontend:
import wixLocation from 'wix-location';
import {fetch} from 'wix-fetch';
import wixData from 'wix-data';
$w.onReady(function () {
const code = wixLocation.query.code;
const state = wixLocation.query.state;
fetch("https ://oauth2.googleapis. com/token", {
"method": "POST",
"headers": {
"Content-Type": "application/x-www-form-urlencoded"
},
"body": "code=" + code + "&grant_type=authorization_code&client_id=xxxxxxxxxxxxxxxxxxxxxxxxxxxx&client_secret=xxxxxxxxxxxxx&redirect_uri=https ://example.wixsite. com/example/success"
})
.then((httpResponse) => {
httpResponse.json()
.then ((result) => {
console.log(result.refresh_token);
})
})
})
Why is this happening?
Somebody help?
Thanks!