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?

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.

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:

That takes you here:

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:

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:

Register With LinkedIn

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

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

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:

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:

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:

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 MeetingPlanner.io, 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.

if (Yii::$app->user->isGuest) {
if ($auth) {
// if the user_id associated with this oauth login is registered, try to log them in
$user_id = $auth->user_id;
$person = new \common\models\User;
$identity = $person->findIdentity($user_id);
Yii::$app->user->login($identity);
} else {
// it's a new oauth id
// first check if we know the email address
if (isset($email) && User::find()->where(['email' => $email])->exists()) {
// the email is already registered, ask person to link accounts after logging in
Yii::$app->getSession()->setFlash('error', [
Yii::t('frontend', "The email in this {client} account is already registered. Please login using your username and password first, then link to this account in your profile settings.", ['client' => $serviceTitle]),
]);
$this->redirect(['login']);
} else {
if ($mode == 'login') {
// they were trying to login with an unconnected account - ask them to login normally and link after
Yii::$app->getSession()->setFlash('error', [
Yii::t('frontend', "We don't recognize the user with this email from {client}. If you wish to sign up, try again below. If you wish to link {client} to your Meeting Planner account, login first with your username and password. Then visit your profile settings.", ['client' => $serviceTitle]),
]);
$this->redirect(['signup']);
}

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 Authtable 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):

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.

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.