Skip to main content

Publish Order Fulfillment Events

Learning Objectives

After completing this unit, you’ll be able to:

  • Explain the difference between the Publish and PublishStream RPC methods.
  • Use the PublishStream RPC method to publish order fulfillment events.
  • Subscribe to the order fulfillment events.

After the custom order app receives the change event for each closed opportunity, it places an order in an external order system. We don't cover this part because it is outside the scope of this Trailhead module. Once the app receives a notification that the order has been fulfilled, it publishes a platform event back to Salesforce. After the platform event is received, the app updates the opportunity record with the info about the shipped order, such as the shipping tracking number.

There are two methods to publish events.

Publish RPC Method

Use the Publish method if you want to wait for the result of a publish request before sending the next batch of event messages and don’t require high publish rates for large volumes of events. ThePublish method is a unary RPC, which means that it sends only one request and receives only one response. It synchronously publishes the batch of events in PublishRequest. After publishing the event messages, the server sends a response to the client.

The PublishResult in PublishResponse contains an error if the publishing of the event failed. If there is no error, this means that the event publishing was successful and the event is in the event bus. You can retry publishing failed events. For more information, see Publish RPC Method in the Pub/Sub API guide.

PublishStream RPC Method

Use PublishStream to achieve a higher publish rate than with Publish and have a high volume of events. ThePublishStream method uses bidirectional streaming. It can send a stream of publish requests while receiving a stream of publish responses from the server. The server returns a PublishResponse for each PublishRequest when publishing is complete for the batch. It isn’t necessary for a client to wait for a PublishResponse before sending a new PublishRequest. Multiple publish batches can be queued up. This behavior allows for a higher publish rate because a client can asynchronously publish more events while publish operations are still in flight on the server side.

For each batch of events in PublishRequest, the order of results in PublishResponse corresponds to the order of events in the publish request. You can correlate each successful or failed result with the corresponding event in the publish request. The PublishResult in PublishResponse contains an error if the publishing of the event failed. If there is no error, this means that the event publishing was successful and the event is in the event bus. You can retry publishing failed events. For more information, see PublishStream RPC Method in the Pub/Sub API guide.

In this unit, we use the PublishStream RPC method to publish only one event to publish two 'Order Fulfillment' custom platform events, one for each order fulfilled.

Define the Order Fulfillment Event in Setup

First, let's create the 'Order Fulfillment' custom platform event.

  1. From Setup, enter Platform Events in the Quick Find box, then select Platform Events.
  2. On the Platform Events page, click New Platform Event.
  3. For Label, enter Order Fulfillment Event.
  4. For Plural Label, enter Order Fulfillment Events.
  5. If available, enable Starts with vowel sound.
  6. For Description, enter Order events contain order data and are received by order processing apps.
  7. Click Save.
  8. In the Custom Fields & Relationships related list, click New.
  9. Follow the wizard to add these fields.

Field Type

Field Label

Text(18)

Order Id

Text(18)

Tracking Number

Publish Platform Events and Receive Them in the Subscriber

Before you publish events, configure a managed subscription for the Order Fulfillment event. Then use the PublishStream RPC method in the sample Java client to publish two Order Fulfillment events, and receive them in a managed subscription.

Make a Tooling API Call to Create ManagedEventSubscription

  1. Send a POST request to this REST endpoint: /tooling/sobjects/ManagedEventSubscription. In Postman, in the Salesforce Platform APIs collection, expand Event Platform and Managed Event Subscriptions, and then click Create managed event subscription.
Note

If you don't find the Managed Event Subscriptions folder, refresh the collection. Click View more actions (...) next to the collection name, click Pull changes, and in the new tab, click Pull Changes.

  1. Use this request body.
{
  "FullName": "Managed_Sub_Order_Fulfillment_Event",
  "Metadata":
  {
      "label" : "Managed Sub Order Fulfillment Event",
      "topicName" : "/event/Order_Fulfillment_Event__e",
      "defaultReplay": "LATEST",
      "state" : "RUN",
      "errorRecoveryReplay" : "LATEST"
  }
}
  1. Click Send. After you create the ManagedEventSubscription in Tooling API, the response returned contains the ID of the created ManagedEventSubscription record, similar to this response.
{
  "id": "18xak000000XaMTAA0",
  "success": true,
  "errors": [],
  "warnings": [],
  "infos": []
}

Prerequisites

  • Set up and build the pub-sub-api sample Java client by following the steps in the previous unit.

Start the Managed Subscription

  1. In your local pub-sub-api repo, navigate to src/main/resources and open the arguments.yaml file.
  2. In arguments.yaml, keep the configurations you made in the previous unit but the managed subscription developer name to the new managed subscription:
    • MANAGED_SUB_DEVELOPER_NAME: Managed_Sub_Order_Fulfillment_Event
  3. Also, disable change event header argument because it is used only for change events.
    • PROCESS_CHANGE_EVENT_HEADER_FIELDS: false
  4. Save your changes.
  5. In a Terminal window, navigate to the top-level java folder of your repo folder.
  6. To start the managed subscription, enter:./run.sh genericpubsub.ManagedSubscribe
Note

When you create a ManagedEventSubcription, there can be a delay before the new configuration takes effect in Pub/Sub API. If the subscription returns an error saying that the managed subscription configuration isn’t found, wait a little while and subscribe again.

Publish Events

Before publishing events, modify the sample code to specify the event fields to publish and some other configurations.

  1. Open another Terminal window.
  2. Navigate to your local pub-sub-api folder.
  3. In an IDE, such as Visual Studio Code, or a text editor, open java/src/main/java/utility/CommonContext.java.
  4. Get your Salesforce user ID. In your Trailhead Playground, click your profile picture, and then click your name.
  5. From the URL of your profile page, copy the ID value that starts with the 005 prefix. The user ID is at the end of the URL: /User/<User_ID>/view
  6. Modify the createEventMessages(Schema schema, final int numEvents) method. Replace the code with this snippet. Replace the <User_Id> placeholder value for CreatedById with your Salesforce user ID.
public List<GenericRecord> createEventMessages(Schema schema, final int numEvents)
{


    String[] orderNumbers = {"99","100"};
    String[] trackingNumbers = {"123456789ABC", "123456789DEF"};
    



    // Update CreatedById with the appropriate User Id from your org.
    List<GenericRecord> events = new ArrayList<>();
    for (int i=0; i<numEvents; i++) {
        events.add(new GenericRecordBuilder(schema)
                .set("CreatedDate", System.currentTimeMillis())
                .set("CreatedById", "<User_Id>")
                .set("Order_Id__c", orderNumbers[i])
                .set("Tracking_Number__c", trackingNumbers[i])
                .build());
    }


    return events;
}
  1. For the configuration parameters in java/src/main/resources/arguments.yaml, supply these values.
  • TOPIC: /event/Order_Fulfillment_Event__e
  • NUMBER_OF_EVENTS_TO_PUBLISH: 2
  • SINGLE_PUBLISH_REQUEST: true
  1. Because you changed the code, rebuild the client from the top-level java folder with this command: mvn clean install
  2. To run the PublishStream RPC example and publish event messages, from the java folder, enter ./run.sh genericpubsub.PublishStream
  3. Switch back the first terminal window for the subscriber client. The received event looks similar to this example.
Received event:
{
  "CreatedDate": 1719015955500,
  "CreatedById": "005ak000004FkWTAA0",
  "Order_Id__c": "99",
  "Tracking_Number__c": "123456789ABC"
}


Received event:
{
  "CreatedDate": 1719015955500,
  "CreatedById": "005ak000004FkWTAA0",
  "Order_Id__c": "100",
  "Tracking_Number__c": "123456789DEF"
}

Congratulations! You've now learned about Pub/Sub API, managed subscriptions, and how to publish and subscribe to events end to end!

Resources

Share your Trailhead feedback over on Salesforce Help.

We'd love to hear about your experience with Trailhead - you can now access the new feedback form anytime from the Salesforce Help site.

Learn More Continue to Share Feedback