Publish Order Fulfillment Events
Learning Objectives
After completing this unit, you’ll be able to:
- Explain the difference between the
Publish
andPublishStream
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.
- From Setup, enter
Platform Events
in the Quick Find box, then select Platform Events. - On the Platform Events page, click New Platform Event.
- For Label, enter
Order Fulfillment Event
. - For Plural Label, enter
Order Fulfillment Events
. - If available, enable Starts with vowel sound.
- For Description, enter
Order events contain order data and are received by order processing apps.
- Click Save.
- In the Custom Fields & Relationships related list, click New.
- 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
- 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.
- 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" } }
- 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
- In your local
pub-sub-api
repo, navigate tosrc/main/resources
and open thearguments.yaml
file. - 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
- Also, disable change event header argument because it is used only for change events.
PROCESS_CHANGE_EVENT_HEADER_FIELDS: false
- Save your changes.
- In a Terminal window, navigate to the top-level
java
folder of your repo folder. - To start the managed subscription, enter:
./run.sh genericpubsub.ManagedSubscribe
Publish Events
Before publishing events, modify the sample code to specify the event fields to publish and some other configurations.
- Open another Terminal window.
- Navigate to your local
pub-sub-api
folder. - In an IDE, such as Visual Studio Code, or a text editor, open
java/src/main/java/utility/CommonContext.java
. - Get your Salesforce user ID. In your Trailhead Playground, click your profile picture, and then click your name.
- 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
- Modify the
createEventMessages(Schema schema, final int numEvents)
method. Replace the code with this snippet. Replace the<User_Id>
placeholder value forCreatedById
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; }
- 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
- Because you changed the code, rebuild the client from the top-level
java
folder with this command:mvn clean install
- To run the PublishStream RPC example and publish event messages, from the java folder, enter
./run.sh genericpubsub.PublishStream
- 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!