Building Your Startup With PHP: Simplifying Onramp With OAuth

Final product image
What You'll Be Creating

This tutorial is part of the Building Your Startup With PHP series on Envato Tuts+. In this series, I'm guiding you through launching a startup from concept to reality using my Meeting Planner app as a real-life example. Every step along the way, I'll release the Meeting Planner code as open-source examples you can learn from. I'll also address startup-related business issues as they arise.

In this tutorial, I'll guide you through implementing OAuth integration with common social networks to make signing up and repeated usage easier and more efficient. I'll explore Facebook, Google, Twitter and LinkedIn, the networks I see as being most appropriate to Meeting Planner's target users. 

All of the code for Meeting Planner is written in the Yii2 Framework for PHP. If you'd like to learn more about Yii2, check out our parallel series Programming With Yii2 at Envato Tuts+.

If you haven't tried out Meeting Planner yet, try scheduling your first meeting now. It's really beginning to come together this year. Ultimately, I was able to use Yii2's built-in AuthClient support to provide sign-in from all of the networks above—so you can use these to register now.

Feedback is welcome. If you have a question or topic suggestion, please post a comment below. You can also reach me on Twitter @reifman.

What Is AuthClient?

AuthClient is Yii's built-in support for your applications to authenticate via third-party services with OpenIDOAuth, or OAuth2

If you followed my Yii2 series in June 2015, you'd have seen me using AuthClient to integrate with Google via OpenID, but the company ended its support for the specification shortly afterwards. Then, in December, I wrote a tutorial which used the Yii2-User extension to add Google OAuth support—the Yii2 Framework didn't yet have this. However, Yii2-User doesn't integrate well with established codebases that already have a user-oriented codebase. But luckily, the Yii2 Framework had since added support for Google OAuth, and everything has become more straightforward. 

In this tutorial, I'll guide you through using the new AuthClient functionality to integrate with a variety of popular social networks. Out of the box, Yii provides support for the following clients:

Another motivation for supporting connection to Meeting Planner via social networks is that it allows people to show up and easily share their name and email with us. With email and password registration, we don't actually ever learn their name. However, Twitter, unlike other social networks, creates significantly problematic barriers to obtaining users' email addresses, which ultimately led me to disable it for now.

Let's get started with the code integration.

Installing AuthClient in Our Application

First, we need to install the Yii components for OAuth, Yii's AuthClient.

Add AuthClient to Composer

Let's add the AuthClient library to composer.json:

Then, we need to update composer:

Configuring AuthClient Support

And, we need to add the AuthClient configuration settings to our configuration file in \frontend\config\main.php.

Add array elements for all of the third-party services that you wish to support (details for each can be found in the AuthClient Guide): 

In order to obtain codes for all those keys and secrets, you need to register your application with each social network. This can often be time consuming.

Registering Developer Applications

Follow along as I walk you through signing up with some of the networks and some of the deeper configuration aspects with others.

Registering With Twitter

Create a new Twitter application at the Twitter Application Dashboard:

Building Your Startup OAuth - Create App

Click Create New App—I found that the callback URL was unnecessary, but for now I used the placeholder

Building Your Startup OAuth - Twitter Dev App Details

Here's the new page for our application:

Building Your Startup OAuth - Twitter App Page

Here's the Settings page:

Building Your Startup OAuth - Twitter Dev App Settings

Here's the Keys and Access Tokens page. Here, we need to copy the Consumer Key (API Key) and Consumer Secret (API Secret):

Building Your Startup OAuth - Twitter Dev App Keys and Tokens

Those keys go in our mp.ini file, which is read into the $config variable above to configure AuthClient for Twitter.

Register our Facebook Application

Next, let's visit the Facebook developer console and Add a New App:

Building Your Startup OAuth - Facebook Dev Console

We'll choose to create a WWW Website app for now:

Building Your Startup OAuth - Facebook Dev Console Add an App

Provide the name of our application:

Building Your Startup OAuth - Facebook Dev Console Generate App ID

And collect our new App ID:

Building Your Startup OAuth - Facebook Dev Console Create an App Dialogs

They ask for all the regular information, such as URLs:

Building Your Startup OAuth - Facebook Dev Console App Webpage URL

And then you can find our Meeting Planner app in the list:

Building Your Startup OAuth - Facebook Dev Console with Apps Listed

Here's the Facebook dashboard for your application:

Building Your Startup OAuth - Facebook Dev Console Finished App Page

Register With Google

Google APIs are a bit more complex than Twitter and Facebook, so the UX is a little harder to follow. But basically, once you create an application, you need OAuth 2.0 keys, which you get by opening the application area on the credentials screen:

Building Your Startup OAuth - Google Dev App Credentials

That takes you here:

Building Your Startup OAuth - Google Dev App Keys and redirect URLs

For security reasons, Google (and LinkedIn) require a full list of exactly which URL paths and parameters might be used during an OAuth sequence. While in development, this can require a lot of adjusting—even for testing from localhost.

Once you've entered them, you'll see them listed below:

Building Your Startup OAuth - Google Dev App All Those URLs

Google does a nice job of helping you configure the consent screen which your users will see when they try to sign up or link their Google account to Meeting Planner:

Building Your Startup OAuth - Google Dev App Credentials Preview

Register With LinkedIn

LinkedIn is fairly simple compared to Google. You require the basic details for your application:

Building Your Startup OAuth - LinkedIn Dev App Settings

Like Google, they require all the URLs you'll be using in development and production. You can also obtain the keys on this page:

Building Your Startup OAuth - LinkedIn Dev Keys and Redirect URLs again

Placing Keys in Our Configuration File

In Protecting Your Keys From GitHub, I described in detail how I use a configuration file to store all of my keys apart from my GitHub repository. Then, I include this file at the beginning of my Yii configuration files. This keeps me from accidentally checking in my keys to my repository and compromising my accounts. 

We place both the Twitter and Facebook Application keys and secrets into /var/secure/mp.ini outside the repository:

Here again is the code in \frontend\config\main.php which includes these settings and sets the individual configuration variables:

Updating the Schema to Store Session Keys

Now that we're ready to write code to integrate social signup and login, we need the database to create an Auth table which will store the social service, its ID for the person, and the user_id for that person in Meeting Planner:

Here's what the migration looks like:

Here's the result when we run it:

Once again, I used Yii's code generator Gii to create the Auth model:

Building Your Startup OAuth - Yiis Gii Model Generator of Auth Model

Ultimately, the Auth table will hold contents like this:

Building Your Startup OAuth - Database view of Auth table

Add the AuthChoice Widget to Meeting Planner

Yii2's AuthChoice widget does an excellent job of implementing the login buttons for each service you configure. And it does so in the order in which you set up the array of services and keys (so you can change it).

It's pretty simple to add the widget to our forms at login.php and signup.php:

Here's our signup page now:

Building Your Startup OAuth - The New Login Screen with AuthChoice Widget Buttons to Social Networks

For existing users who are logged in, I created an easy way for them to link their account. It's called Link Social Accounts on the profile settings page:

Building Your Startup OAuth - New Link Social Accounts

If you click LinkedIn, here's their OAuth screen which will ask you to give permission to Meeting Planner: 

Building Your Startup OAuth - LinkedIn Permissions Page

And here is the screen for Google:

Building Your Startup OAuth - Google Permissions Page

But what's really happening when the user allows us to share their social account details? Let's go through the code I've written to process the users' actions.

Processing the OAuth Permission

The \frontend\controllers\SiteController.php processes the incoming auth action to the function onAuthSuccess:

Most good OAuth clients provide similar information in a similar property array, except Twitter. Twitter was late to the game of sharing email addresses, and for my MVP it's not going to be worth the extra work to configure it now. Google and Facebook are so much more prevalent.

First, I'm gathering the service details and collecting as much personal data as I can: email, first and last name, full name, and especially the external ID of that user at that social network:

In the last lines of code above, we search in the Auth table for the person's external ID. If they don't exist, they are new to Meeting Planner. If they exist, then we recognize them.

Similarly, we need to check if their email address already exists, because it's possible the person with that email address previously registered with Meeting Planner.

When there is no current authenticated user at, the code below looks into the incoming user data. 

If the external ID is already in our Auth table, we log them in. That was easy (for them)!

If we don't recognize the ID but we have registered the email address already, we ask them to log in via user name and password and then link their account.

Building Your Startup OAuth - Error Msg for We have Your Email Previously

Next, if they started on the login page when they clicked the social account button and we don't recognize the external ID or the email address, we redirect them to the signup page and ask them to try again—from the registration page.

If they linked from the signup page, we ensure the new user is not risking a duplicate username (of a pre-existing Meeting Planner user). In this scenario, we just extend the username with a random string for now. And we register them as a new user at Meeting Planner with a password (which they won't really need).

In the final steps above, we add their external social account details to the Auth table for future recognition.

Linking Existing Meeting Planner Accounts

If they are coming from the Link Social Accounts tab on the user profile page (instead of our login or signup page), then we just need to add their external account details to Auth, and move their login to User::STATUS_ACTIVE. (Remember, users that arrive from Meeting Planner invitation links but never registered have a User::STATUS_PASSIVE mode.)

Here's what that looks like (in the future I'll fill in the naming information from the OAuth information—it's not done yet):

Building Your Startup OAuth - Successful Account Linkage

In Closing

I have to admit, the impact of working OAuth connections to major services such as Google, Facebook and LinkedIn is pretty dramatic. It makes signing up and regularly using Meeting Planner so easy and speeds future authentication. It really is kind of incredible.

Meeting Planner has really come together the last couple of months. Please try out the social login and registration right now! Watch for upcoming tutorials in our Building Your Startup With PHP series—there are lots of fun features coming up as the product heads towards MVP.

I'm also beginning to experiment with WeFunder based on the implementation of the SEC's new crowdfunding rules. Please consider following our profile. I may write about this more as part of our series.

Please feel free add your questions and comments below; I generally participate in the discussions. You can also reach me on Twitter @reifman. I welcome feature and topic requests.

If you'd like to know when the next Yii2 tutorial arrives, follow me @reifman on Twitter or check my instructor page. My instructor page will include all the articles from this series as soon as they are published. 

Related Links



Related Articles