Salesforce Apex Trigger Example
Below is an exampole of a trigger handler for a Salesforce Apex Trigger. For a compleate udnerstanding of triggers in Salesforce please consult the salesforce documentation.
Remember to register a Remote Site Settings in salesforce for your Automation webhook.
// Salesforce Apex Class to trigger automation
public class Flow_AccountTriggerHandler {
private static String FlowUrl = 'https://AutomationWebhookUrl'; // Automation Endpoint
private static String FlowApiKey = '<AccessKey>'; //Automation Access Key
@future (callout=true)
public static void makeCalloutToFlow(id accountId, String accountAsJson) {
HttpResponse response = makeHttpPostCalloutToWebhook(
FlowUrl,
FlowApiKey,
accountAsJson);
updateAccountWithAccountNumber(
accountId,
response.getStatusCode(),
response.getBody());
}
private static HttpResponse makeHttpPostCalloutToWebhook(
String webhookEndpoint,
String xApiKeyHeaderValue,
String jsonBody)
{
HttpRequest request = new HttpRequest();
request.setMethod('POST'); // POST Method
request.setEndpoint(webhookEndpoint);
// Begin Headers
request.setHeader('x-api-key', xApiKeyHeaderValue); // Access Key
request.setHeader('Content-Type', 'application/json'); // Body Format
request.setHeader('Accept','*/*'); //Required Can be */*, application/json, application/xml
// Beging Body
request.setBody(jsonBody);
request.setTimeout(60 * 1000);
return new Http().send(request);
}
private static void updateAccountWithAccountNumber(id accId, Integer statusCode, String jsonStr)
{
Account account = getAccountById(accId);
if (account != null) {
if (statusCode == 200)
{
Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(jsonStr);
String hasFailed = (String) results.get('HasFailed');
if (hasFailed != null && hasFailed.toLowerCase().equals('false'))
account.AccountNumber = (String) results.get('CustomerId');
}
account.Description = 'Flow : ' + statusCode + ' ' + jsonStr;
update account;
}
}
private static Account getAccountById(id accountId) {
List <Account> accounts = [SELECT Id,Name,Description FROM Account WHERE Id = :accountId];
if (!accounts.isEmpty()) return accounts[0];
else return null;
}
}
Last updated
Was this helpful?