Хотите повысить уровень интеграции с Salesforce с помощью PHP? Что ж, вам повезло! В этой статье блога мы погрузимся в мир пользовательских запросов конечных точек с помощью REST API Salesforce. Так что хватайте любимый напиток, устраивайтесь поудобнее и начнем!
Salesforce – это мощная CRM-платформа, которая позволяет компаниям управлять отношениями с клиентами, продажами и многим другим. REST API, предоставляемый Salesforce, позволяет разработчикам программно взаимодействовать с данными и функциями Salesforce. Это отличный способ интегрировать ваши PHP-приложения с Salesforce, автоматизировать задачи, получать данные и беспрепятственно отправлять обновления.
Теперь давайте рассмотрим некоторые методы и примеры кода для создания пользовательских запросов к конечной точке с использованием PHP и REST API Salesforce:
-
Аутентификация с помощью Salesforce:
// Your Salesforce authentication credentials $clientId = 'YOUR_CLIENT_ID'; $clientSecret = 'YOUR_CLIENT_SECRET'; $username = 'YOUR_SALESFORCE_USERNAME'; $password = 'YOUR_SALESFORCE_PASSWORD'; // Set up the authentication request $authUrl = 'https://login.salesforce.com/services/oauth2/token'; $params = [ 'grant_type' => 'password', 'client_id' => $clientId, 'client_secret' => $clientSecret, 'username' => $username, 'password' => $password ]; // Send the authentication request $ch = curl_init($authUrl); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); // Extract the access token from the response $accessToken = json_decode($response)->access_token; -
Сделайте запрос GET для получения записей Salesforce:
// Set up the request URL $requestUrl = 'https://yourInstance.salesforce.com/services/data/vXX.X/query?q=SELECT+Id,Name+FROM+Account'; // Set the request headers $headers = [ 'Authorization: Bearer ' . $accessToken ]; // Send the GET request $ch = curl_init($requestUrl); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); // Process the response $records = json_decode($response)->records; foreach ($records as $record) { echo $record->Id . ': ' . $record->Name . '<br>'; } -
Создайте новую запись Salesforce с помощью запроса POST:
// Set up the request URL $requestUrl = 'https://yourInstance.salesforce.com/services/data/vXX.X/sobjects/Account'; // Set the request headers $headers = [ 'Authorization: Bearer ' . $accessToken, 'Content-Type: application/json' ]; // Set the record data $data = [ 'Name' => 'New Account', 'Phone' => '1234567890', 'Website' => 'https://example.com' ]; // Send the POST request $ch = curl_init($requestUrl); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); $response = curl_exec($ch); curl_close($ch); // Process the response $newRecordId = json_decode($response)->id; echo 'New Account created with ID: ' . $newRecordId; -
Обновить существующую запись Salesforce с помощью запроса PATCH:
// Set up the request URL $recordId = 'SOME_RECORD_ID'; $requestUrl = "https://yourInstance.salesforce.com/services/data/vXX.X/sobjects/Account/$recordId"; // Set the request headers $headers = [ 'Authorization: Bearer ' . $accessToken, 'Content-Type: application/json' ]; // Set the updated record data $data = [ 'Phone' => '9876543210', 'Website' => 'https://updated-example.com' ]; // Send the PATCH request $ch = curl_init($requestUrl); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PATCH'); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); $response = curl_exec($ch); curl_close($ch); // Check if the update was successful if ($response === false) { echo 'Failed to update the record.'; } else { echo 'Record updated successfully.'; } -
Удалить запись Salesforce с помощью запроса DELETE:
// Set up the request URL $recordId = 'SOME_RECORD_ID'; $requestUrl = "https://yourInstance.salesforce.com/services/data/vXX.X/sobjects/Account/$recordId"; // Set the request headers $headers = [ 'Authorization: Bearer ' . $accessToken ]; // Send the DELETE request $ch = curl_init($requestUrl); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE'); $response = curl_exec($ch); curl_close($ch); // Check if the delete was successful if ($response === false) { echo 'Failed to delete the record.'; } else { echo 'Record deleted successfully.'; }
И вот оно! Благодаря этим методам и примерам кода у вас теперь есть прочная основа для создания пользовательских запросов к конечным точкам с помощью REST API Salesforce с использованием PHP. Так что вперед, изучайте возможности и улучшайте интеграцию с Salesforce!