Skip to content

Instantly share code, notes, and snippets.

@patpawlowski
Created January 7, 2017 00:16
Show Gist options
  • Save patpawlowski/32a7faa339ad2d8b5542721011894689 to your computer and use it in GitHub Desktop.
Save patpawlowski/32a7faa339ad2d8b5542721011894689 to your computer and use it in GitHub Desktop.
Yet another Sugar REST API v10 Wrapper
<?php
/**
* Created by NetBeans.
* User: patpawlowski
* Date: Dec 20, 2014 at 9:44:51 AM
* File: SugarAPI
*/
class SugarAPI{
private $oauthtoken = FALSE;
private $oathrefreshtoken = '';
private $base_url = '';
private $username = '';
private $password = '';
private $starttime = '';
private $curl_error = '';
private $debug = false;
public function __construct($base_url, $username, $password)
{
if ($this->debug) echo "<pre>\nConstructor starting\n";
$this->base_url = $base_url;
$this->username = $username;
$this->password = $password;
$url_ext = "/oauth2/token";
$oauth2_token_parameters = array(
"grant_type" => "password",
"client_id" => "sugar",
"client_secret" => "",
"username" => $username,
"password" => $password,
"platform" => "base"
);
$this->starttime = new DateTime(); // $this->starttime must be defined before calling "call" the first time.
$oauth2_token_result = $this->call($url_ext, 'POST', $oauth2_token_parameters);
if($oauth2_token_result)
{
$this->oauthtoken = $oauth2_token_result->access_token;
$this->oathrefreshtoken = $oauth2_token_result->refresh_token;
}else{
}
if ($this->debug)
{
echo "oauth2_token_result:\n";
print_r($oauth2_token_result);
echo "OAUTH Token: ".$this->oauthtoken."\n";
echo "Constructor ending\n\n";
}
}
// public function search($module, $filter){
//// e.g. $filter = '[{"name":"812"}]'
// return $this->call('/'.$module.'?filter='.$filter, 'GET');
//// return $this->call('/'.$module.'?q=812', 'GET', array());
// }
public function search($module, $filter){
return $this->call('/'.$module, 'GET', $filter);
}
public function create($module, $record_parameters){
return $this->call('/'.$module, 'POST', $record_parameters);
}
public function read($module, $id){
return $this->call('/'.$module.'/'.$id, 'GET');
}
public function update($module, $id, $record_parameters){
return $this->call('/'.$module.'/'.$id, 'PUT', $record_parameters);
}
public function upsert($module, $record_parameters){
if(!empty($record_parameters['id'])){
$Result = $this->update($module, $record_parameters['id'], $record_parameters);
if(!(isset($Result->error) && $Result->error = 'not_found')){
return $Result;
}
}
return $this->create($module, $record_parameters);
//
// if(empty($record_parameters['id']) || !$this->checkID($module, $record_parameters['id'])){
// return $this->create($module, $record_parameters);
// }else{
// return $this->update($module, $record_parameters['id'], $record_parameters);
// }
}
public function delete($module, $id){
return $this->call('/'.$module.'/'.$id, 'DELETE');
}
public function createRelationship($module, $id, $link_name, $remote_id) {
return $this->call('/'.$module.'/'.$id.'/link/'.$link_name.'/'.$remote_id, 'POST');
}
public function readRelatedRecords($module, $id, $link_name) {
return $this->call('/'.$module.'/'.$id.'/link/'.$link_name);
}
public function deleteRelationship($module, $id, $link_name, $remote_id) {
return $this->call('/'.$module.'/'.$id.'/link/'.$link_name.'/'.$remote_id, 'DELETE');
}
public function readFile($module, $id, $fieldname) {
return $this->call("/$module/$id/file/$fieldname", 'GET',array() ,true, true );
}
public function bulkAPICall($parameters) {
return $this->call('/bulk', 'POST', $parameters);
}
public function getOathToken()
{
return $this->oauthtoken;
}
public function checkID($module, $id) {
$Return = $this->read($module, $id);
if(isset($Return->id)){
return TRUE;
}else{
return FALSE;
}
}
/**
* Generic function to make cURL request.
* @param $url - The URL route to use.
* @param string $oauthtoken - The oauth token.
* @param string $type - GET, POST, PUT. Defaults to GET.
* @param array $parameters - Endpoint parameters.
* @param array $encodeData - Whether or not to JSON encode the data.
* @param array $returnHeaders - Whether or not to return the headers.
* @return mixed
*/
public function call(
$url_ext,
$type = 'GET',
$parameters=array(),
$encodeData=true,
$returnHeaders=false
)
{
if ($this->debug)
{
echo "call function starting\n";
echo "url_ext: ".$type."\n";
echo "type: ".$url_ext."\n";
echo "parameters: \n";
print_r($parameters);
}
// Check for OAUTH Token Expiration
$this->checkToken();
$url = $this->base_url.$url_ext;
$oauthtoken = $this->oauthtoken;
$type = strtoupper($type);
if ($type == 'GET')
{
if(is_array($parameters))
{
$url .= "?" . http_build_query($parameters);
}
}
/*
* $filter_arguments = array(
* "filter" => array(
* array(
* "name" => 'Osborne Coinage'
* ),
* ),
* "max_num" => 2,
* "offset" => 0,
* "fields" => "name,description",
* "order_by" => "name:DESC",
* "favorites" => false,
* "my_items" => false,
* );
*/
if ($this->debug) echo "CURL URL: ".$url."\n";
$curl_request = curl_init($url);
if ($type == 'POST')
{
curl_setopt($curl_request, CURLOPT_POST, 1);
}
elseif ($type == 'PUT')
{
curl_setopt($curl_request, CURLOPT_CUSTOMREQUEST, "PUT");
}
elseif ($type == 'DELETE')
{
curl_setopt($curl_request, CURLOPT_CUSTOMREQUEST, "DELETE");
}
curl_setopt($curl_request, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
curl_setopt($curl_request, CURLOPT_HEADER, $returnHeaders);
curl_setopt($curl_request, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl_request, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_request, CURLOPT_FOLLOWLOCATION, 0);
$header = array('Content-Type: application/json');
if (!empty($oauthtoken))
{
$header[] = "oauth-token: $oauthtoken";
}
curl_setopt($curl_request, CURLOPT_HTTPHEADER, $header);
if (!empty($parameters) && $type !== 'GET')
{
if ($encodeData)
{
//encode the parameters as JSON
$parameters = json_encode($parameters);
}
curl_setopt($curl_request, CURLOPT_POSTFIELDS, $parameters);
}
$result = curl_exec($curl_request);
if(!$result)
{
$this->curl_error = curl_error($curl_request);
}
if ($this->debug)
{
echo "Raw CURL response:\n";
print_r($result);
echo "CURL ERROR: ".curl_error($curl_request);
}
if ($returnHeaders)
{
$header_size = curl_getinfo($curl_request,CURLINFO_HEADER_SIZE);
$headers = substr($result, 0, $header_size);
$ReturnArray = array();
foreach (explode("\r\n",$headers) as $header)
{
$header_parts = explode(':', $header);
if($header_parts[0] === 'Content-Disposition'){
$ReturnArray['FileName'] = substr(explode('filename=', $header_parts[1])['1'], 1, -1);
}
}
$ReturnArray['File'] = substr($result, $header_size);
return $ReturnArray;
}
curl_close($curl_request);
//decode the response from JSON
$response = json_decode($result);
if ($this->debug) echo "\ncall function ending\n";
return $response;
}
private function refreshToken()
{
// $this->starttime must be reset before calling $this->call or an endless loop will be initiated
$Now = new DateTime();
$this->starttime = $Now;
$this->oauthtoken = FALSE;
$url_ext = "/oauth2/token";
$oauth2_token_parameters = array(
"grant_type" => "refresh_token",
"refresh_token" => $this->oathrefreshtoken,
"client_id" => "sugar",
"client_secret" => ""
);
$oauth2_token_result = $this->call($url_ext, 'POST', $oauth2_token_parameters);
print_r($oauth2_token_result);
$this->oauthtoken = $oauth2_token_result->access_token;
$this->oathrefreshtoken = $oauth2_token_result->refresh_token;
echo "OAUTH Token refreshed\n";
}
public function checkToken()
{
$Now = new DateTime();
$TokenAge = date_diff($this->starttime, $Now, true);
if ($TokenAge->i > 59 || $TokenAge->h > 0)
{
echo "OAUTH Token about to expire. Refreshing. . . \n";
$this->refreshToken();
}
}
public function isConnected() {
if($this->oauthtoken)
{
return TRUE;
} else {
return FALSE;
}
}
public function getCurlError() {
return $this->curl_error;
}
}
@patpawlowski
Copy link
Author

Usage is pretty simple
$SugarAPI = new SugarAPI('https://<MySugarInstance>/rest/v10', 'Username', 'Password');

Create a record
$Account = $Sugar->create($module, $record_parameters);
Example:
$Account = $Sugar->create('Accounts', array('name' => 'My Account'));
print_r($Account);

Read a record
$Account = $Sugar->read($module, $id);
Example:
$Account = $Sugar->read('Accounts', 'e9a9aa14-af06-8099-7716-53289dd5fb4f');
print_r($Account);

Update a record
$Account = $Sugar->update($module, $record_parameters);
Example:
$Account = $Sugar->update('Accounts', array('description' => 'This will be the new description on the account'));
print_r($Account);

You can also delete; upsert; create, delete, and update relationships; and the most recent addition, readFile to download an attachment from a document record.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment