Php — Twitter Sign-in & Register with Twitter API and the SDK twitter-api-php

Have you a need to add a Twitter Sign-in and register process to your website in Php?
You are not using Wordpress, and then won’t be able to use WP plugins for Twitter ?

TWITTER API V1

Here I will propose a way to do, but note that I use the Twitter API Oauth V1, not the 2.
V1 still working for a long time to come and is not an issue. And it’s somehow simpler to proceed.

SDKS ?

There is multiples Php SDK that are supposed to help for Twitter API, some are listed in Twitter developpers console.
But after longs tests, globally zero of them are able to process a Twitter connect process.
They are built for other API goals.
Some pretend to propse a help for connect but are not working for this purpose.

First you need to install the SDK following, that is working well for this purpose and is very generic = I can put any Twitter APi endpoint in it and get a result.

https://github.com/J7mbo/twitter-api-php
Installing it is detailled in this url, and simple.

SETUP API KEYS

Then of course you need to create a twitter App, and get 4 elements,
'oauth_access_token' => "xxxxxx",
'oauth_access_token_secret' => "xxxxxx",
'consumer_key' => "xxxxxx",
'consumer_secret' => "xxxxxx"

Consumer key and secret being the API KEY and SECRET under the Consumer Key section.
aouth_access_token and secret being below “Access Token and Secret” section.

CREATE 2 PHP PAGES

Then you need to have 2 pages php,
Page 1 that will
get a URL from Twitter via it’s API and your Twitter API keys,
redirect to Twitter Login, where the user will need to login and then accept this app.
Then after Twitter will be redirected to your second page url (defined in Page 1)

Page 2 where you arrive from Twitter redirection, that will
Get tokens sent by Twitter, and use them to call User data.
At the end of this page you can use those user data as you want to register a user and login him in your CMS or system, it’s up to your system

PAGE 1 — CALL THE API TO GHET REDIRECTION URL

Code here, I give some tips lower
NOTE that the code here is built to be inserted in a CLASS. If you don’t use a class, don’t use “public function xxx” but “function xxx” and replace “public $settingTwitter =” by “$settingTwitter =” and “$this->settingTwitter” by “$settingTwitter”

public $settingsTwitter = array(
'oauth_access_token' => "xxxxxx",
'oauth_access_token_secret' => "xxxxxx",
'consumer_key' => "xxxxxx",
'consumer_secret' => "xxxxxx"
);
public function login_twitter()
{
session_start();
$redirect_url = "{{YOUR OWN REDIRECTION URL"; //The page where Twitter will redirect after you login and accepted login with Twitter
$settings = $this->settingsTwitter;
$postfields = array(
'oauth_callback' => rawurlencode($redirect_url)
);
$url = "https://api.twitter.com/oauth/request_token";
$requestMethod = 'POST';
$twitter = new TwitterAPIExchange($settings);
$result = $twitter->buildOauth($url, $requestMethod)
->setPostfields($postfields)
->performRequest();
$result = explode('&', $result);

$request_token = array(
"oauth_token" => explode('=', $result[0])[1],
"oauth_token_secret" => explode('=', $result[1])[1],
"oauth_callback_confirmed" => explode('=', $result[2])[1],
);
if ($request_token["oauth_callback_confirmed"] === "true") {
$redirection_url = 'https://api.twitter.com/oauth/authenticate?oauth_token=' . $request_token["oauth_token"];
//Here, redirect directly to this TwitterURL, or send it back to be processed on Front (for API system)
//Once passed Twitter login, it will redirect to $redirect_url
} else {
//Show error message
}
}

On top you have settingsTwitter
where you need to replace with your own app API keys

and then $redirect_url = "{{YOUR OWN REDIRECTION URL";
where you need to put the url of your second page, where Twitter wil redirect after login
That’s all here

PAGE 2 — Where you are redirected by Twitter, and process call user data

Code here, I give some tips lower

if (isset($_GET['oauth_verifier']) && isset($_GET['oauth_token'])) {

$oauth_token = $_GET['oauth_token'];
$oauth_verifier = $_GET['oauth_verifier'];


$settings = $this->settingsTwitter;

//QUERY ACCESS TOKEN
$postfields = array(
'oauth_verifier' => $oauth_verifier,
'oauth_token' => $oauth_token,
);
$url = 'https://api.twitter.com/oauth/access_token';
$requestMethod = 'POST';
$twitter = new TwitterAPIExchange($settings);
$result = $twitter->buildOauth($url, $requestMethod)
->setPostfields($postfields)
->performRequest();

$result = explode('&', $result);
$response_array = array(
"oauth_token" => explode('=', $result[0])[1],
"oauth_token_secret" => explode('=', $result[1])[1],
"user_id" => explode('=', $result[2])[1],
"screen_name" => explode('=', $result[3])[1],
);

//QUERY USER DATA

$url = 'https://api.twitter.com/1.1/account/verify_credentials.json';

$getfields = "?include_email=true";//&oauth_token=".$response_array["oauth_token"];
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
$result = $twitter->setGetfield($getfields)
->buildOauth($url, $requestMethod)
->performRequest();
$userinfo = json_decode($result);
if (isset($userinfo->email)) {
$user = (object)array(
"email" => $userinfo->email,
"name" => $userinfo->name,
"id" => $userinfo->id,
);
///HERE PROCESS LOGIN USER IN YOUR CMS
exit;
}else {
//HERE WARN ERROR
}
} else {
//HERE WARN ERROR
}

Be sure that this page could also access to the variable $this->settingsTwitter / or / $settingsTwitte (if in CLASS or not)

At the end of the process, see “HERE PROCESS….” where you will have the object “$userinfo” to use to process you login and/or register process in your own system, and redirect your user to a page where he will be logedin..

That’s mainly all needed, it’s working on my side, where I have a mix of custom Php App and a wordpress behind for some users data.
My configuration is in Php 7.4/7.6, it’s probably not working for Php 8

I’m not sure if it could be working for anybody in any cases, of course.
You can comment if it was usefull for you or if you have a specific case not working.
You can also propose others solutions, it would be insteresting.
Please don’t comment something not productive or useless.
I will delete them, it’s not a place for fighting about what should be good or not ,or about supposed coding best practices.

--

--

Blue Origami Digital — Renaud Hamelin

We are a french company focusing on conception / development of Web solutions, Web apps, advanced website, eCommerces. Specialized on Php, and VueJs