I have set up a Google Connect for my website using a combination of the Google JS API and the Google PHP API.
The entire PHP API consists of 16MB+ of PHP files, tremendously slowing down my local development environment. I want to remove all this bloat and use only the JS API instead, sending it's retrieved values to PHP with AJAX. Is this possible?
My current working code looks like this, but I want to refactor the code to not use the PHP API at all.
jQuery
gapi.load('auth2', function() {
var scopes = [
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile'
];
// Retrieve the singleton for the GoogleAuth library and set up the client.
gapi.auth2.authorize({
'client_id': 'XXXXXXXXXXXXXXXXXX.apps.googleusercontent.com',
'cookie_policy': 'single_host_origin',
'fetch_basic_profile': false,
'ux_mode': 'popup',
'scope': scopes.join(' '),
'prompt': 'select_account'
},
function(googleResponse) {
if ( googleResponse.error ) {
return;
}
var data = {
'action': 'social_connect_google',
'access_token': googleResponse.access_token
}
$.ajax({
url: ajax_url,
type: 'POST',
data: data,
success: function(response) {
if ( response.success === true ) {
console.log(response);
}
}
});
});
});
PHP
/**
* Connect to Google API and login, signup or link accounts.
*
* @since 1.0.0
*
* @return WP_User|NS_Error
*/
public function connect() {
$client = new Google_Client();
$credentials = json_decode('XXXXXXXXX', true);
$client->setAuthConfig($credentials);
// Set Access Token
$client->setAccessToken($_POST['access_token']);
$oauth2 = new Google_Service_Oauth2($client);
if ( !$oauth2 ) {
return new NS_Error('invalid_access_token', 'The access_token was invalid.');
}
$google_user = $this->get_user($oauth2->userinfo->get());
if ( $this->get_user_by_google_id($google_user) ) {
return $this->login($google_user);
} else if ( $this->get_user_by_google_email($google_user) ) {
return $this->link_accounts($google_user);
} else {
return $this->signup($google_user);
}
}
Basically, I need to transfer the OAuth2 part of the PHP code to be done in JavaScript, and then send the retrieved Google User data to PHP, skipping the need for the PHP API.
Can this be done, and is this a valid and secure way to go about things?