Building a custom login for your church website using the API

Posted By: Tracy Mazelin


The Application Programming Interface (API) of Fellowship One provides a way for churches to leverage their own church data within custom built applications. This tutorial is going to outline how you can use our API to build a custom login to your church website by authorizing the user based on their WebLink or InFellowship login credentials. This is a 2nd party application and this post builds upon the foundation laid by Jas Singh here. You will find links to the PHP oAuth library and more detail about 2nd party authorization in his post.

Step 1: Build a login form


First, you will need to build a login form requesting a username and password. If the majority of your church has already converted their WebLink login to an InFellowship login, then you will want to ask for their email address as their username. The authentication is designed to accept either a WebLink or InFellowship username.

Here is an example of the code you would need to use to collect the username and password and also print a login failure message if the credentials submitted do not match what is in your Fellowship One database:

<form action="authenticate.php" method="post">
<?php if(isset($_GET['login']) && $_GET['login'] == "failed")
echo '<span style="color:red">Incorrect Username or Password</span>';?>
<label for="username">Username or Email Address:</label>
<input name="username" type="text" size="20"/>
<label for="password">Password:</label>
<input name="password" type="password" size="20" />
<input type="submit" value="Log In" name="submit" />
<input type="hidden" name="redirect" value="<?php echo $_GET['redirect']?>"/>
<p> <a href="
cCode=[YourChurchCode]" target="_blank">Create Account</a> | <a href=" cCode=[YourChurchCode]">Forgot Password?<br />
</a> </p>

Step 2: Process the submission

Once the user enters login credentials and clicks submit, a form action is required. This is where your church website will need to talk to Fellowship One to see if this user exists and if the credentials are correct. This will be done through the API. As part of the authentication process for accessing protected resources, the API needs the username and password separated by a space and base64 & URL encoded. Below is an example script in PHP for submitting the username and password to the API and collecting key user information for use in your own church website. See comments in the code for explanations:

  //Get these files from the PHP oAuth library
  require_once 'OAuth/AppConfig.php';
  require_once 'OAuth/OAuthClient.php';
  // Create a session
  $results = array();
  //Create an instance of oAuthClient
  $apiConsumer = new OAuthClient(AppConfig::$base_url, AppConfig::$consumer_key, AppConfig::$consumer_secret);
  //Post the username and password collected on the login page to the request to get an access token
if($apiConsumer->getAccessToken2ndParty($_POST['username'],$_POST['password'])) //Get the token and token secret and store them in cookies {
$_SESSION['token'] = $apiConsumer->getToken();
$_SESSION['tokenSecret'] = $apiConsumer->getTokenSecret();
session_destroy(); $_SESSION = array(); //If the tokens are not given, the authentication failed. //The login form reads the redirect url and displays a login failure message header('Location:../login.php?login=failed'); exit();
} //Upon successful authentication, the server will send back a response
//We want to get the person location from the response
$responseHeaders = $apiConsumer->getResponseHeader(); foreach ($responseHeaders as $val) { $start = 'Content-Location:'; $contentLocation = substr( $val, 0, 17 ); if ($contentLocation == $start) { $personLocation = str_replace($start, "", $val); if( $contentLocation == $start ) { $personLocation = str_replace($start, "", $val); $_SESSION['personurl'] = trim($personLocation); } } } } //if no username or password was entered see if there is already a session else if (isset($_SESSION['token'])) { //Initialize the Access Token. $apiConsumer->initAccessToken($_SESSION['token'],$_SESSION['tokenSecret']); } // if no credentials and no existing session redirect to login page else { header("Location:login.php"); exit(); } $url = $_SESSION['personurl'].".json"; //We want to get some fields from the API and store them in cookies for use within our site $person=$apiConsumer->dorequest($url);
$results = json_decode(strstr($person, '{"person":{'), true); $_SESSION['iCode'] = $results['person']['@iCode']; $_SESSION['firstName'] = $results['person']['firstName']; $_SESSION['lastName'] = $results['person']['lastName']; $_SESSION['personID'] = $results['person']['@id'];
//Another call to get address information
$resource = AppConfig::$f1_people_address;
$f1_people_address = str_replace('{personID}', $_SESSION['personID'], $resource);
$url = AppConfig::$base_url.$f1_people_address.".json";
$addresses=json_decode(strstr($addresses, '{"addresses":{"address":[{')); $_SESSION['address1'] = $addresses->addresses->address[0]->address1; $_SESSION['address2'] = $addresses->addresses->address[0]->address2; $_SESSION['address3'] = $addresses->addresses->address[0]->address3; $_SESSION['city'] = $addresses->addresses->address[0]->city; $_SESSION['stProvince'] = $addresses->addresses->address[0]->stProvince; $_SESSION['postalCode'] = $addresses->addresses->address[0]->postalCode;
//Store other commonly used fields here //Take the user to the members area of your website. Put your own path to the members page here header("Location:members.php"); ?>

Step 3: Add this code to your OAuthClient.php file

public function getAccessToken2ndParty($username, $password) {   
    	 curl_setopt( $this->connection, CURLOPT_NOBODY, true );
        //register a callback function which will process the response headers
        curl_setopt($this->connection, CURLOPT_HEADERFUNCTION, array(&$this,'readHeader'));
    	$requestURL =  sprintf( "%s%s", $this->baseUrl, $this->accesstoken_path );
		// SET the username and password
		$requestBody = Util::urlencode_rfc3986(base64_encode( sprintf( "%s %s", $username, $password)));
		$getContentType = array("Accept: application/json",  "Content-type: application/json");
		$requestBody	= $this->postRequest($requestURL, $requestBody , $getContentType,  200);
		preg_match( "~oauth_token\=([^\&]+)\&oauth_token_secret\=([^\&]+)~i", $requestBody, $tokens );
		if( !isset( $tokens[1] ) || !isset( $tokens[2] ) ) {
            return false;

        $this->requestToken = $tokens[1] ;
        $this->tokenSecret = $tokens[2] ;

        return true;

Step 4: Send the logged-in user to a member area

Once authentication is complete and key fields are stored, the script redirects the user to a private area of the church website. You now have key data from the api and can easily make calls to retrieve other resources.

Step 5: Build your own integration applications!

As you can see, the API provides churches with an extra layer of intelligence behind the church website and eliminates the need to store any data in a separate web based database. Single sign on is just the beginning of the functionality afforded to churches. Using the API, it is possible to replace numerous aspects of WebLink/InFellowship with custom built applications which remain consistent with the look and feel of the church website.

Posted In: API, Tips,

No one has commented yet. Be the first!
Commenting is not available in this channel entry.


Previous Posts:

Subscribe to the RSS feed!