Files

76 lines
2.1 KiB
PHP
Raw Permalink Normal View History

2016-11-25 13:03:45 -05:00
<?php
class Salesforce
{
2018-05-21 11:49:15 -04:00
const
2016-11-25 13:03:45 -05:00
API_URL = 'https://api.salesforceiq.com/v2/',
DEFAULT_LIST_ID = '58387a94e4b0a1fea2c76f4a';
2018-05-21 11:49:15 -04:00
protected static $curlOptions = [
2016-11-25 13:03:45 -05:00
'headers' => ['Accept: application/json', 'Content-type: application/json'],
'json_response' => true,
'json_data' => true,
'timeout' => 10
];
2018-05-21 11:49:15 -04:00
public static function createContact(string $email, string $initialListId = null, string $acquisitionChannel = null)
{
$contactData = [
2016-11-25 13:03:45 -05:00
'properties' => [
'email' => [[
'value' => $email,
'metadata' => ['primary' => true]
]]
]
];
2018-05-21 11:49:15 -04:00
$contactId = static::post('contacts?_upsert=email', $contactData)['id'] ?? null;
2016-11-25 13:03:45 -05:00
2018-05-21 11:49:15 -04:00
if ($initialListId) {
if (!$contactId) {
throw new SalesforceException('Failed to generate or update contact');
}
2016-11-25 13:03:45 -05:00
2018-05-21 11:49:15 -04:00
static::post('lists/' . $initialListId . '/listitems?_upsert=contactIds', [
2016-11-25 13:03:45 -05:00
'contactIds' => [$contactId],
'fieldValues' => (object)[
'2' => [['raw' => $acquisitionChannel]]
]
]);
2018-05-21 11:49:15 -04:00
}
2016-11-25 13:03:45 -05:00
}
2018-05-21 11:49:15 -04:00
protected static function getApiUserPassword()
2016-11-25 13:03:45 -05:00
{
2018-05-21 11:49:15 -04:00
$userpw = Config::get(Config::SALESFORCE_KEY) . ':' . Config::get(Config::SALESFORCE_SECRET);
if ($userpw[0] === ':' || substr($userpw, -1) === ':') {
throw new SalesforceException('Salesforce key and/or secret not configured correctly');
}
return $userpw;
2016-11-25 13:03:45 -05:00
}
2018-05-21 11:49:15 -04:00
public static function get($endpoint, array $data = [])
{
$options = [
2016-11-25 13:03:45 -05:00
'password' => static::getApiUserPassword(),
] + static::$curlOptions;
2018-05-21 11:49:15 -04:00
$responseData = Curl::get(static::API_URL . $endpoint, $data, $options);
2016-11-25 13:03:45 -05:00
2018-05-21 11:49:15 -04:00
return $responseData ?? [];
}
2016-11-25 13:03:45 -05:00
2018-05-21 11:49:15 -04:00
public static function post($endpoint, array $data = [], array $options = [])
{
$options += [
2016-11-25 13:03:45 -05:00
'password' => static::getApiUserPassword(),
] + static::$curlOptions;
2018-05-21 11:49:15 -04:00
$responseData = Curl::post(static::API_URL . $endpoint, $data, $options);
return $responseData ?? [];
}
2016-11-25 13:03:45 -05:00
}
class SalesforceException extends Exception
{
}