xConnect: Adding interactions in Sitecore 9

Over the course of the last few posts, we’ve done lots of things with xDB using xConnect! But one thing that hasn’t been covered so far is adding an Interaction to a Contact.

Adding an Interaction

Let’s take an example of a customer entering your store and purchasing a product. Here’s how you could register that Outcome event in an Interaction and add it to the Contact.

using (var client = GetClient())
{
    var contactReference = new IdentifiedContactReference("twitter", "longhorntaco");
    var contact = client.Get(contactReference, new ExpandOptions() { FacetKeys = { "Personal" } });

    if (contact != null)
    {
        // Item ID of the "Enter Store" Offline Channel at 
        // /sitecore/system/Marketing Control Panel/Taxonomies/Channel/Offline/Store/Enter store
        var enterStoreChannelId = Guid.Parse("{3FC61BB8-0D9F-48C7-9BBD-D739DCBBE032}"); 
        var userAgent = "xConnectIntro Console App";

        var interaction = new Interaction(contact, InteractionInitiator.Contact, enterStoreChannelId, userAgent);

        var productPurchaseOutcomeId = Guid.Parse("{9016E456-95CB-42E9-AD58-997D6D77AE83}");
        var outcome = new Outcome(productPurchaseOutcomeId, DateTime.UtcNow, "USD", 42.95m);

        interaction.Events.Add(outcome);

        client.AddInteraction(interaction);
        client.Submit();
    }
}

When creating an Interaction, you need to specify the InteractionInitiator. This is an enumeration with the following options: Brand, Contact, or Unknown. If the customer initiated this interaction, choose InteractionInitiator.Contact. If it was an interaction initiated by you (or the Brand), for example, a user registering for an event based off of an e-mail they received from you, you would choose InteractionInitiator.Brand.

It’s that simple! You can any type of event that inherits from Sitecore.XConnect.EventOutcome, Goal or PageViewEvent. You can even create custom Events an add them to the Events collection, but I’ll save that for another post. 🙂

Source code can be found on GitHub.

Happy Sitecore trails, my friend!

Leave a comment