Salesforce Apex

This code executes the Lingk Event REST API and can pass data from Salesforce to a recipe based on a Salesforce event.

String apiEndpoint = 'https://www.lingkapis.com/v1/@self/events';
String key = '[key]';
String secret ='[secret]'; 

String requestMethod = 'POST';

// Signature creation
System.Url URL = new Url(apiEndpoint);

// Date formatting for Signature and Date header

DateTime dt = DateTime.now();
Date localDate = dt.date();
Time localTime = dt.time();

DateTime nowInUtc = DateTime.newInstance(localDate, localTime);
String formattedDate = nowInUtc.formatGMT('EEE, dd MMM yyyy HH:mm:ss');
formattedDate = formattedDate+' GMT';
// formatGMT('EE, dd mmm yyyy HH:nn:ss GMT');
// "Mon, 02 Jan 2006 15:04:05 GMT"

system.debug('formatted date is ' + formattedDate);
system.debug('request method is ' + requestMethod.toLowerCase());
system.debug('url path  is ' + URL.getPath());

// create a message to sign
String message = 'date: ' + formattedDate + '\n(request-target): ' + requestMethod.toLowerCase() + ' ' + URL.getPath();

system.debug('signingString is ' + message);

Blob signatureBlob = Crypto.generateMac('HMacSHA1', Blob.valueOf(message), Blob.ValueOf(secret));

String signature = EncodingUtil.urlEncode(EncodingUtil.base64Encode(signatureBlob),'ASCII');

system.debug('signature is ' + signature);

// construct authorization header
String authorizationHeader = 'Signature keyId=\"' + key + '\",headers=\"date (request-target)\",algorithm=\"hmac-sha1\",signature=\"' + signature + '\"';

system.debug('authorizationHeader is ' + authorizationHeader);

// JSON Payload
JSONGenerator gen = JSON.createGenerator(true);
gen.writeStartObject();
gen.writeStringField('verb', 'create');
gen.writeStringField('objectType', 'centralu.salesforce.newlead');
gen.writeFieldName('eventObject');
    gen.writeStartObject();
    gen.writeEndObject();    
gen.writeEndObject();
String jsonBody = gen.getAsString();
System.debug(jsonBody); 

// HTTP Request
  // for the code the call the Lingk REST APIs
  // It is best to separate this into a separate class or method
  Http h = new Http();
  HttpRequest req = new HttpRequest();
  req.setHeader('Date', formattedDate);
  req.setHeader('Authorization', authorizationHeader);
  req.setEndpoint(apiEndpoint);
  req.setMethod(requestMethod);
  req.setBody(jsonBody);
  String responseBody;
  HttpResponse res;
  res = h.send(req);
  responseBody = res.getBody();
  system.debug('response ' + responseBody);

  // add additional debugging for HTTP code and errors

Last updated