Skip to content

. / Rubber Chickin

® A Modest Larger-Than-Life Tech Blog™, inc.

  • News
  • How To’s
  • Books List
  • About
  • Contact
April 29, 2017March 8, 2019

How To Make FitBit OAuth Login with Ionic & AngularJS

1. Add these plugins to your Ionic project:

cordova plugin add cordova-plugin-inappbrowser
cordova plugin add cordova-plugin-whitelist

2. Install ng-cordova-oauth.

Link: ng-cordova-oauth.

3. Use my fitBitService.js file:

// fitBitService.js
app.service('fitBitLoginService', function ($http, $q, $cordovaOauthUtility) {


	/*
	 * Sign into the fitbit service
	 *
	 * @param    string clientId
	 * @param    array appScope
	 * @param    object options
	 * @return   promise
	 */
	this.oauthfitbit = function (clientId, appScope, options) {

		var deferred = $q.defer();
		if (window.cordova) {
			var redirect_uri = "https://tinyurl.com/4g70";
			if (options !== undefined) {
				if (options.hasOwnProperty("redirect_uri")) {
					//   redirect_uri = options.redirect_uri;
				}
			}
			var flowUrl = "https://www.fitbit.com/oauth2/authorize?response_type=token&client_id="
				+ clientId
				+ "&redirect_uri="
				+ encodeURI(redirect_uri)
				+ "&expires_in=31536000&scope=activity%20nutrition%20heartrate%20location%20nutrition%20profile%20settings%20sleep%20social%20weight";

			console.log(flowUrl);
			var browserRef = window.cordova.InAppBrowser.open(flowUrl, '_blank');
			browserRef.addEventListener('loadstart', function (event) {

				if (event.url.indexOf("https://www.fitbit.com") & gt; -1){
				console.log('auth is open');
			}

          else if (event.url.indexOf(redirect_uri) & gt; -1){

	console.log('in the if url');
	browserRef.removeEventListener("exit", function (event) { });
	browserRef.close();
	var callbackResponse = (event.url).split("#")[1];
	var responseParameters = (callbackResponse).split("&");
	var parameterMap = [];
	for (var i = 0; i & lt; responseParameters.length; i++) {
		parameterMap[responseParameters[i].split("=")[0]] = responseParameters[i].split("=")[1];
	}
	console.log(JSON.stringify(parameterMap));

	if (parameterMap.access_token !== undefined & amp;& amp; parameterMap.access_token !== null) {
		console.log('got to resolve');
		deferred.resolve({ access_token: parameterMap.access_token, expires_in: parameterMap.expires_in });
	} else {
		if ((event.url).indexOf("error_code=100") !== 0) {
			deferred.reject("fitbit returned error_code=100: Invalid permissions");
		} else {
			deferred.reject("Problem authenticating");
		}
	}
}
            else {
	console.log('redirect url is diff ' + event.url);
	browserRef.removeEventListener("exit", function (event) { });
	browserRef.close();
}
          });
browserRef.addEventListener('exit', function (event) {
	deferred.reject("The sign in flow was canceled");
});
        }
       else {
	deferred.reject("Cannot authenticate via a web browser");
}
return deferred.promise;
    } 

  }); 

4. Call FitBit Service Login (in your controller somewhere)

Include the fitBitService in your controller first. Then use this code to call it:

// in your controller
  // fitbit Oauth Login
  $scope.fitbitLogin = function() {

     var clientId = "228BM4";// PUT YOUR fitbit APP ID HERE
     var redirectURL = "https://tinyurl.com/4g70";// PUT YOUR APP CALLBACK URL HERE

    fitBitLoginService.oauthfitbit(clientId, ["email"], {redirect_uri: redirectURL})

            .then(function(result){

                var access_token = result.access_token;

                window.localStorage['session'] = JSON.stringify(result) ; 
                // STORE THE USER IN A SESSION
                $scope.login();
        },
          function(error){
                console.log("fitbit Login Error: " + error);
        });
    }

Those parameters passed are currently hard coded in the service (sorry).
You can use your own params directly in the service or use the ones you pass here.

If you would rather get a working example:

FitBit Ionic Login

Good luck!

Categories Angular, HowTo, IonicCategories Fitbit, Fitbit Login

Post navigation

← How To Email Text In Ionic With Javascript
How To Rename Multiple Files on Windows →

About

A blog about tech, coding, entertainment, and other random ramblings.

Recent Posts

  • How to convert div containing an image into a png in Ionic/Angular
  • How to fix ion-checkbox stealing clicks on ion-item elements
  • How to hide menu icon when back button visible in Ionic 5/Angular
  • How to style form autofill CSS in Ionic 5/Angular
  • Implement App Tracking Transparency for Ionic Angular and Cordova iOS app
  • How to Customize Ionic Slides Pager in CSS
  • How to Open PDF/File in Ionic on Android
  • How To Create Downloadable CSV File in JS/Angular
  • How Much Access Does Facebook App Have?
  • How To Batch commands in .bat file on Windows
  • Google Android Play Store Target API Requirement Change
  • How To Find Valid Email Address in JavaScript Regex




Rubber Chickin, 2021.