Sample PHP Project with OAuth

<?php
/**
 * @author Jacob Edmond Kerr
 * @date 10-26-2017
 */

require 'infusionsoft/vendor/autoload.php';

class infusionsoft {
	public $db;
	public $errors;
	public $notifications;
	public $table = 'infusionsoft';
	protected $accessToken;
	protected $client;
	public function __construct(){
		global $db;
		$this->db = $db;
		$this->trace = true;
		$this->errors = new errors();
		$this->errors->trace = $this->trace;
        $this->notifications = new notifications();
		$this->notifications->trace = $this->trace;
		$this->refreshToken = "";
		$this->clientID = "";
		$this->clientSecret = "";
		$this->client = $infusionsoft = new \Infusionsoft\Infusionsoft(array(
			'clientId'     => $this->clientID,
			'clientSecret' => $this->clientSecret,
			'redirectUri'  => 'https://www.website.com/infusionsoft/saveauthentication.php',
		));
	}
	
	public function __destruct(){
        $this->errors->log();
        $this->notifications->log();
	}
	
	public function getAccessTokenFromCode(){
		if (isset($_GET['code']) and !$this->client->getToken()) {
			return $this->client->requestAccessToken($_GET['code']);
		}
	}
	
	public function getAuthorizationURL(){
		return $this->client->getAuthorizationUrl();
	}
	
	public function userAuthernticationExists($userID, $userType){
		$userAuthData = $this->db->select($this->table, "userType='".$userType."' AND userID='".$userID."'");
		if(count($userAuthData)>0){
			return true;
		}else{
			return false;
		}
	}
	
	public function saveUserAuthentication($userID, $userType, $refreshingToken=false){
		if(!$refreshingToken){
			// Get the Access Token Object from the code
			$this->accessToken = $this->getAccessTokenFromCode();	
		}
		// Serialize the Access Token Object and save into the database for later use
		$userAuthData = array(
			"userType" => $userType,
			"userID" => $userID,
			"accessToken" => serialize($this->accessToken),
			"createdOn" => $this->db->now()
		);
		if($this->userAuthernticationExists($userID, $userType)){
			$userAuthData['modifiedOn'] = $userAuthData['createdOn'];
			unset($userAuthData['createdOn']);
			$this->db->update($this->table, $userAuthData, "userType='".$userType."' AND userID='".$userID."'");
		}else{
			$this->db->insert($this->table, $userAuthData);
		}
	}
	
	public function loadUserAuthentication($userID, $userType){
		$this->userID = $userID;
		$this->userType = $userType;
		$userAuthData = $this->db->select($this->table, "userType='".$userType."' AND userID='".$userID."'");
		if(count($userAuthData)>0){
			$this->accessToken = unserialize($userAuthData[0]['accessToken']);
			return true;
		}else{
			return false;
		}
	}
	
	// The access token must be set into the object via saveUserAuthentication or loadUserAuthentication
	public function authenticate(){
		try{
			$this->client->setToken($this->accessToken);
			if($this->client->isTokenExpired()){
				$this->accessToken = $this->client->refreshAccessToken();
				$this->client->setToken($this->accessToken);
				$this->saveUserAuthentication($this->userID, $this->userType, true);
			}
			return true;
		}catch(Exception $e){
			return false;
		}
	}
	
	public function tagExist($tag){
		$table = 'ContactGroup';
		$limit = 1000;
		$page = 0;
		$queryData = array('Id' => '%', 'GroupName' => $tag);
		$selectedFields = array('Id','GroupName');
		$orderBy = 'Id';
		$ascending = true;
		$tags = $this->client->data()->query($table, $limit, $page, $queryData, $selectedFields, $orderBy, $ascending); 
		if(count($tags)>0){
			return $tags[0]['Id'];
		}else{
			return false;
		}
	}
	
	public function getTags(){
		$table = 'ContactGroup';
		$limit = 1000;
		$page = 0;
		$queryData = array('Id' => '%');
		$selectedFields = array('Id','GroupName');
		$orderBy = 'Id';
		$ascending = true;
		$tags = $this->client->data()->query($table, $limit, $page, $queryData, $selectedFields, $orderBy, $ascending); 
		if(count($tags)>0){
			return $tags;
		}else{
			return false;
		}
	}
	
	public function contactExists($email){
		$contactData = $this->client->data()->query("Contact",1000,0,['Email' => $email],['Id','FirstName','LastName','Email','Phone1'], 'Id', false);
		if(count($contactData)>0){
			return $contactData[0]['Id'];
		}else{
			return false;
		}
	}
	
	public function printContactServiceClass(){
		print_r($this->client->contacts);
		return method_exists($this->client->contacts('xml'), 'update');
	}
	
	public function createContact($contactData, $tagIDs = array()){
		$contactID = $this->contactExists($contactData['email']);
		// Ugh! This was frustrating! It's like 2 dif version of API in one. Have to send dif data for update then create :'(
		if(!$contactID===false){
			// Contact already exist we just need to update!
			$contact = array(
				'FirstName' => $contactData['firstName'],
				'LastName' => $contactData['lastName'],
				'Phone1' => $contactData['phone'],
				'Phone1Type' => 'Mobile',
				'Address1Type' => 'BILLING',
				'StreetAddress1' => $contactData['address'],
				'Country' => 'United States',
				'PostalCode' => $contactData['zip'],
				'City' => $contactData['city'],
				'State' => "US-".$contactData['state'],
				'Company' => $contactData['brokerage']
			);
			$this->client->contacts('xml')->update($contactID, $contact);
			$contactObj = $this->client->contacts();
			$contactObj->id = $contactID;
		}else{
			$contact = array(
			'email_addresses' => array(
				array(
					'email' => $contactData['email'],
					'field' => 'EMAIL1'
				)
			),
			'given_name' => $contactData['firstName'],
			'family_name' => $contactData['lastName'],
			'phone_numbers' => array(
				array(
					'field' => 'PHONE1', 
					'number' => $contactData['phone']
				)
			),
			'addresses' => array(
				array(
					'line1' => $contactData['address'],
					'country_code' => 'USA',
					'field' => 'BILLING',
					'postal_code' => $contactData['zip'],
					'locality' => $contactData['city'],
					'region' => "US-".$contactData['state']
				)
			)
		);
			// Contact does not exist create a new one!
			$contactObj = $this->client->contacts()->create($contact, false);
		}
		$contactObj->addTags($tagIDs);
		return $contactObj->id;
	}
	
	public function getContacts(){
		print_r($this->client->data()->query("Contact",1000,0,['Id' => '%'],['Id','FirstName','LastName','Email','Phone1'], 'Id', false));
	}
}
1 Like

Edited the title for clarity, thanks for posting your example! :smiley:

1 Like