Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php namespace SFDC;
- /**
- * This class handles connecting to Salesforce and interacting with the API for various operations such as syncing new users
- */
- class SFDCConnection
- {
- private $login_endpoint = 'https://test.salesforce.com'; // for production, use https://login.salesforce.com
- private $api_version = '34.0';
- // these will be set after authentication
- private $access_token = ''; // the session token to use for authentication with each API call
- private $instance_url = ''; // the base URL of the Salesforce instance being logged into (used for API calls)
- /**
- * Connect to the org via OAuth and get an access token and determine the instance url
- *
- * We're using the OAuth 2.0 username-password flow as documented here by Salesforce:
- * https://help.salesforce.com/apex/HTViewHelpDoc?id=remoteaccess_oauth_username_password_flow.htm&language=en_US
- */
- public function authenticate()
- {
- $auth_url = $this->login_endpoint . "/services/oauth2/token";
- $params = "grant_type=password&format=json"
- . "&client_id=" . SFDC_CLIENT_ID
- . "&client_secret=" . SFDC_CLIENT_SECRET
- . "&username=" . SFDC_USERNAME
- . "&password=" . SFDC_PASSWORD;
- $curl = curl_init($auth_url);
- curl_setopt($curl, CURLOPT_HEADER, array('Content-type: application/x-www-form-urlencoded'));
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($curl, CURLOPT_POST, true);
- curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
- curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // for local testing only
- $json_response = curl_exec($curl);
- $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
- // this may be a good place to write to the log file or send a notification to somebody
- if ( $status > 300 ) {
- // die("Error: call to token URL $auth_url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
- }
- // the response body will contain header information which we don't need
- $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
- $header = substr($json_response, 0, $header_size);
- $body = substr($json_response, $header_size);
- curl_close($curl);
- $response = json_decode($body, true);
- $this->access_token = $response['access_token'];
- $this->instance_url = $response['instance_url'];
- }
- /**
- * This method will return the access token
- */
- public function getAccessToken()
- {
- if($this->access_token == ''){
- $this->authenticate();
- }
- return $this->access_token;
- }
- /**
- * This method will return the instance url
- */
- public function getInstanceURL()
- {
- if($this->instance_url == ''){
- $this->authenticate();
- }
- return $this->instance_url;
- }
- /**
- * This method will contact the Salesforce API to create new leads from the provided arrays of lead data
- */
- public function createLeads($leads)
- {
- // iterate over the provided object data and add the metadata required by the API
- foreach($leads as $key => $lead)
- {
- $lead['attributes'] = ["type" => "Lead", "referenceId" => "ref".$key];
- $leads[$key] = $lead;
- }
- // make the call to Salesforce
- $response = $this->createRecords('Lead', $leads);
- // if records were returned then we should query for more info
- if(!empty($response['results']))
- {
- // query the org to see if the leads were converted and retrieve relevant info
- $response['results'] = $this->checkForConvertedLeads($response['results']);
- }
- return $response;
- }
- /**
- * This method will contact the Salesforce API to create new records
- *
- * For more info regarding the API call being used, please refer to the following Salesforce documentation:
- * https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_composite_sobject_tree_flat.htm
- * https://developer.salesforce.com/docs/atlas.en-us.200.0.api_rest.meta/api_rest/resources_composite_sobject_tree.htm
- */
- private function createRecords($SObjectName, $records)
- {
- $url = $this->getInstanceURL()."/services/data/v".$this->api_version."/composite/tree/".$SObjectName."/";
- $content = json_encode(array('records' => $records));
- $curl = curl_init($url);
- curl_setopt($curl, CURLOPT_HEADER, false);
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
- curl_setopt(
- $curl,
- CURLOPT_HTTPHEADER,
- array(
- "Authorization: OAuth ".$this->getAccessToken(),
- "Content-type: application/json"
- )
- );
- curl_setopt($curl, CURLOPT_POST, true);
- curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
- curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // for local testing only
- $json_response = curl_exec($curl);
- $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
- // this may be a good place to write to the log file or send a notification to somebody
- if ( $status > 300 ) {
- // die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
- }
- curl_close($curl);
- $response = json_decode($json_response, true);
- return $response;
- }
- /**
- * This method will contact the Salesforce API to update leads based on the provided arrays of lead data
- */
- public function updateLeads($leads)
- {
- // iterate over the provided object data and add the metadata required by the API
- foreach($leads as $key => $lead)
- {
- $lead['attributes'] = ["type" => "Lead", "referenceId" => "ref".$key];
- $leads[$key] = $lead;
- }
- // make the call to Salesforce
- $this->updateRecords('Lead', $leads);
- // query the org to see if the leads were converted and retrieve relevant info
- return $this->checkForConvertedLeads($leads);
- }
- /**
- * This method will contact the Salesforce API to update records
- *
- * For more info regarding the API call being used, please refer to the following Salesforce documentation:
- * https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_update_fields.htm
- */
- private function updateRecords($SObjectName, $records)
- {
- $responses = array();
- foreach($records as $record)
- {
- $url = $this->getInstanceURL()."/services/data/v".$this->api_version."/sobjects/".$SObjectName."/".$record['id'];
- unset($record['id']);
- $content = json_encode($record);
- $curl = curl_init($url);
- curl_setopt($curl, CURLOPT_HEADER, false);
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
- curl_setopt(
- $curl,
- CURLOPT_HTTPHEADER,
- array(
- "Authorization: OAuth ".$this->getAccessToken(),
- "Content-type: application/json"
- )
- );
- curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PATCH');
- curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
- curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // for local testing only
- $json_response = curl_exec($curl);
- $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
- // this may be a good place to write to the log file or send a notification to somebody
- if ( $status > 300 ) {
- // die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
- }
- curl_close($curl);
- $response = json_decode($json_response, true);
- array_push($responses, $response);
- }
- return $responses;
- }
- /**
- * This method will accept a list of leads and query Salesforce for the fields related to lead conversion
- */
- private function checkForConvertedLeads($leadArr)
- {
- // build a list of lead IDs
- $leadIdArr = array();
- foreach($leadArr as $lead){
- $leadIdArr[] = $lead['id'];
- }
- // query Salesforce for the fields related to lead conversion
- return $this->queryAll('SELECT Id, IsConverted, ConvertedAccountId, ConvertedContactId, ConvertedOpportunityId FROM Lead WHERE Id IN (\''.implode('\',\'', $leadIdArr).'\')');
- }
- /**
- * This method will contact the Salesforce API to query for records using SOQL
- *
- * For more info regarding SOQL, please refer to the following Salesforce documentation:
- * https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/
- */
- private function queryAll($query){
- return $this->query($query, true);
- }
- private function query($query, $getAll)
- {
- $url = $this->getInstanceURL()."/services/data/v".$this->api_version."/query/?q=".urlencode($query);
- $curl = curl_init($url);
- curl_setopt($curl, CURLOPT_HEADER, false);
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($curl, CURLOPT_POST, false);
- curl_setopt(
- $curl,
- CURLOPT_HTTPHEADER,
- array(
- "Authorization: OAuth ".$this->getAccessToken(),
- "Content-type: application/json"
- )
- );
- curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // for local testing only
- $json_response = curl_exec($curl);
- $response = json_decode($json_response, true);
- $results = $response['records'];
- $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
- curl_close($curl);
- // this may be a good place to write to the log file or send a notification to somebody
- if ( $status > 300 ) {
- // die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
- }
- // if not all results were retrieved in the first response, keep querying until everything is returned
- if($getAll == true && $response['done'] == false)
- {
- $resultSet = $this->fetchResults($response['nextRecordsUrl']);
- while($resultSet['done'] == false)
- {
- array_push($results, $resultSet['records']);
- $resultSet = $this->fetchResults($resultSet['nextRecordsUrl']);
- }
- }
- if($getAll == true){
- return $results;
- }
- else{
- return $response;
- }
- }
- /**
- * This method accepts a URL for retrieving query results and makes the request
- */
- private function fetchResults($url)
- {
- $curl = curl_init($url);
- curl_setopt($curl, CURLOPT_HEADER, false);
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
- curl_setopt(
- $curl,
- CURLOPT_HTTPHEADER,
- array(
- "Authorization: OAuth ".$this->getAccessToken(),
- "Content-type: application/json"
- )
- );
- curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // for local testing only
- $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
- $json_response = curl_exec($curl);
- $response = json_decode($json_response, true);
- // this may be a good place to write to the log file or send a notification to somebody
- if ( $status > 300 ) {
- // die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
- }
- curl_close($curl);
- return $response;
- }
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement