Uncategorized

Use Apex Callouts and Workflow with Heroku /Utilisation d’appels externes Apex et d’un workflow avec Heroku

Learning Objectives /Objectifs de formation

After completing this unit, you’ll be able to: /Une fois cette unité terminée, vous pourrez :

  • Understand how to use Apex callouts and workflow with Heroku. /Comprendre comment utiliser des appels externes Apex et un workflow avec Heroku.
  • Understand the use cases for Apex callouts and workflow. /Comprendre l’utilisation de requêtes pour des appels externes Apex et un workflow.

Callouts to Heroku Apps /Appels externes vers des applications Heroku

Sometimes events on Salesforce need to be handled by an external system due to the scale or type of process being executed. For instance, a user in Salesforce uploads an image that needs to be resized for future use. Heroku can receive an event from Salesforce and perform some process in response. Optionally, the output of the process could be stored back in Salesforce using the REST APIs or Heroku Connect. /Parfois, les événements Salesforce doivent être gérés par un système externe en raison de leur taille ou du type de processus exécuté. Par exemple, un utilisateur de Salesforce charge une image qui doit être redimensionnée pour une utilisation ultérieure. Heroku peut recevoir un événement de Salesforce et exécuter en réponse un processus. Le processus de sortie peut éventuellement être stocké dans Salesforce à l’aide des API REST ou de Heroku Connect.

Diagram showing a box with Salesforce and a Data Event that is triggered or sent from an outbound message. An arrow comes from the box and points to another box that contains all the apps that Heroku hosts

There are two primary methods to call a Heroku app based on an event in Salesforce: workflow outbound messages or Apex HTTP callouts. A workflow outbound message declaratively makes a SOAP call. An Apex HTTP callout programmatically makes a REST call to a Heroku app. Either way, the Heroku app receives a request with the event details payload and then performs the action. /Les deux principales méthodes d’appel d’une application Heroku basées sur un événement dans Salesforce sont les suivantes : messages sortants de workflow et appels externes HTTP Apex. Un message sortant de workflow effectue un appel SOAP par déclaration. Un appel externe HTTP Apex effectue un appel REST par programmation à une application Heroku. Avec les deux méthodes, l’application Heroku reçoit une requête avec la charge de travail des détails d’événement, puis exécute l’action.

Callouts with Workflow /Appels externes avec un workflow

With workflow, you declaratively define a rule and a callout to an external system. The rule can be connected to any Salesforce object, like Contact or Account, and be triggered based on these record events: /Avec un workflow, vous définissez par déclaration une règle et un appel externe à un système externe. La règle peut être connectée à n’importe quel objet Salesforce, par exemple Contact ou Compte, et peut être déclenchée en fonction des événements d’enregistrement suivants :

  • Created /Création
  • Created, and every time it’s edited /Création, puis à chaque modification
  • Created, and any time it’s edited to subsequently meet criteria /Création, puis à chaque modification pour remplir les critères

Rules must have criteria that filter the events. If you don’t want to do any filtering, you can add a criteria that is always true. Here is an example rule: /Les règles doivent inclure des critères qui filtrent les événements. Si vous ne souhaitez pas filtrer, vous pouvez ajouter un critère qui est toujours vrai. Voici un exemple de règle :

Screenshot of the Configure Workflow Rule dialog showing that the rule name should be New Contact

To call a Heroku app when the rule executes, add an outbound message to the list of immediate workflow actions and specify a Heroku app endpoint as the endpoint URL, like: /Pour appeler une application Heroku lorsque la règle est exécutée, ajoutez un message sortant à la liste des actions de workflow immédiates, puis spécifiez un point de terminaison d’application Heroku en tant qu’URL de point de terminaison de terminaison, par exemple :

Screenshot of the Configure OUtbound Messaging dialog, showing the message named New Contact to Heroku

If you select Send Session ID, the Heroku app can use that token to make REST API calls on the user’s behalf. If you don’t send the session ID. there’s no way to check that the request was valid or protect against malicious calls to your Heroku app’s API endpoint. /Si vous sélectionnez Send Session ID (Envoyer l’ID de session), l’application Heroku peut utiliser ce jeton pour effectuer des appels d’API REST au nom de l’utilisateur. Si vous n’envoyez pas l’ID de session, il n’est pas possible de vérifier la validité de la requête ou de protéger contre les appels malveillants au point de terminaison d’API de votre application Heroku.

On the Heroku side, you can implement the event handler with any open-source web or REST technology. But because the message is in SOAP format, you need to be able to parse the XML. For instance, with JavaScript, Node.js, Express, and the express-xml-bodyparser library, here is an endpoint that handles an outbound message and parses the SOAP message. /Côté Heroku, vous pouvez implémenter le gestionnaire d’événements avec n’importe quelle technologie Web de source ouverte ou REST. Puisque le message se présente sous le format SOAP, vous devez analyser le XML. Par exemple, avec JavaScript, Node.js, Express et la bibliothèque express-xml-bodyparser, voici un point de terminaison qui gère un message sortant et analyse le message SOAP.

 app.post("/new_contact", function(req, res) {
    var notification = req.body["soapenv:envelope"]["soapenv:body"][0]["notifications"][0];
    var sessionId = notification["sessionid"][0];
    var data = {};
    if (notification["notification"] !== undefined) {
      var sobject = notification["notification"][0]["sobject"][0];
      Object.keys(sobject).forEach(function(key) {
        if (key.indexOf("sf:") == 0) {
          var newKey = key.substr(3);
          data[newKey] = sobject[key][0];
        }
      }); // do something #awesome with the data and sessionId
    }
    res.status(201).end();
  }); 

In this example, each time a contact is created, the Heroku app receives the contact details and can do whatever it needs to with the data. /Dans cet exemple, chaque fois qu’un contact est créé, l’application Heroku reçoit les détails du contact et peut traiter librement les données.

Callouts with Apex Triggers /Appels externes avec des déclencheurs Apex

You can define Apex triggers on Salesforce objects to handle any of these events: /Vous pouvez définir des déclencheurs Apex sur des objets Salesforce pour gérer n’importe quel événement suivant :

  • insert /insérer
  • update /mettre à jour
  • delete /supprimer
  • merge /fusionner
  • upsert /mettre à jour/insérer
  • undelete /restaurer

The trigger can use an Apex callout to make a REST JSON call to an endpoint on a Heroku app. For instance, here is an Apex trigger that calls a Heroku app: /Le déclencheur peut utiliser un appel externe Apex pour effectuer un appel JSON REST à un point de terminaison dans l’application Heroku. Par exemple, voici un déclencheur Apex qui appelle une application Heroku :

 trigger NewContactWebhookTrigger on Contact (after insert) {
  String url = 'https://foo.herokuapp.com/new_contact';
  String content = Webhook.jsonContent(Trigger.new, Trigger.old);
  Webhook.callout(url, content);
} 

The referenced Webhook Apex class is: /La classe Apex Webhook référencée est :

 public class Webhook {
  public static String jsonContent(List<Object> triggerNew, List<Object> triggerOld) {
    String newObjects = '[]';
    if (triggerNew != null) {
      newObjects = JSON.serialize(triggerNew);
    }
    String oldObjects = '[]';
    if (triggerOld != null) {
      oldObjects = JSON.serialize(triggerOld);
    }
    String userId = JSON.serialize(UserInfo.getUserId());
    String content = '{"new": ' + newObjects + ', "old": ' + oldObjects + ', "userId": ' + userId + '}';
    return content;
  }
  @future(callout=true) public static void callout(String url, String content) {
    Http h = new Http();
    HttpRequest req = new HttpRequest();
    req.setEndpoint(url);
    req.setMethod('POST');
    req.setHeader('Content-Type', 'application/json');
    req.setBody(content);
    h.send(req);
  }
} 

The jsonContent method takes the trigger data and serializes it into JSON. The callout method makes the HTTP post to Heroku with the JSON payload. /La méthode jsonContent utilise les données du déclencheur pour les sérialiser en JSON. La méthode d’appel externe effectue la publication HTTP dans Heroku avec la charge de travail JSON.

As with outbound messages, you can build the Heroku app with any open-source web or REST technology. With JavaScript, Node.js, and Express, the endpoint could be defined as: /Comme pour les messages sortants, vous pouvez construire l’application Heroku avec n’importe quelle technologie Web de source ouverte ou REST. Avec JavaScript, Node.js et Express, le point de terminaison peut être défini comme suit :

 app.post("/new_contact", function(req, res) {
  // do something with req.body
  res.status(201).end();
}); 

In the request handler, the req.body is the deserialized JSON data sent from the Apex trigger. /Dans le gestionnaire de requêtes, req.body correspond aux données JSON désérialisées envoyées depuis le déclencheur Apex.

With Apex triggers, you can use some form of pre-shared key to authenticate requests, avoiding the potential for malicious requests. You can also have the payload include a session ID to let the Heroku app make REST API requests back to Salesforce to fetch or update data. /Avec des déclencheurs Apex, vous pouvez utiliser une certaine forme de clé pré-partagée pour authentifier les requêtes afin d’éviter le risque de requêtes malveillantes. Vous pouvez également inclure un ID de session dans la charge de travail pour permettre à l’application Heroku d’effectuer des requêtes API REST vers Salesforce afin d’extraire ou de mettre à jour les données.

Resources /Ressources

Leave a Reply

Your email address will not be published. Required fields are marked *