Advertisement
Guest User

Untitled

a guest
Aug 26th, 2016
232
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.00 KB | None | 0 0
  1. <?php namespace SFDC;
  2.  
  3. /**
  4. * This class handles connecting to Salesforce and interacting with the API for various operations such as syncing new users
  5. */
  6. class SFDCConnection
  7. {
  8. private $login_endpoint = 'https://test.salesforce.com'; // for production, use https://login.salesforce.com
  9. private $api_version = '34.0';
  10.  
  11. // these will be set after authentication
  12. private $access_token = ''; // the session token to use for authentication with each API call
  13. private $instance_url = ''; // the base URL of the Salesforce instance being logged into (used for API calls)
  14.  
  15. /**
  16. * Connect to the org via OAuth and get an access token and determine the instance url
  17. *
  18. * We're using the OAuth 2.0 username-password flow as documented here by Salesforce:
  19. * https://help.salesforce.com/apex/HTViewHelpDoc?id=remoteaccess_oauth_username_password_flow.htm&language=en_US
  20. */
  21. public function authenticate()
  22. {
  23.  
  24. $auth_url = $this->login_endpoint . "/services/oauth2/token";
  25.  
  26. $params = "grant_type=password&format=json"
  27. . "&client_id=" . SFDC_CLIENT_ID
  28. . "&client_secret=" . SFDC_CLIENT_SECRET
  29. . "&username=" . SFDC_USERNAME
  30. . "&password=" . SFDC_PASSWORD;
  31.  
  32. $curl = curl_init($auth_url);
  33. curl_setopt($curl, CURLOPT_HEADER, array('Content-type: application/x-www-form-urlencoded'));
  34. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  35. curl_setopt($curl, CURLOPT_POST, true);
  36. curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
  37. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // for local testing only
  38.  
  39. $json_response = curl_exec($curl);
  40.  
  41. $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  42.  
  43. // this may be a good place to write to the log file or send a notification to somebody
  44. if ( $status > 300 ) {
  45. // 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));
  46. }
  47.  
  48. // the response body will contain header information which we don't need
  49. $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
  50. $header = substr($json_response, 0, $header_size);
  51. $body = substr($json_response, $header_size);
  52.  
  53. curl_close($curl);
  54.  
  55. $response = json_decode($body, true);
  56.  
  57. $this->access_token = $response['access_token'];
  58. $this->instance_url = $response['instance_url'];
  59. }
  60.  
  61. /**
  62. * This method will return the access token
  63. */
  64. public function getAccessToken()
  65. {
  66. if($this->access_token == ''){
  67. $this->authenticate();
  68. }
  69. return $this->access_token;
  70. }
  71.  
  72. /**
  73. * This method will return the instance url
  74. */
  75. public function getInstanceURL()
  76. {
  77. if($this->instance_url == ''){
  78. $this->authenticate();
  79. }
  80. return $this->instance_url;
  81. }
  82.  
  83. /**
  84. * This method will contact the Salesforce API to create new leads from the provided arrays of lead data
  85. */
  86. public function createLeads($leads)
  87. {
  88. // iterate over the provided object data and add the metadata required by the API
  89. foreach($leads as $key => $lead)
  90. {
  91. $lead['attributes'] = ["type" => "Lead", "referenceId" => "ref".$key];
  92. $leads[$key] = $lead;
  93. }
  94.  
  95. // make the call to Salesforce
  96. $response = $this->createRecords('Lead', $leads);
  97.  
  98. // if records were returned then we should query for more info
  99. if(!empty($response['results']))
  100. {
  101. // query the org to see if the leads were converted and retrieve relevant info
  102. $response['results'] = $this->checkForConvertedLeads($response['results']);
  103. }
  104.  
  105. return $response;
  106. }
  107.  
  108. /**
  109. * This method will contact the Salesforce API to create new records
  110. *
  111. * For more info regarding the API call being used, please refer to the following Salesforce documentation:
  112. * https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_composite_sobject_tree_flat.htm
  113. * https://developer.salesforce.com/docs/atlas.en-us.200.0.api_rest.meta/api_rest/resources_composite_sobject_tree.htm
  114. */
  115. private function createRecords($SObjectName, $records)
  116. {
  117. $url = $this->getInstanceURL()."/services/data/v".$this->api_version."/composite/tree/".$SObjectName."/";
  118.  
  119. $content = json_encode(array('records' => $records));
  120.  
  121. $curl = curl_init($url);
  122. curl_setopt($curl, CURLOPT_HEADER, false);
  123. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  124. curl_setopt(
  125. $curl,
  126. CURLOPT_HTTPHEADER,
  127. array(
  128. "Authorization: OAuth ".$this->getAccessToken(),
  129. "Content-type: application/json"
  130. )
  131. );
  132. curl_setopt($curl, CURLOPT_POST, true);
  133. curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
  134. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // for local testing only
  135.  
  136. $json_response = curl_exec($curl);
  137.  
  138. $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  139.  
  140. // this may be a good place to write to the log file or send a notification to somebody
  141. if ( $status > 300 ) {
  142. // die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
  143. }
  144.  
  145. curl_close($curl);
  146.  
  147. $response = json_decode($json_response, true);
  148.  
  149. return $response;
  150. }
  151.  
  152. /**
  153. * This method will contact the Salesforce API to update leads based on the provided arrays of lead data
  154. */
  155. public function updateLeads($leads)
  156. {
  157. // iterate over the provided object data and add the metadata required by the API
  158. foreach($leads as $key => $lead)
  159. {
  160. $lead['attributes'] = ["type" => "Lead", "referenceId" => "ref".$key];
  161. $leads[$key] = $lead;
  162. }
  163.  
  164. // make the call to Salesforce
  165. $this->updateRecords('Lead', $leads);
  166.  
  167. // query the org to see if the leads were converted and retrieve relevant info
  168. return $this->checkForConvertedLeads($leads);
  169. }
  170.  
  171. /**
  172. * This method will contact the Salesforce API to update records
  173. *
  174. * For more info regarding the API call being used, please refer to the following Salesforce documentation:
  175. * https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_update_fields.htm
  176. */
  177. private function updateRecords($SObjectName, $records)
  178. {
  179. $responses = array();
  180.  
  181. foreach($records as $record)
  182. {
  183. $url = $this->getInstanceURL()."/services/data/v".$this->api_version."/sobjects/".$SObjectName."/".$record['id'];
  184.  
  185. unset($record['id']);
  186. $content = json_encode($record);
  187.  
  188. $curl = curl_init($url);
  189. curl_setopt($curl, CURLOPT_HEADER, false);
  190. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  191. curl_setopt(
  192. $curl,
  193. CURLOPT_HTTPHEADER,
  194. array(
  195. "Authorization: OAuth ".$this->getAccessToken(),
  196. "Content-type: application/json"
  197. )
  198. );
  199. curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PATCH');
  200. curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
  201. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // for local testing only
  202.  
  203. $json_response = curl_exec($curl);
  204.  
  205. $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  206.  
  207. // this may be a good place to write to the log file or send a notification to somebody
  208. if ( $status > 300 ) {
  209. // die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
  210. }
  211.  
  212. curl_close($curl);
  213.  
  214. $response = json_decode($json_response, true);
  215. array_push($responses, $response);
  216. }
  217.  
  218. return $responses;
  219. }
  220.  
  221. /**
  222. * This method will accept a list of leads and query Salesforce for the fields related to lead conversion
  223. */
  224. private function checkForConvertedLeads($leadArr)
  225. {
  226. // build a list of lead IDs
  227. $leadIdArr = array();
  228. foreach($leadArr as $lead){
  229. $leadIdArr[] = $lead['id'];
  230. }
  231.  
  232. // query Salesforce for the fields related to lead conversion
  233. return $this->queryAll('SELECT Id, IsConverted, ConvertedAccountId, ConvertedContactId, ConvertedOpportunityId FROM Lead WHERE Id IN (\''.implode('\',\'', $leadIdArr).'\')');
  234. }
  235.  
  236. /**
  237. * This method will contact the Salesforce API to query for records using SOQL
  238. *
  239. * For more info regarding SOQL, please refer to the following Salesforce documentation:
  240. * https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/
  241. */
  242. private function queryAll($query){
  243. return $this->query($query, true);
  244. }
  245. private function query($query, $getAll)
  246. {
  247. $url = $this->getInstanceURL()."/services/data/v".$this->api_version."/query/?q=".urlencode($query);
  248. $curl = curl_init($url);
  249. curl_setopt($curl, CURLOPT_HEADER, false);
  250. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  251. curl_setopt($curl, CURLOPT_POST, false);
  252. curl_setopt(
  253. $curl,
  254. CURLOPT_HTTPHEADER,
  255. array(
  256. "Authorization: OAuth ".$this->getAccessToken(),
  257. "Content-type: application/json"
  258. )
  259. );
  260. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // for local testing only
  261.  
  262. $json_response = curl_exec($curl);
  263. $response = json_decode($json_response, true);
  264. $results = $response['records'];
  265.  
  266. $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  267.  
  268. curl_close($curl);
  269.  
  270. // this may be a good place to write to the log file or send a notification to somebody
  271. if ( $status > 300 ) {
  272. // die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
  273. }
  274.  
  275. // if not all results were retrieved in the first response, keep querying until everything is returned
  276. if($getAll == true && $response['done'] == false)
  277. {
  278. $resultSet = $this->fetchResults($response['nextRecordsUrl']);
  279.  
  280. while($resultSet['done'] == false)
  281. {
  282. array_push($results, $resultSet['records']);
  283. $resultSet = $this->fetchResults($resultSet['nextRecordsUrl']);
  284. }
  285. }
  286.  
  287. if($getAll == true){
  288. return $results;
  289. }
  290. else{
  291. return $response;
  292. }
  293. }
  294.  
  295. /**
  296. * This method accepts a URL for retrieving query results and makes the request
  297. */
  298. private function fetchResults($url)
  299. {
  300. $curl = curl_init($url);
  301. curl_setopt($curl, CURLOPT_HEADER, false);
  302. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  303. curl_setopt(
  304. $curl,
  305. CURLOPT_HTTPHEADER,
  306. array(
  307. "Authorization: OAuth ".$this->getAccessToken(),
  308. "Content-type: application/json"
  309. )
  310. );
  311. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // for local testing only
  312.  
  313. $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  314.  
  315. $json_response = curl_exec($curl);
  316. $response = json_decode($json_response, true);
  317.  
  318. // this may be a good place to write to the log file or send a notification to somebody
  319. if ( $status > 300 ) {
  320. // die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
  321. }
  322.  
  323. curl_close($curl);
  324.  
  325. return $response;
  326. }
  327. }
  328. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement