Java bindings for the Intercom API
This project was previously publishing releases to JCenter, which is being retired by JFrog on May 1st 2021.
To allow continued access to past versions, we've migrated them to Maven Central.
We're currently building a new team to provide in-depth and dedicated SDK support.
In the meantime, we'll be operating on limited capacity, meaning all pull requests will be evaluated on a best effort basis and will be limited to critical issues.
We'll communicate all relevant updates as we build this new team and support strategy in the coming months.
The distribution is hosted on mavenCentral. To use the client, you can add the mavenCentral repository to your dependencies.
Add the project declaration to your pom.xml:
<dependency>
<groupId>io.intercom</groupId>
<artifactId>intercom-java</artifactId>
<version>2.8.2</version>
</dependency>Add mavenCentral to your repositories block:
repositories {
mavenCentral()
}and add the project to the dependencies block in your build.gradle:
dependencies {
implementation 'io.intercom:intercom-java:2.8.2'
} Add mavenCentral to your resolvers in your build.sbt:
resolvers +="mavenCentral" at "https://repo1.maven.org/maven2"and add the project to your libraryDependencies in your build.sbt:
libraryDependencies +="io.intercom"%"intercom-java"%"2.8.2"Resources this API supports:
If you already have an access token you can find it here. If you want to create or learn more about access tokens then you can find more info here.
# WithanOAuthorAccesstoken:
Intercom.setToken("da39a3ee5e6b4b0d3255bfef95601890afd80709");If you are building a third party application you can get your OAuth token by setting-up-oauth for Intercom.
// Create a userUseruser = newUser()
.setEmail("malcolm@serenity.io")
.setUserId("1")
.addCustomAttribute(CustomAttribute.newStringAttribute("role", "sergeant"))
.addCustomAttribute(CustomAttribute.newBooleanAttribute("browncoat", true));
Usercreated = User.create(user);
// Find user by iduser = User.find("541a144b201ebf2ec5000001");
// Find user by emailMap<String, String> params = Maps.newHashMap();
params.put("email", "malcolm@serenity.io");
user = User.find(params);
// Find user by user_idparams = Maps.newHashMap();
params.put("user_id", "1");
user = User.find(params);
// Update custom_attributes for a useruser.addCustomAttribute(CustomAttribute.newStringAttribute("role", "captain"));
User.update(user);
// Iterate over all users (up to 10k records, to read all use Scroll API)UserCollectionusers = User.list();
while(users.hasNext()) {
System.out.println(users.next().getUserId());
}
// List users (sorting)Map<String, String> params = Maps.newHashMap();
params.put("sort", "updated_at");
params.put("order", "asc");
UserCollectionusers = User.list(params);
// List users (created within the past X days)Map<String, String> params = Maps.newHashMap();
params.put("created_since", "2");
UserCollectionusers = User.list(params);
// List users by tagMap<String, String> params = Maps.newHashMap();
params.put("tag_id", "12345");
UserCollectionusers = User.list(params);
// List users by segmentMap<String, String> params = Maps.newHashMap();
params.put("segment_id", "1234567890abcdef12345678");
UserCollectionusers = User.list(params);
// Retrieve users via Scroll APIScrollableUserCollectionusersScroll = User.scroll();
List<User> users = usersScroll.getPage();
usersScroll = usersScroll.scroll();
// Archive a user by Intercom IDUseruser = User.find("541a144b201ebf2ec5000001");
User.archive(user.getId());
// Archive a user by user_idMap<String, String> params = Maps.newHashMap();
params.put("user_id", "1");
User.archive(params);
// Archive a user by emailMap<String, String> params = Maps.newHashMap();
params.put("email", "malcolm@serenity.io");
User.archive(params);
// Permanently delete a user by Intercom IDUser.permanentDelete("541a144b201ebf2ec5000001");Contacts were added in version 1.1 of the client.
// Create a ContactContactcontact = newContact()
.setEmail("fantastic@serenity.io")
.addCustomAttribute(newStringAttribute("role", "fence"));
Contactcreated = Contact.create(contact);
// Find a single contact by server supplied user id or idcontact = Contact.findByID("541a144b201ebf2ec5000002");
contact = Contact.findByUserID("e1a7d875-d83a-46f7-86f4-73be98a98584");
// Update a contactcontact.setName("Stitch Hessian");
Contactupdated = Contact.update(contact);
// Update a contact by IDContactcontact = newContact().setID("541a144b201ebf2ec5000002").setName("Stitch Hessian");
Contactupdated = Contact.update(contact);
// Update a contact by User IDContactcontact = newContact().setUserID("e1a7d875-d83a-46f7-86f4-73be98a98584").setName("Stitch Hessian");
Contactupdated = Contact.update(contact);
// Read a contact list by emailContactCollectioncontacts = Contact.listByEmail("jubal@serenity.io");
while(contacts.hasNext()) {
System.out.println(contacts.next());
}
// Iterate over all contacts (up to 10k records, to read all use Scroll API)ContactCollectionallContacts = Contact.list();
while(allContacts.hasNext()) {
System.out.println(allContacts.next());
}
// Retrieve contacts via Scroll APIScrollableContactCollectioncontactsScroll = Contact.scroll();
List<Contact> contacts = contactsScroll.getPage();
contactsScroll = contactsScroll.scroll();
// List contacts (sorting)Map<String, String> params = Maps.newHashMap();
params.put("sort", "created_at");
params.put("order", "asc");
ContactCollectioncontacts = Contact.list(params);
// Remove a contactContact.delete(contact);
// Remove a contact by idContact.delete(contact.getID());
// Remove a contact by user_idContact.deleteByUserID(contact.getUserID());
// Convert a contactUserconverted = Contact.convert(contact, user);// Find visitor by IDVisitorvisitor = Visitor.findByID("5b69565fa737210d1c2127f1");
// Find visitor by User IDVisitorvisitor = Visitor.findByUserID("6a347bc9-0b96-4925-bbbc-1f8b11f94c50");
// Update a visitorVisitorvisitor = Visitor.findByID("5b69565fa737210d1c2127f1");
visitor.setName("Visitor's Name");
Visitor.update(visitor);
// Delete a visitor by IDVisitor.delete("5b69565fa737210d1c2127f1");
// Delete a visitorVisitorvisitor = Visitor.findByUserID("6a347bc9-0b96-4925-bbbc-1f8b11f94c50");
Visitor.delete(visitor);
// Convert a visitor to a leadVisitorvisitor = Visitor.findByUserID("6a347bc9-0b96-4925-bbbc-1f8b11f94c50");
Contactcontact = Visitor.convertToContact(visitor);
// Convert a visitor to a userVisitorvisitor = Visitor.findByUserID("6a347bc9-0b96-4925-bbbc-1f8b11f94c50");
Useruser = newUser();
user.setUserId("1");
UserconvertUser = Visitor.convertToUser(visitor, user);// Create a companyCompanycompany = newCompany();
company.setName("Blue Sun");
company.setCompanyID("1");
company.setMonthlySpend(123.10f);
company.setPlan(newCompany.Plan("premium"));
company.addCustomAttribute(CustomAttribute.newIntegerAttribute("foddstuff-items", 246));
company.addCustomAttribute(CustomAttribute.newStringAttribute("bestseller", "fruity oaty bar"));
Company.create(company);
// Find a company by company_idmap = Maps.newHashMap();
map.put("company_id", "1");
Companycompany = Company.find(map);
// Find a company by namemap = Maps.newHashMap();
map.put("name", "Blue Sun");
Companycompany = Company.find(map);
// Find a company by idCompanycompany = Company.find("541a144b201ebf2ec5000001");
// Update a companycompany.setName("Blue Sun Corporation");
Company.update(company);
// Iterate over all companiesCompanyCollectioncompanies = Company.list();
while(companies.hasNext()) {
System.out.println(companies.next().getName());
}
// Retrieve companies via Scroll APIScrollableCompanyCollectioncompaniesScroll = Company.scroll();
List<Company> companies = companiesScroll.getPage();
companiesScroll = companiesScroll.scroll();
// Get a list of users in a companymap = Maps.newHashMap();
map.put("company_id", "6");
UserCollectionusers = Company.listUsers(map);
// Add a user to one or more companiesUseruser = User.find("541a144b201ebf2ec5000001");
user.addCompany(company);
User.update(user);// Iterate over all adminsAdminCollectionadmins = Admin.list();
while(admins.hasNext()) {
System.out.println(admins.next().getName());
}
// Find admin by IDAdminadmin = Admin.find("123456");
// Set admin as away and enable away mode reassignmentAdminadmin = Admin.setAwayMode("123456", true, true);// Create an event with a user ID// This is only valid for usersEventevent = newEvent()
.setEventName("bought-hat")
.setUserID("1")
.putMetadata("invitee_email", "jayne@serenity.io")
.putMetadata("found_date", System.currentTimeMillis())
.putMetadata("new_signup", true);
Event.create(event);
// Create an event with an email// This is only valid for usersEventevent = newEvent()
.setEventName("bought-hat")
.setEmail("test@example.com");
Event.create(event);
// Create an event with an ID// This is valid for both users and leadsEventevent = newEvent()
.setEventName("bought-hat")
.setId("599d6aeeda850883ed8ba7c2");
Event.create(event);
// List events of a userMap<String, String> params = Maps.newHashMap();
params.put("type", "user");
params.put("user_id", "1");
// Alternatively list by Intercom ID// params.put("intercom_user_id", "541a144b201ebf2ec5000001");// Or by email// params.put("email", "river@serenity.io");EventCollectionevents = Event.list(params);
while (events.hasNext()) {
System.out.println(events.next().getEventName());
}
// List event summaries of a userMap<String, String> params = Maps.newHashMap();
params.put("type", "user");
params.put("user_id", "1");
// Alternatively list by Intercom ID// params.put("intercom_user_id", "541a144b201ebf2ec5000001");// Or by email// params.put("email", "river@serenity.io");EventSummaryCollectioneventSummaryCollection = Event.listSummary(params);
for(EventSummaryeventSummary : eventSummaryCollection.getEventSummaries()){
System.out.println(eventSummary);
}// create a tagTagtag = newTag().setName("alliance");
tag = Tag.create(tag);
// update a tagtag.setName("independent");
tag = Tag.update(tag);
// tag and untag usersUserone = newUser().setEmail("river@serenity.io");
Usertwo = newUser().setEmail("simon@serenity.io").untag();
User.create(one);
User.create(two);
Tag.tag(tag, one, two);
// tag and untag contactsContactcontact1 = Contact.findByID("5ab313046e4997e35bc13e7c");
Contactcontact2 = Contact.findByUserID("697ea3e0-227d-4d70-b776-1652e94f9583").untag();
Tag.tag(tag, contact1, contact2);
// iterate over all tagsfinalTagCollectiontags = Tag.list();
while (tags.hasNext()) {
System.out.println(tags.next().getId());
}
// tag and untag companiesCompanyc1 = newCompany().setCompanyID("1");
Companyc2 = newCompany().setCompanyID("2").untag();
Company.create(c1);
Company.create(c2);
Tag.tag(tag, c1, c2);
// delete a tagTag.delete(tag);// Find a segmentSegmentsegment = Segment.find("1");
// Update a segmentsegment.setName("new name");
Segment.update(segment);
// Iterate over all segmentsSegmentCollectionsegments = Segment.list();
while(segments.hasNext()) {
System.out.println(segments.next().getId());
}// create a user noteUseruser = newUser().setId("5310d8e8598c9a0b24000005");
Authorauthor = newAuthor().setId("1");
Notenote = newNote()
.setUser(user)
.setAuthor(author)
.setBody("The note");
Note.create(note);
// Find a note by idnote = Note.find("1");
// Iterate over all notes for a user via their user_idMap<String, String> params = Maps.newHashMap();
params.put("user_id", "1");
NoteCollectionnotes = Note.list(params);
while(notes.hasNext()) {
System.out.println(notes.next().getBody());
}
// Iterate over all notes for a user via their email addressparams = Maps.newHashMap();
params.put("email", "malcolm@serenity.io");
notes = Note.list(params);
while(notes.hasNext()) {
System.out.println(notes.next().getBody());
}// send a message to a userUseruser = newUser().setId("5310d8e8598c9a0b24000005");
Adminadmin = newAdmin().setId("1");
AdminMessageadminMessage = newAdminMessage()
.setAdmin(admin)
.setUser(user)
.setSubject("This Land")
.setBody("Har har har! Mine is an evil laugh!")
.setMessageType("email")
.setTemplate("plain");
Conversation.create(adminMessage);
// send a message from a userUserMessageuserMessage = newUserMessage()
.setBody("Hey! Is there, is there a reward?")
.setFrom(user);
Conversation.create(userMessage);
// send a message from a contactContactMessagecontactMessage = newContactMessage()
.setBody("Hey! Is there, is there a reward?")
.setFrom(contact);
Conversation.create(contactMessage);
//list all conversationsConversationCollectionconversations = Conversation.list();
while (conversations.hasNext()) {
Conversationconversation = conversations.next();
}
// find admin conversationsMap<String, String> params = Maps.newHashMap();
params.put("type", "admin");
params.put("admin_id", "1");
ConversationCollectionadminConversations = Conversation.list(params);
while (adminConversations.hasNext()) {
Conversationconversation = adminConversations.next();
}
// find user conversationsparams = Maps.newHashMap();
params.put("type", "user");
params.put("user_id", "1");
ConversationCollectionuserConversations = Conversation.list(params);
while (userConversations.hasNext()) {
Conversationconversation = userConversations.next();
}
// find a conversation by idfinalConversationconversation = Conversation.find("66");
ConversationMessageconversationMessage = conversation.getConversationMessage();
ConversationPartCollectionparts = conversation.getConversationPartCollection();
List<ConversationPart> partList = parts.getPage();
for (ConversationPartpart : partList) {
StringpartType = part.getPartType();
Authorauthor = part.getAuthor();
Stringbody = part.getBody();
}
ConversationPartpart = conversation.getMostRecentConversationPart();
Adminassignee = conversation.getAssignee();
Useruser = conversation.getUser();
// Find all open conversations assigned to an admin and render as plaintextparams = Maps.newHashMap();
params.put("type", "admin");
params.put("admin_id", "7");
params.put("display_as", "plaintext");
ConversationCollectionopenForAdmin = Conversation.list(params);
// admin replyAdminadmin = newAdmin().setId("1");
AdminReplyadminReply = newAdminReply(admin);
adminReply.setBody("These apples are healthsome");
adminReply.setAttachmentUrls(newString[]{"http://www.example.com/attachment.jpg"}); // optional - list of attachmentsConversation.reply("66", adminReply);
// admin closeAdminadmin = newAdmin().setId("1");
AdminReplyadminReply = newAdminReply(admin);
adminReply.setMessageType("close");
Conversation.reply("66", adminReply);
// admin snoozeAdminadmin = newAdmin().setId("1");
AdminReplyadminReply = newAdminReply(admin);
adminReply.setSnoozedUntil(1549092382);
Conversation.reply("66", adminReply);
// admin open / unsnoozeAdminadmin = newAdmin().setId("1");
AdminReplyadminReply = newAdminReply(admin);
adminReply.setMessageType("open");
Conversation.reply("66", adminReply);
// user replyUseruser1 = newUser().setId("5310d8e8598c9a0b24000005");
UserReplyuserReply = newUserReply(user1);
userReply.setBody("Mighty fine shindig");
userReply.setAttachmentUrls(newString[]{"http://www.example.com/attachment.jpg"}); // optional - list of attachmentsSystem.out.println(MapperSupport.objectMapper().writeValueAsString(userReply));
Conversation.reply("66", userReply);
// run assignment rulesConversation.runAssignmentRules("19240007891");
// mark conversation as readConversation.markAsRead("66");// create a subscriptionSubscriptionsubscription = newSubscription();
subscription.setUrl(newURI("https://example.org/webhooks/1"));
subscription.addTopic(Subscription.Topic.USER_CREATED);
subscription.addTopic(Subscription.Topic.USER_TAG_CREATED);
Subscription.create(subscription);
// create a subscribtion and subscribe to eventsSubscriptionsubscription = newSubscription();
subscription.addTopic(Subscription.Topic.EVENT_CREATED);
Map<String,ArrayList<String>> metadata = newHashMap<String, ArrayList<String>>();
ArrayList<String> events = newArrayList<String>(Arrays.asList("cart"));
metadata.put("event_names", events);
subscription.setMetadata(metadata);
subscription.setMetadata(metadata);
Subscription.create(subscription);
// update a subscriptionSubscriptionsubscription = Subscription.find("nsub_60ca7690-4020-11e4-b789-4961958e51bd");
subscription.addTopic(Subscription.Topic.COMPANY_CREATED);
SubscriptionupdatedSubscription = Subscription.update(subscription);
// delete a subscriptionSubscriptionsubscription = newSubscription();
subscription.setId("nsub_83793feb-8394-4cb6-91d6-68ef4dd08a8e");
SubscriptiondeletedSubscription = Subscription.delete(subscription);
// find a subscriptionsubscription = Subscription.find("nsub_60ca7690-4020-11e4-b789-4961958e51bd");
// ping a subscription by IDSubscription.ping("nsub_60ca7690-4020-11e4-b789-4961958e51bd");
// ping a subscription by subscription objectsubscription = Subscription.find("nsub_60ca7690-4020-11e4-b789-4961958e51bd");
Subscription.ping(subscription);
// list subscriptionsSubscriptionCollectionlist = Subscription.list();
while(list.hasNext()) {
Subscriptionsub = list.next();
StringappID = sub.getAppID();
StringserviceType = sub.getServiceType();
List<Subscription.Topic> topics = sub.getTopics();
StringhubSecret = sub.getHubSecret();
}
// notification sent feedNotificationCollectionsent = Subscription.sentFeed(subscription.getId());
while(sent.hasNext()) {
Notificationnotification = sent.next();
Stringid = notification.getId();
Stringtopic = notification.getTopic();
NotificationDatadata = notification.getData();
Stringtype = data.getType();
// raw map representation of the payloadMapitem = data.getItem();
}
// notification error feedNotificationErrorCollectionerrors = Subscription.errorFeed(subscription.getId());
while (errors.hasNext()) {
NotificationErrornotificationError = errors.next();
RequestResponseCapturecapture = notificationError.getCapture();
URIrequestURI = capture.getRequestURI();
StringrequestMethod = capture.getRequestMethod();
Map<String, String> requestHeaders = capture.getRequestHeaders();
StringrequestEntity = capture.getRequestEntity();
intstatusCode = capture.getResponseStatusCode();
Map<String, String> responseHeaders = capture.getResponseHeaders();
StringresponseEntity = capture.getResponseEntity();
}
// consume a webhook notificationInputStreamjsonStream = ...;
finalNotificationnotification = Notification.readJSON(jsonStream);
StringjsonString = ...;
finalNotificationnotification = Notification.readJSON(jsonString);// app totalsCounts.Totalstotals = Counts.appTotals();
System.out.println("companies: " + totals.getCompany().getValue());
System.out.println("segments: :" + totals.getSegment().getValue());
System.out.println("tags: :" + totals.getTag().getValue());
System.out.println("users: :" + totals.getUser().getValue());
// conversation totalsCounts.ConversationconversationTotals = Counts.conversationTotals();
System.out.println("assigned: " + conversationTotals.getAssigned());
System.out.println("closed: :" + conversationTotals.getClosed());
System.out.println("open: :" + conversationTotals.getOpen());
System.out.println("unassigned: :" + conversationTotals.getUnassigned());
// admin open/close countsCounts.ConversationadminCounts = Counts.conversationAdmins();
List<Admin> admins = adminCounts.getAdmins();
for (Adminadmin : admins) {
System.out.println(admin.getName() + ": " + admin.getClosed() + ", " + admin.getOpen());
}
// tag user countsSystem.out.println("tag user counts: ");
List<Counts.CountItem> tags = Counts.userTags();
for (Counts.CountItemtag : tags) {
System.out.println(tag.getName()+": " +tag.getValue());
}
// segment user countsList<Counts.CountItem> segments = Counts.userSegments();
for (Counts.CountItemsegment : segments) {
System.out.println(segment.getName()+": " +segment.getValue());
}
// company user countsList<Counts.CountItem> companyUsers = Counts.companyUsers();
for (Counts.CountItemcompany : companyUsers) {
System.out.println(company.getName()+": " +company.getValue());
}
// company tag countsList<Counts.CountItem> companyTags = Counts.companyTags();
for (Counts.CountItemtag : companyTags) {
System.out.println(tag.getName()+": " +tag.getValue());
}To signal local versus remote methods, calls that result in HTTP requests are performed
using static methods, for example User.find(). The objects returned by static methods
are built from server responses. The exception to the static idiom is where the next(),
hasNext() and nextPage() methods on Collections are used to abstract over pagination.
Some API classes have static list() methods that correspond to paginated API responses.
These return a Collection object (eg UserCollection) which can be iterated in two
ways
The collection's
getPage(),hasNextPage()andnextPage()methods - these are useful when you want to fetch one or just a few pages directly.Java's inbuilt iterator methods
next()andhasNext()- these are useful when you want to fetch data without manually handling pagination.User and Contact listing only works up to 10k records. To retrieve all records use the Scroll API via
scroll()
You do not need to deal with the HTTP response from an API call directly.
If there is an unsuccessful response then an IntercomException or a subclass
of IntercomException will be thrown. The exception will have Error objects
that can be examined via getErrorCollection and getFirstError for more detail.
The API throws the following runtime exceptions -
- AuthorizationException: for a 401 or 403 response
- InvalidException: for a 422 response or a local validation failure
- RateLimitException: for a 429 rate limit exceeded response
- ClientException: for a general 4xx response
- ServerException: for a 500 or 503 response
- IntercomException: general exception
The client can be configured to accept any http stack that implements
java.net.HttpURLConnection by implementing the HttpConnectorSupplier
interface.
For example, to use OkHttp as a connection supplier, create a supplier class -
publicclassOkHttpSupplierimplementsHttpConnectorSupplier {
privatefinalOkUrlFactoryurlFactory;
publicOkHttpSupplier(OkUrlFactoryurlFactory) {
this.urlFactory = urlFactory;
}
@OverridepublicHttpURLConnectionconnect(URIuri) throwsIOException {
returnurlFactory.open(uri.toURL());
}
}and hand a supplier to the Intercom object -
finalOkHttpClientclient = newOkHttpClient();
finalOkUrlFactoryfactory = newOkUrlFactory(client);
finalOkHttpSuppliersupplier = newOkHttpSupplier(factory);
Intercom.setHttpConnectorSupplier(supplier);The default connection and request timeouts can be set in milliseconds using the
Intercom.setConnectionTimeout and Intercom.setRequestTimeout methods.
The base URI to target can be changed for testing purposes
URIbaseURI = newURI("https://example.org/server");
Intercom.setApiBaseURI(baseURI);