Facebook

Wednesday, September 9, 2015

Complete script for login with google and fetch details of users

Complete script for login with google and fetch details of users

HTML
<a id="customBtn" class="gmail_a"> 
    <img src="<?php echo ROOT_URL_BASE;?>image/google.png" /></a>
</a>

Javascript

var googleUser = {};
//Replace with your google client id
var clientId = 'xx-xx.apps.googleusercontent.com';
var startApp = function() {
    gapi.load('auth2', function(){
        //Retrieve the singleton for the GoogleAuth library
        // and set up the client.
        auth2 = gapi.auth2.init({
            client_id: clientId,
            cookiepolicy: 'single_host_origin',
            // Request scopes
            scope: 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email'
        });
        attachSignin(document.getElementById('customBtn'));
    });
};

function attachSignin(element) {
    console.log(element.id);
    auth2.attachClickHandler(element, {}, function(googleUser) {
        gapi.client.load('plus', 'v1', signedIn);
    }, function(error) {
        alert(JSON.stringify(error, undefined, 2));
    });
}

function signedIn(){
    gapi.client.plus.people.get({userId: 'me'}).execute(function(resp){
        handleEmailResponse(resp);
    })
}

function handleEmailResponse(resp) {
    var primaryEmail;
    for (var i=0; i < resp.emails.length; i++) {
        if (resp.emails[i].type === 'account') 
            primaryEmail = resp.emails[i].value;
    }
    parseGoogleUserDetails(resp);
}

function parseGoogleUserDetails(GoogleResponse) {
    console.log(GoogleResponse);
    //The response contains many information of users
    var primaryEmail;
    for (var i=0; i < GoogleResponse.emails.length; i++) {
        if (GoogleResponse.emails[i].type === 'account') 
        primaryEmail = GoogleResponse.emails[i].value;
    }
    var first_name = GoogleResponse.name.givenName;
    var last_name = GoogleResponse.name.familyName;
    var gender;
    if (typeof GoogleResponse.gender != 'undefined') {
        gender = capitalizeFirstLetter(GoogleResponse.gender)
    }
    var city;
    if (GoogleResponse.placesLived.length > 0 )
    for (var i=0; i < GoogleResponse.placesLived.length; i++) {
        if (typeof GoogleResponse.placesLived[i].primary){
            if (GoogleResponse.placesLived[i].primary === true) 
                city = GoogleResponse.placesLived[i].value;
        }
    }
    var formData = {
        'socialMedia': 'google',
        'socialMediaId' : GoogleResponse.id,
        'email' : primaryEmail,
        'first_name' : first_name,
        'last_name' : last_name,
        'gender' : gender,
        'city' : city
    };
    createSocialAccount(formData)
}

No comments:

Post a Comment