Fellowship One RESTful API is a REST based web application that uses several open protocols and patterns to provide consumers access to secure resources. STANDARDS, PROTOCOLS, and PATTERNS - nothing else. As developers we see where there is major value in sticking with something that is "tried and true." If we could use web based patterns and protocols for a web based API we could not only get instant adoption but gain the efficiencies and effectiveness of technologies that "just work."   

Enjoy all of the features and benefits of being part of the Fellowship One developer community.
• Engage others in the developer community
• Get access to loads of code to use and learn from
• Create / Share applications that consume the Fellowship One REST API

Since we are community focused, we wanted you to have as much code and information that you'd need to get jump started for the REST API so that you'll be able to discuss / communicate your ideas on consuming the REST API throughout the social-sphere. Please take a moment to check out the current code libraries and blogs.

Building a custom login for your church website using the API

Posted By: Tracy Mazelin on November 29, 2011

Background

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

image

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">
<p>
<?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"/>
</p>
<p>
<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>
<p> <a href="https://integration.fellowshipone.com/integration/Conversion/Create.aspx?
cCode=[YourChurchCode]" target="_blank">Create Account</a> | <a href="https://integration.fellowshipone.com/integration/loginhelp.aspx? cCode=[YourChurchCode]">Forgot Password?<br />
</a> </p>
</form>

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:

<?php
  //Get these files from the PHP oAuth library
  require_once 'OAuth/AppConfig.php';
  require_once 'OAuth/OAuthClient.php';
  // Create a session
  session_start();
  $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(isset($_POST["submit"]))
{
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();
}
else
{
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=$apiConsumer->dorequest($url);
$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 for integrating with web based features of Fellowship One.  Those features include a profile editor, online giving, event registrations and volunteer opportunities. If all event registrations are placed together in an aggregate form within Fellowship One, this method provides a one-stop place for any integration between your church website and Fellowship One:

image

Step 5: Launch WebLink sessions tied to the logged-in user

At the time of this writing, WebLink is still the method used for accessing each of the above resources and since the script collected key fields via the API, a unique individual code has been collected - the icode. This icode can be concatenated to each URL to access each resource like this:

<a href="https://integration.fellowshipone.com/integration/contribution/onlinecontribution.aspx?flo=true&iCode=<?php echo $_SESSION['iCode'];?>&cCode=[YourChurchCode]" target="_blank"></a>

Step 6: 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 with custom built applications which remain consistent with the look and feel of the church website.

Posted In:
Comments:  Comments