Wednesday, June 7, 2017

Google Contact API with Ionic

The code that I used for this is like this:
invitePeersController.getGmailContacts = function(){
    console.log("I come in gmail contacts");
    var clientId = "contact key";
    var apiKey = "apiKey";
    var scopes = "https://www.googleapis.com/auth/contacts.readonly";
    authorize();
    function authorize() {
        gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthorization);
    }
    function handleAuthorization(authorizationResult){
        invitePeersController.gmailContacts = [];
        var gmailData = [];
        if (authorizationResult && !authorizationResult.error){
            var urlContact = "https://www.google.com/m8/feeds/contacts/default/thin?alt=json&access_token=" + authorizationResult.access_token + "&max-results=50000&v=3.0";
            var promiseGoogleData = HttpService.httpGetExternalLink(urlContact);
            promiseGoogleData.then(function (response) {
                var jsonChildData = response.data.feed.entry;
                for(var i=0; i<jsonChildData.length ;i++){
                    var item = {};
                    try{
                        var name = jsonChildData[i].title.$t;
                        var email = jsonChildData[i].gd$email[0].address;

                        if(name.substring(1, name.length-1) && email.substring(1, email.length-1)){
                            item ["name"] = name.substring(1, name.length-1);
                            item ["email"] = email.substring(1, email.length-1);
                            item ["id"] =  email.substring(1, email.length-1).replace(/[^a-zA-Z ]/g, "");
                        invitePeersController.gmailContacts.push(item);
                        gmailData.push(item);
                       }

                    }catch(error){
                        console.log("Error is thrown while trying to read gmail resposne");
                }

            }
            $state.go("app.inviteContacts");
            InvitePeersService.setGmailContactsData( invitePeersController.gmailContacts);

                        return response;
                    })
                    .catch(function (error) {
                        console.log("Something went terribly wrong while trying to get Gmail Data.");
                    });
                }


            }

        }
Also don't forget to add the domain names in the credentials:
enter image description here

No comments:

Post a Comment