NAV Navbar

Select Platform

iOS (Swift) Android (Java)

Overview

The SessionM Platform SDK is the enhanced version of the SessionM SDK used by many mobile apps and publishers. The SDK handles all API life-cycle interactions with the SessionM Platform, provides information about interactions with content that is being presented, customer state changes, and pending content and messaging.

The SDK's main areas of focus apply to establishing customer identity, helping you to build useful audience segments, and delivering messages or promotional campaigns. The sections that follow describe some of the general concepts that apply to any SDK undertaking.

You may want to examine the Android and iOS sample applications stored in the following GitHub repositories:

Android Examples
iOS Examples

The applications in these repositories demonstrate how to implement many of the APIs available in the SessionM SDK.

Events

Clients can configure and stream events (previously called "actions") to the platform along with event attributes in order to relay information about customer activity. For example, if a customer buys a particular piece of the client's merchandise, a purchase event could be sent to the platform with an attribute indicating the specific SKU purchased.

Events can be broken into three broad buckets:

Actions and Outcomes

Actions incentivize or track a specific customer activity using a set of events/attributes being streamed to the platform. For example, the client might define an action called "Buy Large Blue T-shirt" using the action and rule builder function in the SessionM Platform UI to select purchase events where the SKU equals that product's SKU.

The SDK is like an analytics package, with which you submit actions (arbitrary text strings) to the SessionM Platform about events of note inside your application. The actions you submit can trigger outcomes, which are triggered responses to a completed actions. The SessionM Platform uses these actions to trigger content displays like presenting in-app messages, targeting push notification campaigns, or simply adding a customer to a segment for later retargeting. You can also create a feed of messages targeted to the customer based on these actions.

Outcomes can enter the customer into sophisticated marketing or experience flows that you define in the SessionM Platform. For example, submitting an action like "customer purchased coffee" might trigger an outcome such as a message thanking the customer for their purchase and promoting a coupon they could use on a return visit. Or, it could trigger an email campaign informing them of their progress towards a free breakfast sandwich.

Notifications and Messaging

In the SDK, developers have fine-grained control over the display of messages. All message displays and content feeds are managed by the developer, and SessionM provides native open source code for implementations of native messaging, activity feeds and other messaging or engagement concepts. The SDK is also developed to handle the lifecycle of rich-media messaging displayed in the context of an in-app WebView.

The SDK offers the following messaging capabilities:

All these messages can further enable a customer to:

Messages, campaigns and promotions are set up in the SessionM Platform. For more information, see your customer success contact.

Earning Incentives

One of the core outcomes to an action is an incentive, which is when something of value is given to a customer for completing an action. Incentive types include points, offers, gift cards, physical prizes, sweepstakes entries or charity donations.

In the SDK, there are a lot of ways for customers to earn incentives.

Campaigns
Within the SessionM Platform, campaigns represent scheduled and targeted customer engagements of any kind: messaging, promotions, coupons, offers, games and display advertising. Customers can participate in campaigns to earn points.

Receipts
The SDK allows customers to upload receipt images representing purchases. Once approved, customers can get incentives.

Loyalty Card Linking
Customers in the US can link their loyalty cards from select retailers and be awarded for buying specific products.

Places
Customers can check into places based on their geolocation to earn incentives.

Geofencing
SDK supports geofencing that allow customers to earn incentives.

Redeeming Rewards or Reward Store Items

Items that can be "purchased" (redeemed for with points or other loyalty currency) in a client's digital rewards store. Reward types largely match incentive types – offers, gift cards, physical prizes, sweepstakes entries or charity donations. In short, you can "redeem" points or some other loyalty currency for a reward in a rewards store.

Developing Mobile Applications with the SDK

This documentation site provides extensive information on all of the APIs the SDK offers to developers building mobile applications that utilize the SessionM Platform. However, implementation details drawn from the most common use cases surfacing in existing SDK implementations are detailed in the SDK Cookbook.

The "General Integration" section within the SDK Cookbook describes the general integration steps necessary to configure SessionM for your application and set up the development environment. Before you begin development using the cookbook as a guide, you may want to review the sections below for some useful, introductory information on Android and iOS implementations.

Android Implementation

The minimum API level for Android development is 16 (Android OS 4.1). Note that SessionM can run in earlier API levels, but it will not function.

For basic information on the latest version of an Android implementation, see the Android 3.0.0 Release Notes.

In addition, SessionM has an open source project that illustrates many of the features of the SDK. The sample project can be found here: Android

iOS Implementation

With respect to iOS implementations, consider the following pre-requisites:

For basic information on the latest version of an iOS implementation, see the iOS 3.0.0 Release Notes.

In addition, SessionM has an open source project that illustrates many of the features of the SDK. The sample project can be found here: iOS

Customers

The APIs featured in this grouping support several different aspects of working with customers engaged with the SessionM Platform, including the following:

Note that, historically, a customer has been referred to as a "user." In fact, many of the objects and methods managing them still contain the term in their names. This documentation site maintains both standards: the term "user" is evident throughout published platform code; and the term "customer" is utilized in conceptual and procedural discussions.

Identity API

The SessionM SDK provides an Identity API that offers a login service which enables customers of a web-based or mobile property to authenticate themselves to the SessionM Platform. Doing so allows them to gain access to their application. The API is based on a set of methods that support SessionM OAuth authentication, which are detailed below.

The workflow typical of establishing a customer's identity involves first creating a customer and then authenticating their login credentials. Subsequently, customers can then be logged in and logged out with ease. The model representing a customer's identity is SMPUser, which is detailed in Customer API section of this site.

SessionM also provides an Identity Plugin for authentication purposes. This allows clients to use an authentication provider which their mobile application can then use to register and authorize users, or customers, in their application. For more information, see the "Identity Plugin" section of the SDK Cookbook.

Bear in mind that customers were previously called "users." As such, both words are used in this documentation site. The term "user" is evident throughout published platform code, while the term "customer" is common in conceptual and procedural discussions.

You may find it helpful to review an Android or iOS sample application that implements this API.

This API provides the following methods for managing customers:

Basic Method

The basic way to call the methods is shown below:

SessionM.getAuthenticationProvider().authenticate("user@sessionm.com", "password", new SessionMOauthProviderIDP.SessionMOauthProviderListener() {
  @Override
  public void onAuthorize(SessionMOauthProviderIDP.AuthenticatedState authenticatedState, SessionMError error) {
      if (error != null) {
        // error processing
      } else {
        // Success processing
      }
  }
});
if let sessionMOAuthProvider = SessionM.authenticationProvider() as? SessionMOAuthProvider {
  sessionMOAuthProvider.authenticateUser(email, password: password) { (state, error) in
    if let error = error {
      // error processing
    } else {
      // Success processing
    }
  }
}

Create a New SessionM Customer

Make a request to create a new customer.

Method

/*!
 @abstract Makes a request to create a new user.
 @param data Required. Data used to create the new account.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func createUser(withData data: SMPUserCreate, completionHandler: @escaping (SMAuthState, SMError?) -> Void)
/**
 * Gets access token from SessionM IdP.  Confirms the token is not expired 1st
 *
 * @param create   {@link SMPUserCreate} is the user to create
 * @param listener {@link SessionMOauthProviderListener} is called with result of create attempt
 * @return {@link SessionMError}
 */
public SessionMError createUser(SMPUserCreate create, SessionMOauthProviderListener listener)


For more information, see the SMPUserCreate Model.

Callback

CompletionHandler: (state: SMAuthState, error: SMError?) -> Void

Notification Name: updatedAuthStateNotification
Notification Data: key: kManagerNotificationData, value: NSNumber (SMAuthState)
/**
  * The SessionMOauthProviderListener is a listener for state changes.
  */
public interface SessionMOauthProviderListener {
  /**
    * On authorize.
    *
    * @param state {@link AuthenticatedState}
    * @param error {@link SessionMError}
    */
    void onAuthorize(AuthenticatedState state, SessionMError error);
}


If an error is returned, see Error Handling for more information. Note, this callback shows the status of an authentication request. If you want to get the current customer, review the Customer API for more information.

SMPUserCreate Model

Attribute java swift Description
externalID String String? External ID of SessionM Platform customer being created.
email String String Email address of SessionM Platform customer being created.
password String String Password of SessionM Platform customer being created.
firstName String String? First name of SessionM Platform customer being created.
lastName String String? Last name of SessionM Platform customer being created.
gender String String? Gender of SessionM Platform customer being created.
dateOfBirth String String? Date of birth of SessionM Platform customer being created.
DMA String String? Designated market area associated with SessionM Platform customer being created.
city String String? City associated with SessionM Platform customer being created.
state String String? State associated with SessionM Platform customer being created.
zipCode String String? Zip code associated with SessionM Platform customer being created.
country String String? Country associated with SessionM Platform customer being created.
locale String String? Locale identifier (e.g. "en-us") for SessionM Platform customer being created.
ipAddress String String? IP address associated with SessionM Platform customer being created.
referral SMPUserReferral SMPUserReferral? Represents another customer's name and referral code, which can be provided by the SessionM Platform customer being created as part of a refer-a-friend program.

SMPUserReferral Model

Attribute java swift Description
referralCode String String A referral code received from a SessionM Platform customer that can be provided when creating or updating another customer account as part of a refer-a-friend program.
source String String? Name of the SessionM Platform customer who provided the referral code.

AuthState Enumeration

SMAuthState Enumeration

java swift Description
Authenticated authenticated User is successfully authenticated.
LoggedOut loggedOut User has successfully logged out and is no longer authenticated.
Failed failed Attempt to authenticate user failed.
Unknown unknown Authentication state is unknown.

Authenticate a Current SessionM Customer with Email

Make a request to authenticate the given customer credentials.

Method

/*!
 @abstract Makes a request to authenticate the given user credentials using the default SessionM Platform identity service provider.
 @param email Required. User's email.
 @param password Required. User's password.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func authenticateUser(withEmail email: String, password: String, completionHandler: @escaping (SMAuthState, SMError?) -> Void)
/**
 * Authenticate a user with email/password for the SessionM IdP.
 *
 * @param email    email address
 * @param password password
 * @param listener {@link SessionMOauthProviderListener} is called with result of authenticate attempt
 * @return {@link SessionMError}
 */
public SessionMError authenticateUser(String email, String password, SessionMOauthProviderListener listener)

Callback

CompletionHandler: (state: SMAuthState, error: SMError?) -> Void

Notification Name: updatedAuthStateNotification
Notification Data: key: kManagerNotificationData, value: NSNumber (SMAuthState)
/**
  * The SessionMOauthProviderListener is a listener for state changes.
  */
public interface SessionMOauthProviderListener {
  /**
    * On authorize.
    *
    * @param state {@link AuthenticatedState}
    * @param error {@link SessionMError}
    */
    void onAuthorize(AuthenticatedState state, SessionMError error);
}


If an error is returned, see Error Handling for more information. Note, this callback shows the status of an authentication request. If you want to get the current customer, review the Customer API for more information.

Authenticate a Current SessionM Customer with Token and Provider

Make a request to authenticate the given customer credentials using a token and a provider. This gives support for 3rd party tokens to be used to authenticate with the SessionM Identity Provider (IDP). An example would be Facebook. The Facebook SDK returns a token. This token and the provider "facebook" are used in this call.

The server will use the token and provider to check with the originating IDP (Facebook) to validate it before creating a SessionM OAuth token. If the user does not exist in the SessionM IDP, it will create the user using the information from the originating IDP.

Adding additional providers requires adding an additional module to the server, so plan ahead if this is a requirement.

Method

/*!
 @abstract Makes a request to authenticate an OAuth token from the given identity service provider.
 @param token Required. Token string from the provider.
 @param provider Required. Used to identify provider for server processing.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func authenticateUser(withToken token: String, provider: String, completionHandler: @escaping (SMAuthState, SMError?) -> Void)
/**
 * Authenticate a user with social token (Google, Facebook, etc.) for the SessionM IdP.
 *
 * @param token    social token
 * @param provider social provider
 * @param listener {@link SessionMOauthProviderListener} is called with result of authenticate attempt
 * @return {@link SessionMError}
 */
public SessionMError authenticateUserWithToken(String token, String provider, SessionMOauthProviderListener listener)

Callback

CompletionHandler: (state: SMAuthState, error: SMError?) -> Void

Notification Name: updatedAuthStateNotification
Notification Data: key: kManagerNotificationData, value: NSNumber (SMAuthState)
/**
  * The SessionMOauthProviderListener is a listener for state changes.
  */
public interface SessionMOauthProviderListener {
  /**
    * On authorize.
    *
    * @param state {@link AuthenticatedState}
    * @param error {@link SessionMError}
    */
    void onAuthorize(AuthenticatedState state, SessionMError error);
}


If an error is returned, see Error Handling for more information. Note, this callback shows the status of an authentication request. If you want to get the current customer, review the Customer API for more information.

Logout Current SessionM Customer

Make a request to log out the current customer. Note that this method has no parameters.

Method

/*!
 @abstract Makes a request to log out the current user.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func logOutUser(completionHandler: @escaping (SMAuthState, SMError?) -> Void)
/**
 * Logout user from SessionM IdP.
 *
 * @param listener {@link SessionMOauthProviderListener}
 */
public void logoutUser(final SessionMOauthProviderListener listener)

Callback

CompletionHandler: (state: SMAuthState, error: SMError?) -> Void

Notification Name: updatedAuthStateNotification
Notification Data: key: kManagerNotificationData, value: NSNumber (SMAuthState)
/**
  * The SessionMOauthProviderListener is a listener for state changes.
  */
public interface SessionMOauthProviderListener {
  /**
    * On authorize.
    *
    * @param state {@link AuthenticatedState}
    * @param error {@link SessionMError}
    */
    void onAuthorize(AuthenticatedState state, SessionMError error);
}


If an error is returned, see Error Handling for more information. Note, this callback shows the status of an authentication request. If you want to get the current customer, review the Customer API for more information.

Out-of-the-Box Web Authorization

The SessionM SDK provides OAuth 2.0 web authorization flow support for the SessionM Platform OAuth identity provider.

Method

/*!
 @abstract Presents an instance of 'SFSafariViewController' (the Safari app is opened instead on iOS 8 devices) that points to a web page where the user's credentials can be authorized.
 @discussion If the authorization is successful, then a request is sent to authenticate the user in the SessionM Platform with the newly authorized access token.
 @param presenting Required. View controller to use to present the 'SFSafariViewController' instance.
 @param completionHandler Required. The block to execute after the authentication request is processed.
 */
open func startWebAuthorization(in presenting: UIViewController, completionHandler: @escaping (SMAuthState, SMError?) -> Void)

/*!
 @abstract Presents an instance of 'SFSafariViewController' (the Safari app is opened instead on iOS 8 devices) that points to a web page where the user's credentials can be authorized (note: does not include automatic code exchange).
 @discussion If the authorization is successful, then an authorization code is passed to the 'completionHandler' block.
 @param presenting Required. View controller to use to present the 'SFSafariViewController' instance.
 @param completionHandler Required. The block to execute after the authentication request is processed.
 */
open func startWebAuthorizationForAuthCode(in presenting: UIViewController, completionHandler: @escaping (SMAuthState, SMError?) -> Void)

/*!
 @abstract Attempts to handle the provided OAuth response redirect URI to continue authorization.
 @discussion A call to this method must be added to your application delegate's 'application:openURL:options:' method to handle OAuth response redirects from 'startWebAuthorizationInViewController:completionHandler:' and 'startWebAuthorizationForAuthCodeInViewController:completionHandler:' method calls.
 @param redirect Required. Potential redirect URI passed to the 'application:openURL:options:' method.
 @result 'Bool' indicating whether the redirect URI was handled.
 */
open func handleOAuthRedirectURI(_ redirect: URL) -> Bool
/**
 * Extended feature: Starts web authorization flow with SessionM Identity Service provider.
 * Make sure to include SessionM WebAuth module before calling this method!!!
 *
 * Default is {@link WebAuthResponseType#AuthCode}
 *
 * @param activity current Activity
 * @param listener {@link SessionMOauthProviderListener} is called with result of authenticate attempt
 * @return Error before starting the web view activity
 */
public SessionMError startWebAuthorization(Activity activity, SessionMOauthProviderListener listener)

/**
 * Extended feature: Starts web authorization flow with SessionM Identity Service provider.
 * Make sure to include SessionM WebAuth module before calling this method!!!
 *
 * Default is {@link WebAuthResponseType#AuthCode}
 *
 * @param activity current Activity
 * @param listener {@link SessionMOauthProviderListener} is called with result of authenticate attempt
 * @return Error before starting the web view activity
 */

public SessionMError startWebAuthorization(Activity activity, WebAuthResponseType webAuthResponseType, SessionMOauthProviderListener listener)

Additional Configuration to Support Web Authorization

You need to add an additional module for this feature.

For Android
  1. Add SessionM WebAuth dependency in your proper build.gradle file:

    dependencies {
        //Required
        compile 'com.sessionm.sdk:sessionm-sdk-webauth:3.0.0
    }
    


  2. Add your redirect scheme in build.gradle file.

    defaultConfig {
      //Required
      manifestPlaceholders = [
      'appAuthRedirectScheme': 'YOUR_REDIRECT_URL_SCHEME' //For example, smpauth://com.sessionm.smp_auth
      ]
    }
    


  3. Add RedirectUriReceiverActivity in AndroidManifest.xml. You can find sample code on our sample project.

    <activity android:name="com.sessionm.webauth.api.RedirectUriReceiverActivity">
        <intent-filter>
            <action android:name="android.intent.action.VIEW"/>
            <category android:name="android.intent.category.DEFAULT"/>
            <category android:name="android.intent.category.BROWSABLE"/>
            <data
                android:host="YOUR_REDIRECT_URL_HOSTNAME"
                android:path="YOUR_REDIRECT_URL_PATH"
                android:scheme="YOUR_REDIRECT_URL_SCHEME"/>
        </intent-filter>
    </activity>
    
For iOS
  1. If using CocoaPods, note that the SessionMWebAuthKit framework is linked automatically if the SessionMSDK pod is specified in your Podfile. SessionMSDK/WebAuth can be specified for finer dependency management.

  2. Add your redirect scheme to your Info.plist file:

    <key>CFBundleURLTypes</key>
        <array>
            <dict>
                <key>CFBundleTypeRole</key>
                <string>Editor</string>
                <array>
                    <string>YOUR_REDIRECT_URL_SCHEME</string>
                </array>
            </dict>
        </array>
    


  3. Add the following code snippet to your ApplicationDelegate.

    // Swift
    func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
      if let provider = SessionM.authenticationProvider() as? SessionMOAuthProvider {
        return provider.handleOAuthRedirectURI(url)
      }
      return false
    }
    

Customer API

The SessionM SDK provides a Customer API with functions for managing customer data. The primary model enabling this work is SMPUser, which contains attributes representing email, name, gender, account status, user state and location.

Once customers are created, authenticated and logged in using the Identity API, you can utilize the methods in this Customer API to fetch and update customer data.

All of the available methods in this API are associated with UserManager (for Android) and SMUserManager (for iOS).

The callbacks associated with these methods return data and are available with UserListener (for Android). Since the iOS delegate has been deprecated, use the methods available with completionHandler or NSNotification instead.

This API provides the following methods for managing customers and their related SMS verifications:

Bear in mind that customers were previously called "users." As such, both words are used in this documentation site. The term "user" is evident throughout published platform code, while the term "customer" is common in conceptual and procedural discussions.

You may find it helpful to review an Android or iOS sample application that implements this API.

Fetch Current SessionM Customer

Fetch current SessionM customer information.

Method

/*!
 @abstract Makes a request to fetch the current user's data.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func fetchUser(completionHandler: @escaping (SMPUser?, Set<String>?, SMError?) -> Void)
/**
 * Fetch user with callback
 *
 * @param listener {@link OnUserFetchedListener}
 * @return {@link SessionMError}
 */
public SessionMError fetchUser(OnUserFetchedListener listener)

Callback

CompletionHandler: (user: SMPUser?, deltas: Set<String>?, error: SMError?) -> Void

Notification Name: updatedUserNotification
Notification Data: key: kManagerNotificationData, value: SMPUser
                   key: kUserDeltas, value: Set<String>
/**
 * Interface for results on calls to {@link #fetchUser(OnUserFetchedListener)}
 */
public interface OnUserFetchedListener  {
    /**
     * On fetched.
     *
     * @param user   the user
     * @param deltas the deltas
     * @param error  {@link SessionMError}
     */
    void onFetched(SMPUser user, Set<String> deltas, SessionMError error);
}


If an error is returned, see Error Handling for more information.

SMPUser Model

Attribute java swift Description
userID String String Identifier of the SessionM Platform customer.
externalID String String? External identifier of the SessionM Platform customer.
availablePoints int Int Points available to the customer.
unclaimedAchievementCount int Int Unclaimed achievement count associated with SessionM Platform customer.
testPoints int Int Test points associated with the SessionM Platform customer.
email String String? Email associated with the SessionM Platform customer.
firstName String String? First name of the SessionM Platform customer.
lastName String String? Last name of the SessionM Platform customer.
gender String String? Gender of the SessionM Platform customer.
dateOfBirth String String? Date of birth of SessionM Platform customer.
createdTime String String? Customer created time in the SessionM Platform system.
updatedTime String String? Customer most recent updated time in SessionM Platform system.
zipCode String String? Zip code associated with SessionM Platform customer.
DMA String String? Designated market area associated with SessionM Platform customer.
state String String? State associated with SessionM Platform customer.
country String String? Country associated with SessionM Platform customer.
latitude double CLLocationDegrees Latitude associated with SessionM Platform customer's physical location.
longitude double CLLocationDegrees Longitude associated with SessionM Platform customer's physical location.
nextTierPercentage double Double Percentage to next tier associated with SessionM Platform customer.
accountStatus AccountStatus SMAccountStatus User account status.
currentZipCode String String? Current zip code associated with SessionM Platform customer, calculated by SessionM platform by user's latest location/zipcode, etc., if applicable.
currentDMA String String? Current designated market area associated with SessionM Platform customer, calculated by SessionM platform by user's latest location/zipcode, etc., if applicable.
currentState String String? Current state associated with SessionM Platform customer, calculated by SessionM platform by user's latest location/zipcode, etc., if applicable.
currentCountry String String? Current country associated with SessionM Platform customer, calculated by SessionM platform by user's latest location/zipcode, etc., if applicable.
proxyIDs ArrayList<String> [String]? Third party identifiers associated with SessionM Platform customer.
userProfile Map<String, Object> [String : NSObject]? Developer-defined attributes that can be used for analytics, targeting ads, etc.
isTestAccount boolean Bool If the customer is a test account in the SessionM Platform.
isSuspended boolean Bool If the customer is suspended in the system.
timestamp long TimeInterval Indicates when the cached user object was last updated.
extras N/A [String : NSObject]? Any data values that do not have an associated class property.

AccountStatus Enumeration

SMAccountStatus Enumeration

java swift Description
GOOD good User is in good standing.
UNKNOWN unknown Account status is unknown.
MULTIPLE_ACCOUNTS_VIOLATION multipleAccountsViolation User has been blocked due to having multiple accounts.
REPORTED_VIOLATION reportedViolation User has been reported as violating the Terms of Service.
REQUESTED_SUSPENSION requestedSuspension User has requested that their account be suspended.
REVIEWED_REPORT reviewedReport User's reported Terms of Service violation has been reviewed by an admin.
TOS_VIOLATION tosViolation User has been blocked due to violating the Terms of Service.
UNVERIFIED unverified User's account has not been verified.
WARNED warned User has been warned for violating the Terms of Service.

Update Current SessionM Customer

Update current SessionM customer.

Method

/*!
 @abstract Makes a request to update the current user's data.
 @param updates Required. Data changes to make.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func updateUser(updates: SMPUserUpdate, completionHandler: @escaping (SMPUser?, Set<String>?, SMError?) -> Void)
/**
 * Update user with listener
 *
 * @param userRequest the user request
 * @param listener    {@link OnUserUpdatedListener}
 * @return {@link SessionMError}
 */
public SessionMError updateUser(SMPUserUpdate userRequest, OnUserUpdatedListener listener)

For more information on the updates/userRequest parameter, see SMPUserUpdate Model.

Callback

CompletionHandler: (user: SMPUser?, deltas: Set<String>?, error: SMError?) -> Void

Notification Name: updatedUserNotification
Notification Data: key: kManagerNotificationData, value: SMPUser
                   key: kUserDeltas, value: Set<String>
/**
 * Interface for results on calls to {@link #updateUser(SMPUserUpdate, OnUserUpdatedListener)}
 */
public interface OnUserUpdatedListener {
    /**
     * On updated.
     *
     * @param user   the user
     * @param deltas the deltas
     * @param error  {@link SessionMError}
     */
    void onUpdated(SMPUser user, Set<String> deltas, SessionMError error);
}


If an error is returned, see Error Handling for more information.

SMPUserUpdate Model

Attribute java swift Description
externalID String String? External ID of SessionM Platform customer being updated.
email String String? Email address of SessionM Platform customer being updated.
firstName String String? First name of SessionM Platform customer being updated.
lastName String String? Last name of SessionM Platform customer being updated.
gender String String? Gender of SessionM Platform customer being updated.
dateOfBirth String String? Date of birth of SessionM Platform customer being updated.
zipCode String String? Zip code associated with SessionM Platform customer being updated.
DMA String String? Designated market area associated with SessionM Platform customer being updated.
state String String? State associated with SessionM Platform customer being updated.
country String String? Country associated with SessionM Platform customer being updated.
locale String String? Locale identifier (e.g. "en-us") for SessionM Platform customer being updated.
latitude double CLLocationDegrees Latitude associated with SessionM Platform customer being updated.
longitude double CLLocationDegrees Longitude associated with SessionM Platform customer being updated.
ipAddress String String? IP address associated with SessionM Platform customer being updated.
userProfile Map<String, Object> [String : NSObject]? Customer profile associated with SessionM Platform customer being updated.
referral SMPUserReferral SMPUserReferral? Represents another customer's name and referral code, which can be provided by the SessionM Platform customer being updated as part of a refer-a-friend program.

Get Cached Current SessionM Customer

Get the current cached object for the current customer. Note that this method has no parameters, and, because it returns a cached customer, it has no callbacks. For information on this object, see SMPUser Model.

Method

/*!
 @property currentUser
 @abstract Returns the currently cached user object.
 @discussion This property is updated in response to a successful 'fetchUserWithCompletionHandler:' or 'updateUser:completionHandler:' call - or to an internal change in the user's points value or authentication state (see 'SessionMOAuthProviderIDP').
 */
open var currentUser: SMPUser? { get }
/**
 * Returns the currently cached user object.
 * This property is updated in response to a successful {@link #fetchUser()} or {@link #updateUser(SMPUserUpdate)} - or to an internal change in the user's points value or authentication state.
 * @return {@link SMPUser} Current cached user.
 */
public SMPUser getCurrentUser()

Customer Tags API

The SessionM SDK provides a Customer Tags API with functions for managing customer tags data. Tags can be used to target customers for specific campaigns.

All of the available methods in this API are associated with UserTagsManager (for Android) and SMUserTagsManager (for iOS).

The callbacks associated with these methods return data and are available with UserTagsListener (for Android). Since the iOS delegate has been deprecated, use the methods available with completionHandler or NSNotification instead.

This API provides the following methods for managing customer tags:

Bear in mind that customers were previously called "users." As such, both words are used in this documentation site. The term "user" is evident throughout published platform code, while the term "customer" is common in conceptual and procedural discussions.

You may find it helpful to review an Android or iOS sample application that implements this API.

Fetch Current SessionM Customer Tags

Fetch current SessionM customer tags information.

Method

/*!
 @abstract Makes a request to fetch the current user's tag data.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func fetchUserTags(completionHandler: @escaping ([String : NSObject]?, SMError?) -> Void)
/**
 * Fetch user tags.
 *
 * @param listener {@link OnUserTagsFetchedListener}
 * @return {@link SessionMError}
 */
public SessionMError fetchUserTags(OnUserTagsFetchedListener listener)

Callback

CompletionHandler: (tags: [String : NSObject]?, error: SMError?) -> Void

Notification Name: fetchedUserTagsNotification
Notification Data: key: kManagerNotificationData, value: [String : NSObject]
/**
 * Interface for results on calls to {@link #fetchUserTags(OnUserTagsFetchedListener)}
 */
public interface OnUserTagsFetchedListener {
    /**
     * On fetched.
     *
     * @param tags  the tags
     * @param error {@link SessionMError}
     */
    void onFetched(Map tags, SessionMError error);
}


If an error is returned, see Error Handling for more information.

Update Current SessionM Customer Tags

Update current SessionM customer tags information.

Method

/*!
 @abstract Makes a request to update the current user's tag data.
 @param updates Required. Data changes to make.
 @param timeToLive Required. How long this change will be in effect on the server.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func updateUserTags(updates: [String], timeToLive: Int, completionHandler: @escaping ([String : NSObject]?, SMError?) -> Void)
/**
 * Update user tags boolean.
 *
 * @param tags     the tags
 * @param listener {@link OnUserTagsUpdatedListener}
 * @return the boolean
 */
public boolean updateUserTags(List<String> tags, OnUserTagsUpdatedListener listener)

Callback

CompletionHandler: (tags: [String : NSObject]?, error: SMError?) -> Void

Notification Name: updatedUserTagsNotification
Notification Data: key: kManagerNotificationData, value: [String : NSObject]
/**
 * Interface for results on calls to {@link #updateUserTags(List, OnUserTagsUpdatedListener)}, {@link #updateUserTags(List, long, OnUserTagsUpdatedListener)}.
 */
public interface OnUserTagsUpdatedListener {
    /**
     * On updated.
     *
     * @param tags  the tags
     * @param error {@link SessionMError}
     */
    void onUpdated(Map tags, SessionMError error);
}


If an error is returned, see Error Handling for more information.

SMS Verification API

The SessionM SDK provides an SMS Verification API with functions for verifying an existing customer's identity using SMS verification capacity.

The general steps for validating an active SessionM customer on a device include:

  1. Request SMS text message be sent.
    The SMS message appears on the customer's phone.

  2. Send verification code to the SessionM server.
    Note that the code entered is the one they received on their phone.

Subsequently, at any time, the system can fetch the current status for the customer's account validation.

All of the available methods in this API are associated with SMSVerificationManager (for Android) and SMSVerificationManager (for iOS).

The callbacks associated with these methods return data and are available with SMSVerificationListener (for Android). Since the iOS delegate has been deprecated, use the methods available with completionHandler or NSNotification instead.

This API provides the following methods for managing customers and their related SMS verifications:

Bear in mind that customers were previously called "users." As such, both words are used in this documentation site. The term "user" is evident throughout published platform code, while the term "customer" is common in conceptual and procedural discussions.

You may find it helpful to review an Android or iOS sample application that implements this API.

Request SMS Text Message

Request SMS text message. This method utilizes the SMSVerification model, which defines attributes that support the SMS verification of a customer before placing an order. Note that the number of verification codes that can be validated is constrained by whatever limit you specify on the SessionM server.

Method

/*!
 @abstract Makes a request to send an SMS verification message to the specified phone number.
 @param phoneNumber Required. The phone number to which the SMS message will be sent.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func sendVerificationMessage(toPhoneNumber phoneNumber: String, completionHandler: @escaping (SMSVerification?, SMError?) -> Void)
/**
 * Send a verification code to user.
 *
 * @param phoneNumber phone number to verify
 * @return boolean if request is sent.
 */
public SessionMError sendSMSVerificationMessage(String phoneNumber, OnSMSVerificationMessageSentListener onSMSVerificationMessageSentListener)

Note that the phone number to verify can be only US/CA numbers with a country code of 1. All supplied numbers must consist of only 10 digits (area code plus the phone number), thus excluding the country code. Formatted examples include: 5556789000, (555)-678-9000, 555-678-9000, (555) 678 9000, 555 678 9000.

Callback

CompletionHandler: (verification: SMSVerification?, error: SMError?) -> Void

Notification Name: sentVerificationMessageNotification
Notification Data: key: kManagerNotificationData, value: SMSVerification
/**
 * Interface for results on calls to {@link #sendSMSVerificationMessage(String)}}
 */
public interface OnSMSVerificationMessageSentListener {
    /**
     * On SMS verification message sent
     *
     * @param smsVerification the sms verification object
     * @param error           {@link SessionMError}
     */
    void onMessageSent(SMSVerification smsVerification, SessionMError error);
}


The platform returns the following error messages for this method:

Code Returned String Reason
sms_limit_reached Reached SMS Limit. Please Contact Customer Support. The phone number provided has reached its daily limit for SMS messages.
sms_invalid_number Invalid Number The phone number provided is not a valid U.S. number.
sms_invalid_device Invalid Device The phone number provided is not associated to a supported device. Only phone numbers to mobile devices are accepted.
sms_not_supported SMS not supported for this number An improper number was supplied and the request failed to send. Numbers not in the US or device is not a mobile device. (Can't be a pager, a landline device, etc.)
sms_service_down Service is down The phone verification service is down.
sms_already_verified N/A Customer trying to re-verify after already verifying.
sms_link_expired N/A Customer must act within timeframe; if they don't, the code or link expires and can't be used.
sms_invalid_code N/A Customer specified wrong code or wrong followed wrong URL.
N/A Reached Identification Limit The customer has exceeded the maximum number of SMS requests allowed.
N/A Reached Max Number of Verifications. Please contact customer support. The phone number has exceeded the maximum number of allowed verifications (phone number already verified and in use).
N/A Missing Phone Number A phone number was not supplied in the request.

For information on generic error messages associated with all SDK methods, see Error Handling for more information.

SMSVerification Model

Attribute java swift Description
verificationID String String Identifier associated with customer being verified.
status SMSVerificationStatus SMSVerificationStatus Current customer SMS verification status.
mode String String? Mode, such as sms.
extras N/A [String : NSObject]? Any data values that do not have an associated class property.

SMSVerificationStatus Enumeration

SMSVerificationStatus Enumeration

java swift Description
PENDING pending SMS message sent; waiting for further action.
VALID valid SMS message sent and verification code submitted correctly; account now verified.
EXPIRED expired SMS message sent but no action taken in the allotted time; code now expired and will need to request another SMS message with new activation code.
INVALID invalid There was an error handling your request.

Check Verification Code

Check code entered by customer. Note that this method makes use of the SMSVerification model, which is detailed in SMSVerification Model.

Method

/*!
 @abstract Makes a request to validate the specified verification code.
 @param code Required. The verification code to validate.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func checkVerificationCode(_ code: String, completionHandler: @escaping (SMSVerification?, SMError?) -> Void)
/**
 * Verify the verification code.
 *
 * @param code verification code that user received.
 * @return if request is sent.
 */
public SessionMError checkSMSVerificationCode(String code, OnSMSVerificationCodeCheckedListener onSMSVerificationCodeCheckedListener)

Callback

CompletionHandler: (verification: SMSVerification?, error: SMError?) -> Void

Notification Name: checkedVerificationCodeNotification
Notification Data: key: kManagerNotificationData, value: SMSVerification
/**
 * Interface for results on calls to {@link #checkSMSVerificationCode(String)}}
 */
public interface OnSMSVerificationCodeCheckedListener {
    /**
     * On code checked.
     *
     * @param smsVerification the sms verification object
     * @param error           {@link SessionMError}
     */
    void onCodeChecked(SMSVerification smsVerification, SessionMError error);
}


If an error is returned, see Error Handling for more information.

Fetch Verification Status

Request customer's current SMS verification information. Note that this method has no parameters, and it makes use of the SMSVerification model, which is detailed in SMSVerification Model.

Method

/*!
 @abstract Makes a request to fetch the current user's verification data.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func fetchVerificationData(completionHandler: @escaping (SMSVerification?, SMError?) -> Void)
/**
 * Returns current user's SMS verification status.
 *
 * @return if request is sent
 */
public SessionMError fetchSMSVerification(OnSMSVerificationFetchedListener onSMSVerificationFetchedListener)

Callback

CompletionHandler: (verification: SMSVerification?, error: SMError?) -> Void

Notification Name: fetchedVerificationDataNotification
Notification Data: key: kManagerNotificationData, value: SMSVerification
/**
 * Interface for results on calls to {@link #fetchSMSVerification()}}
 */
public interface OnSMSVerificationFetchedListener {
    /**
     * On fetched.
     *
     * @param smsVerification the sms verification object
     * @param error           {@link SessionMError}
     */
    void onFetched(SMSVerification smsVerification, SessionMError error);
}


If an error is returned, see Error Handling for more information.

Places API

The SessionM SDK provides a Places API to allow customers to retrieve a list of places, which are physical venues defined with lat/long specifications that can support visualization in a map view. This API also allows customers to check in to their places. Whether done via geofence crossings or manual customer check-ins, this API manages place data that includes customer lat/long coordinates.

The methods presented for the Places API manage objects that represent places. These methods are available with PlacesManager for Android and SMPlacesManager for iOS.

The callbacks associated with these methods return data and are available with PlacesListener for Android. For iOS, the delegate is deprecated. Use methods with completionHandler and/or NSNotification.

This API provides the following methods for fetching or checking in to places:

You may find it helpful to review Android and iOS sample applications that implement this API.

Fetch Places

Fetch a list of places.

Method

/*!
 @abstract Makes a request to update 'places' with venues available for check inside a circle centered at the specified location.
 @param location Required. The center of the circle in which places will be fetched.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func fetchPlaces(near location: CLLocation, completionHandler: @escaping ([SMPlace]?, SMError?) -> Void)

/*!
 @abstract Makes a request to update 'places' with a limited number of venues available for check in inside the circle with the specified radius centered at the specified location.
 @param location Required. The center of the circle in which places will be fetched.
 @param radius Optional. The radius in meters of the circle in which places will be fetched.
 @param limit Optional. The maximum amount of places to fetch.
 @param adUnitID Optional. Fetched places that do not have a bonus opportunity linking to the ad unit with the specified ID will be filtered out. Developers can setup ad units from the Campaigns module in the SessionM Platform portal.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func fetchPlaces(near location: CLLocation, radius: Float, limit: Int32, adUnitID: String?, completionHandler: @escaping ([SMPlace]?, SMError?) -> Void)
/**
 * Fetch places
 *
 * @param location User current location.
 * @param listener {@link OnPlacesFetchedListener}
 * @return {@link SessionMError}
 */
public SessionMError fetchPlaces(Location location, OnPlacesFetchedListener listener)

/**
 * Fetch places based the current location with filter
 * @param location User current location.
 * @param radius   Range of places to fetch.
 * @param limit    Limit of places to fetch.
 * @param adUnitID Filter ad unit ID used to filter places.
 * @param listener {@link OnPlacesFetchedListener}
 * @return {@link SessionMError}
 */
public SessionMError fetchPlaces(Location location, int radius, int limit, String adUnitID, OnPlacesFetchedListener listener)

Callback

CompletionHandler: (places: [SMPlace]?, error: SMError?) -> Void

Notification Name: fetchedPlacesNotification
Notification Data: key: kManagerNotificationData, value: [SMPlace]
/**
 * Interface for callback from methods fetch places}
 */
public interface OnPlacesFetchedListener {
    /**
     * On fetched.
     *
     * @param places {@link List}
     * @param error  {@link SessionMError}
     */
    void onFetched(List<Place> places, SessionMError error);
}


If an error is returned, see Error Handling for more information.

Place Model

SMPlace Model

Attribute java swift Description
placeID String String Place identifier.
name String String? Place name.
checkinStatus CheckinStatus SMCheckinStatus Check in status.
unlockTime long Int Unlocked time to be able to checkin again; time to set checkInStatus to checkable.
distance int Int Distance between place and customer current location.
distanceLabel String String? Label for current distance.
acceptedDistance int Int Accepted distance to checkin to this place.
isPromoted boolean Bool If current place is a promoted place.
points int Int Points to checkin to this place.
iconURL String String? Icon URL.
latitude double CLLocationDegrees Latitude of current place.
longitude double CLLocationDegrees Longitude of current place.
address String String? Street address.
city String String? City name.
state String String? State name.
extras N/A [String : NSObject]? Any data values that do not have an associated class property.

CheckinStatus Enumeration

SMCheckinStatus Enumeration

java swift Description
CHECKABLE checkable Can check in to the place now.
ALREADY_CHECKEDIN_CHECKABLE alreadyCheckedInCheckable Checked in once, but the place supports multiple checkins.
ALREADYCHECKEDIN_TOOFAR alreadyCheckedInTooFar Already checked in to the place, and it is too far from the current location.
BLOCKED_CHECKABLE blockedCheckable Customer is blocked from checking in to the place but it is with in check in radius.
BLOCKED_TOOFAR blockedTooFar Customer is blocked from checking in to the place and it is outside check in radius.
BLOCKED_LIMITHIT blockedLimitHit Customer is blocked from checking in to the place because they reached check in limit.
TOOFAR tooFar Place is too far from the current location.
NOT_CHECKABLE notCheckable Cannot check in to the place now for some other reasons.

Check In to a Place

Check in to a place. This method supports a customer's ability to manually check in to a place. For example, a customer engaging in one of the following activities:

Method

/*!
 @abstract Makes a request to check into the specified place.
 @param place Required. The place to check into.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func checkIntoPlace(_ place: SMPlace, completionHandler: @escaping (SMPlaceCheckinResult?, SMError?) -> Void)
/**
 * Check in
 *
 * @param place    {@link Place}
 * @param listener {@link OnCheckedInListener}
 * @return {@link SessionMError}
 */
public SessionMError checkIn(Place place, OnCheckedInListener listener)


For more information, see Place/SMPlace Model.

Callback

CompletionHandler: (checkin: SMPlaceCheckinResult?, error: SMError?) -> Void

Notification Name: checkedInNotification
Notification Data: key: kManagerNotificationData, value: SMPlaceCheckinResult
/**
 * Interface for callback from methods {@link #checkIn(Place, OnCheckedInListener)}
 */
public interface OnCheckedInListener {
    /**
     * On checked in.
     *
     * @param checkinResult {@link CheckinResult}
     * @param error         {@link SessionMError}
     */
    void onCheckedIn(CheckinResult checkinResult, SessionMError error);
}


If an error is returned, see Error Handling for more information.

CheckinResult Model

SMPlaceCheckinResult Model

Attribute java swift Description
placeID String String Place that was checked in to by a customer.
state String String The state of check in.
message NotificationMessage SMNotificationMessage? Bonus message if available.
canCheckInAgainAt String String? Indicates when place can be checked into again.
extras N/A [String : NSObject]? Any data values that do not have an associated class property.

Get Cached Places

Get a list of cached places. Note that this method has no parameters, and, because it returns a cached list of places, it has no callbacks. For information on the places in the cached list being returned, see Place/SMPlace Model.

Method

/*!
 @property places
 @abstract Places that are available for check in.
 @discussion This property is updated in response to a successful 'fetchPlacesAroundLocation:completionHandler:' or 'fetchPlacesAroundLocation:withRadius:limit:adUnitID:completionHandler:' call.
 */
open var places: [SMPlace] { get }
/**
 * Cached list of latest {@link Place}
 *
 * @return a list of places
 */
public List<Place> getPlaces()

Events API

The SessionM SDK provides an Events API that allows you to fetch the behavior progress for customers or create an event.

Events objects are passed and received using API calls that are immutable. Event builders facilitate building the elements of a request.

All of the available methods in this API are associated with EventsManager (for Android) and SMEventsManager (for iOS).

The callbacks associated with these methods return data and are available with EventsListener (for Android). Since the iOS delegate has been deprecated, use the methods available with completionHandler or NSNotification instead.

Events can carry many different kinds of attributes. To better understand what an event looks like, consider the example shown below:

▿ JSON Request

 {
   "events" : {
    "purchase" : [ {
     "name" : "Burger",
     "amount" : 8.09,
     "qty" : 1,
     "store" : "Demo Vendor"
    },
    {
     "name" : "Lemonade",
     "amount" : 2.8,
     "qty" : 1,
     "store" : "Demo Vendor"
    }]
   }
  }


It contains an event named "purchase" and has two instances of this event; as such, the event is an array of two instances. Each Item (or instance) has a timestamp that is auto-populated, a "qty" attribute that defaults to 1 and a name of store. Note that different types of events have different attributes.

This API provides the following methods for managing events:

In addition to reference information on each of the methods above, this API documentation includes a section detailing the builders available for building an event request and a section that features several event builder samples.

You may find it helpful to review an Android sample application that implements this API.

Fetch Progress for a Customer

Retrieve current status for customer’s campaign behaviors. Note that this method has no parameters.

Method

/*!
 @abstract Makes a request to fetch the latest action item updates.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func fetchBehaviorProgress(completionHandler: @escaping (SMBehaviorProgressFetchedResponse?, SMError?) -> Void)
/**
 * Fetch behavior progress with callback.
 *
 * @param listener {@link OnProgressFetchedListener}
 * @return {@link SessionMError}
 */
public SessionMError fetchBehaviorProgress(OnProgressFetchedListener listener)

Callback

CompletionHandler: (response: SMBehaviorProgressFetchedResponse?, error: SMError?) -> Void

Notification Name fetchedBehaviorProgressNotification
Notification Data: key: kManagerNotificationData, value: SMBehaviorProgressFetchedResponse
/**
 * Interface for results on calls to {@link EventsManager#fetchBehaviorProgress(OnProgressFetchedListener)}.
 */
public interface OnProgressFetchedListener extends SingleCallbackPerMethodFromManager {
    /**
     * On progress fetched.
     *
     * @param response the response
     * @param {@link SessionMError}
     */
    void onProgressFetched(ProgressFetchedResponse response, SessionMError error);
}


If an error is returned, see Error Handling for more information.

The iOS implementation of this method utilizes a block completion handler called FetchBehaviorProgressCompletionHandler.

ProgressFetchedResponse Model

SMBehaviorProgressFetchedResponse Model

Attribute java swift Description
availablePoints int Int Points available to the customer.
behaviors Map<String, Behavior> [String : SMBehavior] Map of behaviors by behavior name.
extras Map<String, Object> [String : NSObject]? Any data values that do not have an associated class property.

Note that this class extends the "EventsResponse" or "SMEventsResponse" model.

Behavior Model

SMBehavior Model

Attribute java swift Description
type BehaviorType SMBehaviorType Behavior types.
campaignID String String Campaign behavior is associated with.
extras Map<String, Object> [String : NSObject]? Any data values that do not have an associated class property.

Note that this is the base class for all behavior classes.

BehaviorType Enumeration

SMBehaviorType Enumeration

java swift Description
Unknown unknown Unknown.
Count count For more information on this type, see the count behavior model.
Unique unique For more information on this type, see the unique behavior model.
Composite composite For more information on this type, see the composite behavior model.

CountBehavior Model

SMCountBehavior Model

Attribute java swift Description
eventName String String Name of event.
currentCount int Int Event count towards completing the associated behavior.
totalCount int Int Event count required for completing the associated behavior.
points int Int Amount of points completing the associated behavior is worth.
achieved int Int Total times the associated behavior has been completed by a given customer.
maxTimesRepeatable int Int Number of times the associated behavior can be achieved by a given customer overall.
maxTimesRepeatablePerPeriod int Int Number of times the associated behavior can be achieved by a customer within a defined period.
period int Int Time period in which you want to count events. For example, 1 day, 1 week, 1 month, 90 days. Specify value in seconds.

Note that this class inherits from the Behavior/SMBehavior class.

UniqueBehavior Model

SMUniqueBehavior Model

Attribute java swift Description
completedUniques List<String> [String] List of completed tasks associated with the behavior's unique set of actions.
points int Int Amount of points completing the associated behavior is worth.
achieved int Int Total times the associated behavior has been completed by a given customer.
maxTimesRepeatable int Int Number of times the associated behavior can be achieved by a given customer overall.
currentCount int Int Event count towards completing the associated behavior.
totalCount int Int Event count required for completing the associated behavior.
data Object Any? The additional data associated with the behavior.

Note that this class inherits from the Behavior/SMBehavior class.

CompositeBehavior Model

SMCompositeBehavior Model

Attribute java swift Description
points int Int Amount of points completing the composite behavior is worth.
achieved int Int Total times the composite behavior has been completed by a given customer.
maxTimesRepeatable int Int Number of times a composite behavior can be achieved by a given customer overall.
maxTimesRepeatablePerPeriod int Int Number of times a composite behavior can be achieved by a customer within a defined period.
period int Int Time period in which you want to count events. For example, 1 day, 1 week, 1 month, 90 days. Specify value in seconds.
goals Map<String, Goal> [String : SMGoal] Specified by goal name. Composite behavior associated with composite action.
groups Map<String, Group> [String : SMGroup] Specified by group ID. Action group associated with composite behavior.

Note that this class inherits from the Behavior/SMBehavior class.

Goal Model

SMGoal Model

Attribute java swift Description
type String String Type of the object (“goal”).
points int Int Amount of points completing the goal is worth.
isCompleted boolean Bool Indicator whether the desired customer action (sometimes referred to as a goal) has been completed.
isRequired boolean Bool Indicator whether the completion of the desired customer action is required to complete the composite action.
groupID String String Index of the group the action belongs to within the composite action.
progress ProgressBehavior SMProgressBehavior Progress towards meeting goal. Value can be either "CountBehavior" or "UniqueBehavior."
extras Map<String, Object> [String : NSObject]? Any data values that do not have an associated class property.

Group Model

SMGroup Model

Attribute java swift Description
type String String Type of the object (“group”).
currentCount int Int Completed goal count within the group.
totalCount int Int Total count required to complete the group.
isCompleted boolean Bool Indicator whether the completion of the desired customer action is required to complete the group.
numberGoals int Int Number of actions within the group.
goals Map<String, Goal> [String : SMGoal] Action associated with group. For more information, see the goal model.
extras Map<String, Object> [String : NSObject]? Any data values that do not have an associated class property.

ProgressBehavior Model

SMProgressBehavior Model

Attribute java swift Description
type BehaviorType SMBehaviorType Behavior types.
campaignID String String Campaign behavior is associated with.
extras Map<String, Object> [String : NSObject]? Any data values that do not have an associated class property.

Note that this class to show composite behaviors and their ability to contain both unique and count behaviors.

Post an Event

Post an event and send an event message to the server to be processed.

Immutable event objects are passed and received using API calls. Event builders facilitate building the elements of a request. For more information, see Build an Event Request.

Method

/*!
 @abstract Makes a request to post the specified event to the SessionM Platform.
 @param event Required. Event data to be posted.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func postEvent(_ event: SMEvent, completionHandler: @escaping (SMEventPostedResponse?, SMError?) -> Void)

/*!
 @abstract Makes a request to post the specified event builder's generated event to the SessionM Platform.
 @param builder Required. The event builder whose generated event will be posted.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func postEvent(from builder: SMEventBuilder, completionHandler: @escaping (SMEventPostedResponse?, SMError?) -> Void)
/**
 * Post Event (or subclass of Event) with callback. By default, event will be sent asap.
 *
 * @param event    the event
 * @param listener {@link OnEventPostedListener}
 * @return the {@link SessionMError}
 */
public SessionMError postEvent(Event event, OnEventPostedListener listener)

Callback

CompletionHandler: (response: SMEventPostedResponse?, error: SMError?) -> Void

Notification Name: postedEventNotification
Notification Data: key: kManagerNotificationData, value: SMEventPostedResponse
/**
 * Interface for results on calls to {@link #postEvent(Event, OnEventPostedListener)}, {@link #postEvent(EventBuilder, OnEventPostedListener)},
 * {@link #postEvent(SimpleEventBuilder, OnEventPostedListener)}, {@link #postEvent(Event, WhenToSend, OnEventPostedListener)},
 * {@link #postEvent(EventBuilder, WhenToSend, OnEventPostedListener)}, and {@link #postEvent(SimpleEventBuilder, WhenToSend, OnEventPostedListener)}
 */
public interface OnEventPostedListener extends SingleCallbackPerMethodFromManager {
    /**
     * On event posted.
     *
     * @param response the response
     * @param {@link SessionMError}
     */
    void onEventPosted(EventPostedResponse response, SessionMError error);
}


If an error is returned, see Error Handling for more information.

Note that the iOS implementation of this method utilizes a block completion handler called PostEventCompletionHandler.

EventsResponse Model

SMEventsResponse Model

Attribute java swift Description
availablePoints int Int Points available to the customer.
behaviors Map<String, Behavior> [String : SMBehavior] Data representing the application's action items and the user's progress towards completing them. Behavior matches fetchBehaviorProgress().
extras Map<String, Object> [String : NSObject]? Any data values that do not have an associated class property.

EventPostedResponse Model

SMEventPostedResponse Model

Attribute java swift Description
notifications List<Notification> [SMEventNotification] Any notifications to be presented to the user as a result of posting the event.
deltas Map [String : NSObject] Any changes to the user's progress towards completing any action items as a result of posting the event.
user User [String : NSObject] Any changes to the user's account status (e.g., point balance or rewards tier) as a result of posting the event.

Note that this class inherits from the EventsResponse/SMEventsResponse class.

Notification Model

SMEventNotification Model

Attribute java swift Description
notificationID String String Unique identifier for the notification.
campaignID String String Unique identifier for the campaign targeted by the event.
notificationType String String Type of notification.
behaviorName String String Name of the behavior associated with the event.
actionType String String? Determines how the content pointed to by 'actionURL' is displayed.
actionURL String String? Notification message URL.
message String String? Notification message body.
payload Object [String : NSObject]? Customer-defined creative content associated with the campaign.
data Object Any? Additional data associated with the notification.
extras Map<String, Object> [String : NSObject]? Any data values that do not have an associated class property.

Build an Event Request

The SessionM Platform provides several different builders for constructing events that can be used in the requests to create new events. The following event builders are discussed in these sections:

Using these builders, you can engage in the following process flow to build an event:

  1. Create an event builder.
  2. Create an event item builder.
  3. Add item(s) to the event.

For more information, see Simple Event sample.

Method for SMEventBuilder:

open class SMEventBuilder : NSObject {
  open class func builder(eventName: String) -> Self
  public init(eventName: String)
  open func build() -> SMEvent

  open var campaignID: String?
  open var permalink: String?

  open func addItem(_ item: SMEventItem)
  open func addItems(_ items: [SMEventItem])

  open func addItem(from builder: SMEventItemBuilder)
  open func addItems(from builders: [SMEventItemBuilder])
Method Signatures for EventBuilder:

interface EventBuilder
  public EventBuilder(String name)
  public Event build()

  public T campaignID(String campaignID)
  public T permalink(String permalink)

  public String getEventName()
  public String getCampaignID()
  public String getPermalink()

  public List<EventItem> getItems()

  public T addItem(EventItem item)
  public T addItems(EventItem... items)
  public T addItems(List<EventItem> items)

  public T addItemBuilder(EventItemBuilder builder)
  public T addItemBuilders(EventItemBuilder... builders)
  public T addItemBuilders(List<EventItemBuilder> builders)

Event Builders

This API exposes the base interface and class for the platform's event builders. Each event builder utilizes the following pattern:
new ActivityEventBuilder(“name”).parm(“howdy”)...build();

Base event builders include:

Method signatures for both of these event builders display in the right-hand column.

Event Type Builders

In addition to the base base event builder, this API provides the following event type builders:

Method for SMActivityEventBuilder:

open class SMActivityEventBuilder : SMEventBuilder
Method Signatures for ActivityEventBuilder:

interface ActivityEventBuilder <- EventBuilder
public ActivityEventBuilder(String name);
Activity Event Builders

This API exposes the interface and class for the platform's activity event builders.

Activity event builders include:

Method signatures for both of these activity event builders display in the right-hand column.

Method for SMPurchaseEventBuilder:

open class SMPurchaseEventBuilder : SMEventBuilder
Method Signatures for PurchaseEventBuilder:

interface PurchaseEventBuilder <- EventBuilder
public PurchaseEventBuilder();
Purchase Event Builders

This API exposes the interface and class for the platform's purchase event builders.

Purchase event builders include:

Method signatures for both of these purchase event builders display in the right-hand column.

Method Signatures for LocationEventBuilder:

interface LocationEventBuilder <- EventBuilder
Location Event Builder

This API exposes the interface for the platform's location event builder. The location event builder is LocationEventBuilder, the Android-Java interface that builds a purchase event.

Method signatures for both of this location event builder displays in the right-hand column.

Event Instance Builders

In addition to the base base event and event type builders, this API provides the following event instance builders:

Method for SMEventItemBuilder:

open class SMEventItemBuilder
open func build() -> SMEventItem
open func setAttribute(value: NSObject?, forKey key: String)
Method Signatures for EventItemBuilder:

public class EventItemBuilder
public EventItemBuilder();
public EventItem build();

public long getTimestamp();

public EventItemBuilder setAttribute(String key, Object value);
public Map<String, Object> getAttributes();
Event Item Builders

This API exposes the base interface and class for the platform's event item builders. Item event builders include:

Method signatures for both of these event item builders display in the right-hand column.

Method for SMActivityEventItemBuilder:

open class SMActivityEventItemBuilder : SMEventItemBuilder
Method Signatures for ActivityItemBuilder:

public class ActivityItemBuilder <- EventItemBuilder
public ActivityItemBuilder();
Activity Event Item Builders

This API exposes the base interfaces for the platform's activity event item builders. Activity item event builders include:

Method signatures for both of these activity event item builders display in the right-hand column.

Method for SMPurchaseEventItemBuilder:

open class SMPurchaseEventItemBuilder :
SMEventItemBuilder
  open var name: String?
  open var parentName: String?
  open var details: String?
  open var time: String?
  open var channel: String?
  open var subChannel: String?
  open var store: String?
  open var postalCode: String?
  open var country: String?
  open var currency: String?
  open var transactionID: String?
  open var transactionType: String?
  open var quantity: Int
  open var price: Int
  open var overridePrice: Int
  open var reloadAmount: Int
  open var reloadType: String?
  open var subtotal: Int
  open var total: Int
Method Signatures for PurchaseEventItemBuilder:

public class PurchaseEventItemBuilder <- EventItemBuilder

  public PurchaseEventItemBuilder();
  public PurchaseEventItem build();

  public PurchaseEventItemBuilder name(String name);
  public PurchaseEventItemBuilder quantity(int quantity);
  public PurchaseEventItemBuilder description(String description);
  public PurchaseEventItemBuilder priceAmount(double priceAmount);
  public PurchaseEventItemBuilder overridePriceAmount(double overridePriceAmount)
  public PurchaseEventItemBuilder currency(String currency);
  public PurchaseEventItemBuilder channel(String channel);
  public PurchaseEventItemBuilder subChannel(String subChannel);
  public PurchaseEventItemBuilder store(String store);
  public PurchaseEventItemBuilder postalCode(String postalCode);
  public PurchaseEventItemBuilder country(String country);
  public PurchaseEventItemBuilder transactionID(String transactionID);
  public PurchaseEventItemBuilder transactionType(String transactionType);
  public PurchaseEventItemBuilder reloadType(String reloadType);
  public PurchaseEventItemBuilder reloadAmount(double reloadAmount);
  public PurchaseEventItemBuilder time(String time);
  public PurchaseEventItemBuilder parentName(String parentName);
  public PurchaseEventItemBuilder subtotalAmount(double subtotalAmount);
  public PurchaseEventItemBuilder amount(double amount);

  public int getQty();
  public String getName();
  public String getDescription();
  public double getPriceAmount();
  public double getOverridePriceAmount();
  public String getCurrency();
  public String getChannel();
  public String getSubChannel();
  public String getStore();
  public String getPostalCode();
  public String getCountry();
  public String getTransactionID();
  public String getTransactionType();
  public String getReloadType();
  public double getReloadAmount();
  public String getTime();
  public String getParentName();
  public double getSubtotalAmount();
  public double getAmount();
Purchase Event Item Builders

This API exposes the classes for the platform's purchase event item builders. Purchase event item builders include:

Method signatures for both of these purchase event item builders display in the right-hand column.

Event Builder Samples

This section contains a selection of event builder samples.

In Java, all of the samples use the following callback listener:

private EventsListener = new EventsListener() {
   @Override public void onProgressFetched(ProgressFetchedResponse response) {// Handle fetch}
   @Override public void onEventPosted(EventPostedResponse response) {// Handle successful event post}
   @Override public void onFailure(SessionMError error) {// Handle Error}
}

Simple Event

The samples featured in this section demonstrate how to create a simple event.

In Swift, a simple event is created as follows:

func simpleEvent() {
   let builder = SMSimpleEventBuilder(eventName: "test_action")
   SMEventsManager.instance().postEvent(builder.build()) { (response, error) in
        if let err = error { }
        // Handle Error
        else if let resp = response {
        // Handle Response
        }
    }
}


In Java, a simple event is created as follows:

public void simpleEvent() {
  _eventsManager.setListener(_listener);
  _eventsManager.postEvent(new EventsManager.SimpleEventBuilder("do_stuff") .addAttribute("by", "3"));
}

Basic Event

The samples featured in this section demonstrate how to create a basic event.

In Swift, a basic event is created as follows:

func basicEvent() {
   let builder = SMActivityEventBuilder(eventName: "test_action")
   builder.addItem(SMActivityEventItemBuilder().build())
   SMEventsManager.instance().postEvent(builder.build())
   {(response, error) in
      if let err = error {// Handle Error}
      else if let resp = response {// Handle Response}
   }
}


In Java, a basic event is created as follows:

public void basicEvent() {
  EventItemBuilder beib = new EventItemBuilder();
  EventBuilder beb = new EventBuilder("do_stuff")
    .addItem(beib.build()
  _eventsManager.setListener(_listener);
  _eventsManager.postEvent(beb.build());
}

Purchase Event

The samples featured in this section demonstrate how to create a purchase event.

In Swift, a purchase event is created as follows:

func purchaseEvent() {
  let itemBuilder = SMPurchaseEventItemBuilder()
  itemBuilder.name = "test_name"
  let builder = SMPurchaseEventBuilder()
  builder.addItem(itemBuilder.build())
  SMEventsManager.instance().postEvent(builder.build()) { (response, error) in
    if let err = error {// Handle Error}
    else if let resp = response {// Handle Response}
  }
}


In Java, a purchase event is created as follows:

public void purchaseEvent() {
    PurchaseEventItemBuilder peib1 = new PurchaseEventItemBuilder().reloadType("first_reload").reloadAmount(11.05);
    PurchaseEventItemBuilder peib2 = new PurchaseEventItemBuilder().name("444905095");
    PurchaseEventBuilder peb1 = new PurchaseEventBuilder().campaignID("820").addItemBuilders(peib1, peib2);
    _eventsManager.setListener(_listener);
    _eventsManager.postEvent(peb1, EventsManager.WhenToSend.ASAP);
}

Campaigns

The APIs featured in this grouping support a few different ways to work with scheduled and targeted customer engagements, or campaigns, being run from the SessionM Platform, including the following:

Campaigns can target specific audience segments, as well as support a set of rules around campaign duration, opt-in requirements, delivery methods, creative assets and desired customer actions.

These campaign APIs operate on the assumption that campaigns are already configured on the platform.

Feed Messages API

The SessionM SDK provides a Feed Messages API for fetching feed messages. Individual messages can be grouped into a feed for visual display to the customer. This is a common UI design pattern in mobile applications and is often called an "Activity Feed."

Each activity feed message is composed of a SMFeedMessage or FeedMessage object, which contains all the data needed to render a UI display to the customer. What the visual display of the message object looks and functions like is entirely up to the developer of the application. The assumption is that they know what is best for their app and can make the best possible decision about when and how to display UI to the customer.

The methods presented for the Feed Messages API manage feed message objects which represent this type of campaign on the SessionM Platform. These methods are available with CampaignsManager for Android and SMCampaignsManager for iOS.

The callbacks associated with these methods return data and are available with CampaignsListener for Android. Since the iOS delegate is deprecated, use method with completionHandler and/or NSNotification.

This API provides the following sections that describe the methods for fetching or getting feed messages:

You may find it helpful to review Android and iOS sample applications that implement this API.

Fetch Feed Messages

Fetch the latest feed messages with default settings, or with customized settings.

Method

/*!
 @abstract Makes a request to update 'feedMessages' with feed message campaigns targeted to the current user's locale (default value is 'SessionM.customLocale' if set and 'Locale.current' otherwise).
 @discussion Note: A cached value for 'feedMessages' will be provided if a fetch request was recently made. Use 'forceFetchFeedMessages(for:completionHandler:)' to force a fetch request to be sent.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func fetchFeedMessages(completionHandler: @escaping ([SMFeedMessage]?, SMError?) -> Void)

/*!
 @abstract Makes a request to update 'feedMessages' with feed message campaigns targeted to the specified locale.
 @discussion Note: A cached value for 'feedMessages' will be provided if a fetch request was recently made. Use 'forceFetchFeedMessages(for:completionHandler:)' to force a fetch request to be sent.
 @param locale Optional. The locale in which the fetch will be restricted.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func fetchFeedMessages(for locale: Locale, completionHandler: @escaping ([SMFeedMessage]?, SMError?) -> Void)

/*!
 @abstract Makes a request to update 'feedMessages' with feed message campaigns targeted to the specified locale.
 @param locale Optional. The locale in which the fetch will be restricted.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func forceFetchFeedMessages(for locale: Locale, completionHandler: @escaping ([SMFeedMessage]?, SMError?) -> Void)
/**
 * Fetch feed messages with callback.
 * If the cached copy and the server are the same, no request will be made and this returns the cached version.
 * Otherwise, a request will be sent to server to get the latest value.
 *
 * Note, if you want to force a real fetch to server, use {@link #forceFetchFeedMessages(Locale, OnMessagesFetchedListener)}}
 *
 * @param onMessagesFetched when feed messages are fetched
 * @return a {@link SessionMError}
 */
public SessionMError fetchFeedMessages(OnMessagesFetchedListener onMessagesFetched)

/**
 * Fetch latest messages with customized Locale and listener.
 * If the cached copy and the server are the same, no request will be made and this returns the cached version.
 * Otherwise, a request will be sent to server to get the latest value.
 *
 * Note, if you want to force a real fetch to server, use {@link #forceFetchFeedMessages(Locale, OnMessagesFetchedListener)}}
 *
 * @param locale            locale of request
 * @param onMessagesFetched when the feed messages fetched
 * @return a {@link SessionMError}
 */
public SessionMError fetchFeedMessages(Locale locale, OnMessagesFetchedListener onMessagesFetched)

/**
 * Force fetch feed messages. This method guarantees the response is always from server with the latest value.
 *
 * @param locale            locale of request
 * @param onMessagesFetched when the feed messages fetched
 * @return a {@link SessionMError}
 */
public SessionMError forceFetchFeedMessages(Locale locale, OnMessagesFetchedListener onMessagesFetched)

Callback

CompletionHandler: (messages: [SMFeedMessage]?, error: SMError?) -> Void

Notification Name: fetchedFeedMessagesNotification
Notification Data: key: kManagerNotificationData, value: [SMFeedMessage]
/**
 * Interface for results on calls to {@link CampaignsManager#fetchFeedMessages(OnMessagesFetchedListener)} and {@link CampaignsManager#fetchFeedMessages(Locale, OnMessagesFetchedListener)}.
 */
public interface OnMessagesFetchedListener {
    /**
     * When FeedMessages have been fetched, or an error occurred.
     *
     * @param messages the messages
     * @param error    the error
     */
    void onFetched(List<FeedMessage> messages, SessionMError error);
}


If an error is returned, see Error Handling for more information.

FeedMessage Model

SMFeedMessage Model

Attribute java swift Description
messageID String String Feed message identifier.
campaignID String String Campaign identifier that the current message belongs to.
header String String The title of the message.
subheader String String? The subtitle of the message.
details String String The detail content of the message.
points int Int The points of the message.
actionType MessageActionType SMMessageActionType Message action type.
actionURL String String? The URL to the displayed activity or the app deeplink URL.
iconURL String String? The URL of the message icon, which is shown either in the notification center or in activity feed.
imageURL String String? The URL of the message image, which is shown either in the notification center as "Rich Notification" or in the activity feed.
startTime String String? The start time of the current campaign.
endTime String String? The end time of the current campaign.
data Map<String, Object> NSObject? All the other extra data for customized message.
extras Map<String, Object> [String : NSObject]? Any data values that do not have an associated class property.

MessageActionType Enumeration

SMMessageActionType Enumeration

java swift Description
DEEP_LINK deepLink Deep links into app.
FULL_SCREEN fullScreen Presents full screen rich media message.
EXTERNAL_LINK externalLink Opens in the native mobile browser or any other apps.
UNKNOWN unknown Unknown action type.

Get Cached Feed Messages

Returns the current cached list of feedMessageData. Note that this method has neither parameters nor a callback. However, for information on the model it returns, see FeedMessage/SMFeedMessage Model.

Method

/*!
 @property feedMessages
 @abstract Feed message campaigns.
 @discussion This property is updated in response to a successful 'fetchFeedMessagesWithCompletionHandler:' or 'fetchFeedMessagesWithLocale:completionHandler:' call.
 */
open var feedMessages: [SMFeedMessage] { get }
/**
 * Returns the current cached list of feed message.
 *
 * @return a list of {@link FeedMessage}
 */
public List<FeedMessage> getFeedMessages()

Inbox API

The SessionM SDK provides an Inbox API for working with inbox messages. These messages can be delivered into an embedded list-view feature in the UI associated with a client's digital property defined for the SessionM Platform.

You can use this API to allow customers to read, engage with and update messages. For example, 3rd party systems can retrieve a list of inbox messages and update their corresponding states (or statuses).

The methods presented for the Inbox API manage objects that represent inbox messages. These methods are available with InboxManager for Android and SMInboxManager for iOS.

The callbacks associated with these methods return data and are available with InboxListener for Android. For iOS, the delegate is deprecated. Use methods with completionHandler and/or NSNotification.

This API provides the following methods for managing inbox messages:

You may find it helpful to review Android and iOS sample applications that implement this API.

Create Inbox Message

Create an inbox message.

Method

/*!
 @abstract Makes a request to create a message with the specified configuration for the current user.
 @param message Required. Message configuration.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func createMessage(_ message: SMNewInboxMessage, completionHandler: @escaping (SMInboxMessage?, SMError?) -> Void)
/**
 * Create an inbox message
 *
 * @param inboxMessage the inbox message
 * @param listener     {@link OnInboxMessageCreatedListener}
 * @return {@link SessionMError}
 */
public SessionMError createInboxMessage(NewInboxMessage inboxMessage, OnInboxMessageCreatedListener listener)

Callback

CompletionHandler: (message: SMInboxMessage?, error: SMError?) -> Void

Notification Name createdMessageNotification
Notification Data: key: kManagerNotificationData, value: SMInboxMessage
/**
 * Interface for results on calls to {@link #createInboxMessage(NewInboxMessage, OnInboxMessageCreatedListener)}
 */
public interface OnInboxMessageCreatedListener {
    /**
     * On created.
     *
     * @param message {@link InboxMessage}
     * @param error   {@link SessionMError}
     */
    void onCreated(InboxMessage message, SessionMError error);
}


If an error is returned, see Error Handling for more information.

NewInboxMessage Model

SMNewInboxMessage Model

Attribute java swift Description
subject String String Message subject.
externalID String String? Developer-defined ID associated with the message.
imageURL String String? URL to image associated with the message.
metadata Map<String, Object> [String : NSObject]? Metadata associated with the message.
data Map<String, Object> [String : NSObject]? Contains optional configuration such as a message body or deep link URL.

Fetch Inbox Messages

Fetch a list of inbox messages for the current customer. Note that this method has no parameters.

Method

/*!
 @abstract Makes a request to update 'inboxMessages' with the current user's inbox messages.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func fetchMessages(completionHandler: @escaping ([SMInboxMessage]?, SMError?) -> Void)
/**
 * Fetch inbox messages.
 *
 * @param listener {@link OnInboxMessagesFetchedListener}
 * @return {@link SessionMError}
 */
public SessionMError fetchInboxMessages(OnInboxMessagesFetchedListener listener)

Callback

CompletionHandler: (messages: [SMInboxMessage]?, error: SMError?) -> Void

Notification Name: fetchedMessagesNotification
Notification Data: key: kManagerNotificationData, value: [SMInboxMessage]
/**
 * Interface for results on calls to {@link #fetchInboxMessages(OnInboxMessagesFetchedListener)}
 */
public interface OnInboxMessagesFetchedListener {
    /**
     * On fetched.
     *
     * @param inboxMessages {@link List}
     * @param error         {@link SessionMError}
     */
    void onFetched(List<InboxMessage> inboxMessages, SessionMError error);
}


If an error is returned, see Error Handling for more information.

InboxMessage Model

SMInboxMessage Model

Attribute java swift Description
messageID String String Inbox identifier.
externalID String String? Inbox external identifier.
type String String? Type of message, inbox.
subject String String? Subject of the message.
imageURL String String? URL to any associated image in the message.
createdTime String String? Created time for current inbox message.
expiresTime String String? Expiration time for current inbox message.
state InboxMessageState SMInboxMessageState Indicates the state of the inbox message.
metadata String String? Any additional metadata (key-value pairs) to add to the message; supports use of rich display.
data Object [String : NSObject]? Body of the message specified in the body attribute.
extras Map<String, Object> [String : NSObject]? Any data values that do not have an associated class property.

InboxMessageState Enumeration

SMInboxMessageState Enumeration

java swift Description
NEW new Message is newly created.
READ read Message has been read.
DELETED deleted Message has been deleted.
UNKNOWN unknown Message has been deleted.

Get Cached Inbox Messages

Get a list of cached inbox messages.

This method has no parameters, and it requires no callback since it returns a cached list of inbox messages. You may want to consult the InboxMessage/SMInboxMessage Model for details on the model represented in the list of inbox messages returned by this method.

Method

/*!
 @property inboxMessages
 @abstract The current user's inbox messages.
 @discussion This property is updated in response to a successful 'fetchInboxMessagesWithCompletionHandler:' call.
 */
open var inboxMessages: [SMInboxMessage] { get }
/**
 * Gets cached inbox message list.
 *
 * @return List of {@link InboxMessage}
 */
public List<InboxMessage> getInboxMessages()

Update State of Inbox Messages

Change the state of an inbox message. These methods support the modification of inbox message state by specifying:

State can be changed to new, read or deleted.

Passing in the Message and State

Modifying the state of a message by passing in the message.

Method
/*!
 @abstract Makes a request to update the specified message with the specified state.
 @param message Required. The message to be updated.
 @param state Required. The new message state.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func updateMessage(_ message: SMInboxMessage, toState state: SMInboxMessageState, completionHandler: @escaping ([SMInboxMessage]?, SMError?) -> Void)
/**
 * Update inbox message state (Preferred)
 *
 * @param message  the message
 * @param state    the state
 * @param listener {@link OnInboxMessagesStateUpdatedListener}
 * @return {@link SessionMError}
 */
public SessionMError updateInboxMessageState(InboxMessage message, InboxMessage.STATE_TYPES state, OnInboxMessagesStateUpdatedListener listener)


For information on the state parameter, see the InboxMessageState/SMInboxMessageState enumeration.

Callback
CompletionHandler: (messages: [SMInboxMessage]?, error: SMError?) -> Void

Notification Name: updatedMessagesNotification
Notification Data: key: kManagerNotificationData, value: [SMInboxMessage]
/**
 * Interface for results on calls to {@link #updateInboxMessagesState(List, InboxMessage.STATE_TYPES, OnInboxMessagesStateUpdatedListener)},
 * {@link #updateInboxMessageState(InboxMessage, InboxMessage.STATE_TYPES, OnInboxMessagesStateUpdatedListener)},
 * {@link #updateInboxMessageState(String, InboxMessage.STATE_TYPES, OnInboxMessagesStateUpdatedListener)}.
 */
public interface OnInboxMessagesStateUpdatedListener {
    /**
     * On state updated.
     *
     * @param messages {@link List}
     * @param error    {@link SessionMError}
     */
    void onStateUpdated(List<InboxMessage> messages, SessionMError error);
}


If an error is returned, see Error Handling for more information.

You may also want to consult InboxMessage/SMInboxMessage Model for details on the model represented in the list of inbox messages returned by this method.

Passing in the Message ID and State

Modifying the state of a single message by passing in the message's ID.

Note that this method shares a callback with the method that passes in the message being updated, which is detailed in the callback section for Passing in the Message and State. For information on the messages it returns, see InboxMessage/SMInboxMessage Model.

Method
/*!
 @abstract Makes a request to update the message with the specified identifier with the specified state.
 @param messageID Required. The identifier of the message to be updated.
 @param state Required. The new message state.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func updateMessage(havingID messageID: String, toState state: SMInboxMessageState, completionHandler: @escaping ([SMInboxMessage]?, SMError?) -> Void)
/**
 * Update inbox message state
 *
 * @param inboxMessageID the inbox message id
 * @param state          the state
 * @param listener       {@link OnInboxMessagesStateUpdatedListener}
 * @return {@link SessionMError}
 */
public SessionMError updateInboxMessageState(final String inboxMessageID, InboxMessage.STATE_TYPES state, OnInboxMessagesStateUpdatedListener listener)


For information on the state parameter, see the InboxMessageState/SMInboxMessageState enumeration.

Passing in Multiple IDs for the Messages

Modifying the state of multiple messages by passing in their IDs.

Note that this method shares a callback with the method that passes in the message being updated, which is detailed in the callback section for Passing in the Message and State. For information on the messages it returns, see InboxMessage/SMInboxMessage Model.

Method
/*!
 @abstract Makes a request to update the messages with the specified identifiers with the specified state.
 @param messageIDs Required. The identifiers of the messages to be updated.
 @param state Required. The new message state.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func updateMessages(havingIDs messageIDs: [String], toState state: SMInboxMessageState, completionHandler: @escaping ([SMInboxMessage]?, SMError?) -> Void)
/**
 * Update inbox messages.
 *
 * @param messageIDs {@link List}
 * @param state      {@link InboxMessage.STATE_TYPES}
 * @param listener   {@link OnInboxMessagesStateUpdatedListener}
 * @return {@link SessionMError}
 */
public SessionMError updateInboxMessagesState(List<String> messageIDs, InboxMessage.STATE_TYPES state, OnInboxMessagesStateUpdatedListener listener)


For information on the state parameter, see the InboxMessageState/SMInboxMessageState enumeration.

Push Notifications

For push notifications from the platform to your application, SessionM provides methods that handle the message, prepare the SMNotificationMessage object and present the notification for display. For more information, see the "Push Notification" section within the SDK Cookbook.

In addition, you may find it helpful to review Android and iOS sample applications that implement this API.

Geofences

The SessionM SDK supports logic that signals the server when a customer crosses a defined geofence that is associated with a campaign's targeted location, or venue. The SDK can trigger campaign messaging based on these signals.

For more information, see the "Geofence" section within the SDK Cookbook.

Loyalty

The APIs featured in this grouping support several different ways to incentivize customers to stay engaged with long-term and expanding customer loyalty programs. Using these APIs, you can manage some of the entities most critical to running loyalty programs from the SessionM Platform, including the following:

Offers API

Offers are digital coupons for predetermined deals. For instance, if a client sells clothing, an offer could be “15% off any sweater” or “a free t-shirt.” The methods presented for the Offers API support a few different functions for fetching, purchasing and claiming offers.

Generally, the typical workflow for SDK implementations utilizing this API's methods follows:

  1. Fetch the store offers available for purchase by the user.
  2. The user purchases an offer.
  3. Fetch the offer purchased by the user.
  4. Claim the offer at a Point of Sale system.

All of the available methods are associated with OffersManager (for Android) and SMOffersManager (for iOS).

The callbacks associated with these methods return data and are available with OffersListener (for Android); in iOS blocks are used.

This API provides a collection of methods that do the following:

You may find it helpful to review an Android or iOS sample application that implements this API.

Fetch Store Offers

Retrieves store offers available for purchase by the user. This method has no parameters.

Method

/*!
 @abstract Makes a request to fetch loyalty offers available for purchase.
 @discussion Note: A cached value for 'fetchStoreOffersResponse' will be provided if a fetch request was recently made. Use 'forceFetchStoreOffers(completionHandler:)' to force a fetch request to be sent.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func fetchStoreOffers(completionHandler: @escaping (SMStoreOffersFetchedResponse?, SMError?) -> Void)

/*!
 @abstract Makes a request to fetch loyalty offers available for purchase.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func forceFetchStoreOffers(completionHandler: @escaping (SMStoreOffersFetchedResponse?, SMError?) -> Void)
/**
 * Fetch latest Offers User can purchase.
 * If the cached copy and the server are the same, no request will be made and this returns the cached version.
 * Otherwise, a request will be sent to server to get the latest value.
 *
 * Note, if you want to force a real fetch to server, use {@link #forceFetchStoreOffers(OnStoreOffersFetched)}
 * Callback {@link OffersListener#onStoreOffersFetched(StoreOffersFetchedResponse)}
 *
 * @param listener {@link OnStoreOffersFetched}
 * @return {@link SessionMError}
 */
public SessionMError fetchStoreOffers(OnStoreOffersFetched listener)

/**
 * Force fetch latest Offers User can purchase. This method guarantees the response is always from server with the latest value.
 *
 * Callback {@link OffersListener#onStoreOffersFetched(StoreOffersFetchedResponse)}
 *
 * @return {@link SessionMError}
 */
public SessionMError forceFetchStoreOffers(OnStoreOffersFetched listener)

Callback

CompletionHandler: (response: SMStoreOffersFetchedResponse?, error: SMError?) -> Void

Notification Name: fetchedStoreOffersNotification
Notification Data: key: kManagerNotificationData, value: SMStoreOffersFetchedResponse
/**
 * Interface for callback from methods {@link #fetchStoreOffers(OnStoreOffersFetched)}
 */
public interface OnStoreOffersFetched {
    /**
     * On fetched.
     *
     * @param offersStore {@link StoreOffersFetchedResponse}
     * @param error       {@link SessionMError}
     */
    void onFetched(StoreOffersFetchedResponse offersStore, SessionMError error);
}


If an error is returned, see Error Handling for more information.

StoreOffersFetchedResponse Model

SMStoreOffersFetchedResponse Model

Attribute java swift Description
offers List<StoreOfferItem> [SMStoreOfferItem] Offer items returned in result.
offerGroups List<OfferGroup> [SMOfferGroup] Offer groups associated with offer items in result.
offerCategories List<OfferCategory> [SMOfferCategory] Offer categories associated with offer items in result.

This model extends the "OffersResponse" or "SMOffersResponse" model.

StoreOfferItem Model

SMStoreOfferItem Model

Attribute java swift Description
offerID String String Unique identifier for store offer item.
quantity int Int Number of individual instances of store offer items available for purchase.
price double Double Price of store offer item.
isVerificationRequired boolean Bool Indicates whether customer verification is required prior to purchasing store offer item.
weight int Int Sorting position among all store offer items.

This model extends the "OfferItem" or "SMOfferItem" model.

Purchase Store Offer

Spends user points to buy a store offer.

Method

/*!
 @abstract Makes a request to purchase the loyalty offer with the specified offer identifier.
 @param offerID Required. The identifier for the offer that will be purchased.
 @param quantity Required. The amount of individual instances of the offer that will be purchased.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func purchaseOffer(havingID offerID: String, quantity: Int, completionHandler: @escaping (SMOfferPurchasedResponse?, SMError?) -> Void)
/**
 * Purchase offer
 *
 * @param offerID  {@link String}
 * @param quantity int
 * @param listener {@link OnOfferPurchased}
 * @return {@link SessionMError}
 */
public SessionMError purchaseOffer(String offerID, int quantity, OnOfferPurchased listener)

Callback

CompletionHandler: (response: SMOfferPurchasedResponse?, error: SMError?) -> Void

Notification Name: purchasedOfferNotification
Notification Data: key: kManagerNotificationData, value: SMOfferPurchasedResponse
/**
 * Interface for callback from methods {@link #purchaseOffer(String, int, OnOfferPurchased)}
 */
public interface OnOfferPurchased {
    /**
     * On purchased.
     *
     * @param purchase {@link OfferPurchasedResponse}
     * @param error    {@link SessionMError}
     */
    void onPurchased(OfferPurchasedResponse purchase, SessionMError error);
}


If an error is returned, see Error Handling for more information.

Offer Purchase Response Model

Customers served by the Offers API are represented in Android by the OfferPurchasedResponse data model and in iOS by the SMOfferPurchasedResponse data model. Callbacks return a response object that models information about the user's offer purchases and is described by attributes detailed in the following table:

This model extends the "OffersResponse" or "SMOffersResponse" model.

OfferPurchasedResponse Model

SMOfferPurchasedResponse

Attribute java swift Description
userOffer UserOfferItem SMUserOfferItem User's purchased offer items returned in result.
pointsRemaining int Int User's remaining point balance after purchasing offer item.
isSuccessful boolean Bool Indicates whether offer item was purchased successfully.

Fetch User Offers

Retrieves offers that were purchased by the user. These fetched user offers have a different expiration date than the store offers discussed for fetchStoreOffers(). This method has no parameters.

Method

/*!
 @abstract Makes a request to fetch loyalty offers that have been purchased by the current user.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func fetchUserOffers(completionHandler: @escaping (SMUserOffersFetchedResponse?, SMError?) -> Void)
/**
 * Fetch user offers
 *
 * @param listener {@link OnUserOffersFetched}
 * @return {@link SessionMError}
 */
public SessionMError fetchUserOffers(OnUserOffersFetched listener)

Callback

CompletionHandler: (response: SMUserOffersFetchedResponse?, error: SMError?) -> Void

Notification Name: fetchedUserOffersNotification
Notification Data: key: kManagerNotificationData, value: SMUserOffersFetchedResponse
/**
 * Interface for callback from methods {@link #fetchUserOffers(OnUserOffersFetched)}
 */
public interface OnUserOffersFetched {
    /**
     * On fetched.
     *
     * @param userOffers {@link UserOffersFetchedResponse}
     * @param error      {@link SessionMError}
     */
    void onFetched(UserOffersFetchedResponse userOffers, SessionMError error);
}


If an error is returned, see Error Handling for more information.

UserOffersFetchedResponse Model

SMUserOffersFetchedResponse Model

This model extends the "OffersResponse" or "SMOffersResponse" model.

Attribute java swift Description
userOffers List<UserOfferItem> [SMUserOfferItem] User's purchased offer items returned in result.
offerGroups List<OfferGroup> [SMOfferGroup] Offer groups associated with the offer items in the result.
offerCategories List<OfferCategory> [SMOfferCategory] Offer categories associated with offer items in result.
totalPoints int Int Total number of points spent by user.
availablePoints int Int User's remaining point balance.

Claim User Offer

Claims a user offer. Retrieves information on a user offer so it can be claimed via a Point of Sale system that can accept it.

Method

/*!
 @abstract Makes a request to claim the loyalty offer with the specified user offer identifier.
 @param userOfferID Required. The user-specific identifier for the purchased offer that will be claimed.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func claimUserOffer(havingID userOfferID: String, completionHandler: @escaping (SMUserOfferClaimedResponse?, SMError?) -> Void)
/**
 * Claim user offer
 *
 * @param userOfferID {@link String}
 * @param listener    {@link OnUserOfferClaimed}
 * @return {@link SessionMError}
 */
public SessionMError claimUserOffer(String userOfferID, OnUserOfferClaimed listener)

Callback

CompletionHandler: (response: SMUserOfferClaimedResponse?, error: SMError?) -> Void

Notification Name: claimedUserOfferNotification
Notification Data: key: kManagerNotificationData, value: SMUserOfferClaimedResponse
/**
 * Interface for callback from methods {@link #claimUserOffer(String, OnUserOfferClaimed)}.
 */
public interface OnUserOfferClaimed {
    /**
     * On claimed.
     *
     * @param claimedResult {@link UserOfferClaimedResponse}
     * @param error         {@link SessionMError}
     */
    void onClaimed(UserOfferClaimedResponse claimedResult, SessionMError error);
}


If an error is returned, see Error Handling for more information.

UserOfferClaimedResponse Model

SMUserOfferClaimedResponse Model

This model extends the "OffersResponse" or "SMOffersResponse" model.

Attribute java swift Description
claimedOffer ClaimedOfferItem SMClaimedOfferItem User's claimed offer item returned in the result.

ClaimedOfferItem Model

SMClaimedOfferItem Model

Attribute java swift Description
code String String User's redeemable 6-digit code used to redeem the offer item.
codeImageURI String String The URI that points to barcode image representing user’s 6-digit code. User can redeem offer item with code.
codeCreationTime String Date The date time on server when 6-digit code and barcode were created.
codeExpirationTime String Date The date time at which user’s 6-digit code expires and can no longer be used to redeem offer item.

Note that this model extends the "UserOfferItem" or "SMUserOfferItem" model.

Common Data Models for Offers

Many of the offers-related data models discussed in this documentation, inherit attributes from these other, common, models:

OfferItem Model

SMOfferItem Model

Attribute java swift Description
name String String Name of the offer item.
details String String Offer item description.
terms String String Terms of service for offer item.
media List<OfferMedia> SMOfferMedia Media content items applicable to offer item.
offerGroupID String String Identifier for offer group to which offer item belongs.
offerType String String Description of the offer item's offer type (e.g., "fixed_amount_discount" or "percent_discount").
startDate String Date Indicates when offer item becomes available for purchase.
endDate String Date? Date after which offer item no longer is available for purchase.
isRedeemable boolean Bool Indicates whether offer item can currently be redeemed.
extras Map<String, Object> [String : NSObject]? Any data values that do not have an associated class property.

UserOfferItem Model

SMUserOfferItem Model

Attribute java swift Description
userOfferID String String Unique identifier for user's instance of purchased offer item.
offerID String String Unique identifier that refers back to associated store offer item.
acquireDate String Date Indicates when offer item was purchased by user.
expirationDate String Date? Date after which offer item can no longer be redeemed by user.
redeemDate String Date? Indicates when offer item was redeemed by user.

Note that this model extends the "OfferItem" or "SMOfferItem" model.

OfferGroup Model

SMOfferGroup Model

Attribute java swift Description
offerGroupID String String Unique identifier of offer group.
name String String Offer group name.
sortOrder int Int Sort order when this offer group is displayed in a list with other groups.
extras Map<String, Object> [String : NSObject]? Any data values that do not have an associated class property.

OfferCategory Model

SMOfferCategory Model

Attribute java swift Description
offerCategoryID String String Unique identifier for offer category.
name String String Offer category name.
offerTypes List<String> [String] Offer types applicable to category.
sortOrder int Int Sorting position among all offer categories.
extras Map<String, Object> [String : NSObject]? Any data values that do not have an associated class property.

OfferMedia Model

SMOfferMedia Model

Attribute java swift Description
offerMediaID String String Unique identifier for offer media content.
offerCategoryID String String Identifier for category to which media content belongs.
categoryName String String Name of offer category to which media content belongs.
uri String String URI of media content.
contentType int Int Type of media content pointed to by URI. Values include: 0 for "Unknown"; 1 for "Image"; 2 for "Video"; 4 for "Audio"; and 5 for "Web Link".
extras Map<String, Object> [String : NSObject]? Any data values that do not have an associated class property.

OffersResponse Model

SMOffersResponse Model

Attribute java swift Description
extras Map<String, Object> [String : NSObject]? Any data values that do not have associated class properties.

Transactions API

Query points transactions for a specific customer.

The methods presented for the Transactions API allow you to query points transactions. All of the available methods are associated with TransactionsManager (for Android) and SMTransactionsManager (for iOS).

The callbacks associated with these methods return data and are available with TransactionsListener (for Android). Since the iOS delegate has been deprecated, use the methods available with completionHandler or NSNotification instead.

This API provides a collection of methods that do the following:

You may find it helpful to review Android and iOS sample applications that implement this API.

Fetch Transactions

Fetch a list of transactions. This method pulls data for only the last 30 days.

Method

/*!
 @abstract Makes a request to update 'transactions' with the current user's points transactions.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func fetchTransactions(completionHandler: @escaping ([SMTransaction]?, Bool, SMError?) -> Void)
/**
 * Fetch transactions
 *
 * @param listener {@link OnTransactionsFetchedListener}
 * @return {@link SessionMError}
 */
public SessionMError fetchTransactions(OnTransactionsFetchedListener listener)

Callback

CompletionHandler: (transactions: [SMTransaction]?, hasMore: Bool, error: SMError?) -> Void

Notification Name: fetchedTransactionsNotification
Notification Data: key: kManagerNotificationData, value: [SMTransaction]
/**
 * Interface for callback from methods {@link #fetchTransactions(OnTransactionsFetchedListener)}
 */
public interface OnTransactionsFetchedListener {
    /**
     * On fetched.
     *
     * @param transactions {@link List}
     * @param hasMore      boolean
     * @param error        {@link SessionMError}
     */
    void onFetched(List<Transaction> transactions, boolean hasMore, SessionMError error);
}


If an error is returned, see Error Handling for more information.

Transaction Model

SMTransaction Model

Attribute java swift Description
recordID String String Unique identifier for transaction record.
balance int Int Points balance after the transaction.
date String String Transaction date.
details String String Detail descriptions of the transactions.
points int Int Points credited or debited.
recordModelID String String? Associated ID for corresponding receipt submission result or loyalty card transaction.
transaction TransactionKind SMTransactionKind Indicates type of transaction.
source TransactionSource SMTransactionSource Indicates the source of points awarded in the transaction.
type TransactionPointsType SMTransactionPointsType Indicates the type of points awarded in the transaction.
extras N/A [String : NSObject]? Any data values that do not have an associated class property.

TransactionKind Enumeration

SMTransactionKind Enumeration

java swift Description
DEBIT debit User lost points from the transaction.
CREDIT credit User earned points from the transaction.
UNKNOWN unknown Transaction kind is unknown.

TransactionSource Enumeration

SMTransactionSource Enumeration

java swift Description
UNKNOWN unknown Transaction source is unknown.
ACHIEVEMENT achievement Points were earned by claiming an achievement.
CONTEST contest Points were earned or lost from a contest.
SPONSOR sponsor Points were earned by engaging with sponsored content.
MERCHANT_REWARDS merchantRewards Points were earned or lost from a loyalty rewards program transaction.
ENTERPRISE enterprise Points were earned through a server-to-server API call.
COMP comp Points were given to user as compensation.
USED used points were lost from making a rewards store purchase.

TransactionPointsType Enumeration

SMTransactionPointsType Enumeration

java swift Description
UNKNOWN unknown Transaction points type is unknown.
DONATION donation A donation was made.
SWEEPSTAKES sweepstakes A sweepstakes was won or entered.
MERCHANDISE merchandise Merchandise from a loyalty rewards program was purchased.
DIGITAL digital A digital reward was purchased from the rewards store.
PHYSICAL physical A physical reward was purchased from the rewards store.
RECEIPT receipt Points were earned from a receipt capture campaign.
LOYALTY_CARD loyaltyCard Points were earned from a loyalty card transaction.
ACHIEVEMENT N/A Achievement type.
HISTORICAL historical Indicates that the transaction data was migrated into the SessionM Platform from an external rewards system.

Fetch Transactions with Parameters

Fetch a list of transactions using a set of available parameters.

Note that this method shares a callback with the method that fetches transactions, which is detailed in the callback section for Fetch Transactions. For information on the transactions it returns, see Transaction/SMTransaction Model.

Method

/*!
 @abstract Makes a request to update 'transactions' with a limited number of the current user's points transactions that took place between the specified start and end dates.
 @param startDate Optional. Transactions after this date will not be fetched.
 @param endDate Optional. Transactions before this date will not be fetched.
 @param limit Optional. The maximum amount of transactions to fetch.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func fetchTransactions(from startDate: Date?, to endDate: Date?, limit: Int32, completionHandler: @escaping ([SMTransaction]?, Bool, SMError?) -> Void)
/**
 * Fetch a list of {@link Transaction} with params.
 *
 * @param startDate default now
 * @param endDate   default startData - 1 month
 * @param limit     default 1000, max 1000
 * @param listener  {@link OnTransactionsFetchedListener}
 * @return {@link SessionMError}
 */
public SessionMError fetchTransactions(Date startDate, Date endDate, int limit, OnTransactionsFetchedListener listener)

Fetch More Transactions

Fetch more transactions if possible. Note that this method contains no parameters. However, it does share a callback with the method that fetches transactions, which is detailed in the callback section for Fetch Transactions. For information on the transactions it returns, see Transaction/SMTransaction Model.

Method

/*!
 @abstract Makes a request to update 'transactions' with points transactions that were not included in the previous fetch.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func fetchMoreTransactions(completionHandler: @escaping ([SMTransaction]?, Bool, SMError?) -> Void)
/**
 * Fetch more transactions.
 *
 * @param listener {@link OnTransactionsFetchedListener}
 * @return {@link SessionMError}
 */
public SessionMError fetchMoreTransactions(OnTransactionsFetchedListener listener)

Get Cached Transactions

Fetch a list of cached transactions.

This method has no parameters, and it requires no callback since it returns a cached list of transactions. You may want to consult Transaction/SMTransaction Model for details on the model represented in the list of transactions returned by this method.

Method

/*!
 @property transactions
 @abstract The current user's points transactions.
 @discussion This property is updated in response to a successful 'fetchTransactionsWithCompletionHandler:', 'fetchTransactionsWithStartDate:endDate:limit:completionHandler:' or 'fetchMoreTransactionsWithCompletionHandler:' call.
 */
open var transactions: [SMTransaction] { get }
/**
 * Returns cached transactions list.
 *
 * @return a list of {@link Transaction}
 */
public List<Transaction> getTransactions()

Referrals API

Referrals provide the means to run a refer-a-friend program. These programs must be set up initially in the platform before you can begin using the SDK's Referrals API to fetch or send a referral.

Each referral is defined by a referrer and at least one referee. A referrer is an existing SessionM customer that wants to notify other people about a promotion; a referee is the person (or people) receiving the referral. The SessionM SDK currently works only with the referrer, fetching and sending their referrals.

A referral object, which is returned by the fetch and send methods, specifies the referrer, along with a variety of attributes, including their email, telephone number, and the name of their associated referee(s).

The SDK can send a referral via an email or an SMS message. Both types of communication can provide the person receiving the referral (known as a referee) a URL or a code they can use to access and activate the referral.

The methods presented for the Referrals API allow you to send referrals and retrieve their associated status/details. All of the available methods are associated with ReferralsManager (for Android) and SMReferralsManager (for iOS).

The callbacks associated with these methods return data and are available with ReferralsListener (for Android). Since the iOS delegate has been deprecated, use the methods available with completionHandler or NSNotification instead.

This API provides a collection of methods that do the following:

You may find it helpful to review Android and iOS sample applications that implement this API.

Fetch Referrals

Fetch a list of sent referrals. Returned object includes multiple attributes. These include basic data such as the referrer's email or phone, as well as attributes describing the referral's status and time-related data about the lifecycle of the referral itself. For more information on these attributes, see the Referral/SMReferral Model.

Method

/*!
 @abstract Makes a request to update 'referrals' with the current user's referrals.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func fetchReferrals(completionHandler: @escaping ([SMReferral]?, SMError?) -> Void)
/**
 * Fetch referrals
 *
 * @param listener {@link OnReferralsFetchedListener}
 * @return {@link SessionMError}
 */
public SessionMError fetchReferrals(OnReferralsFetchedListener listener)

Callback

CompletionHandler: (referrals: [SMReferral]?, error: SMError?) -> Void

Notification Name: fetchedReferralsNotification
Notification Data: key: kManagerNotificationData, value: [SMReferrals]
/**
 * Interface with callback from methods {@link #fetchReferrals(OnReferralsFetchedListener)}, {@link #fetchReferralWithID(String, OnReferralsFetchedListener)}
 */
public interface OnReferralsFetchedListener {
    /**
     * On fetched.
     *
     * @param referrals {@link List}
     * @param error     {@link SessionMError}
     */
    void onFetched(List<Referral> referrals, SessionMError error);
}


If an error is returned, see Error Handling for more information.

Referral Model

SMReferral Model

Attribute java swift Description
referralID String String Referral identifier.
referee String String? Referee name/ID for greeting.
referrer String String? Name of person who sent the referral.
email String String? Referee email.
phoneNumber String String? Referee phone number.
origin String String? Referral origin.
source String String? Referral source.
pendingTime String String? Start time for pending status.
engagedTime String String? Start time for engaged status.
registeredTime String String? Start time for registered status.
convertedTime String String? Start time for converted status.
voidedTime String String? Start time for voided status.
clientData String Any? Code client data.
conversionPoints int Int Points awarded for conversion.
status ReferralStatus SMReferralStatus Indicates the status of the referral.
extras N/A [String : NSObject]? Any data values that do not have an associated class property.

ReferralStatus Enumeration

SMReferralStatus Enumeration

java swift Description
PENDING pending Referral is pending engagement by the referee.
ENGAGED engaged Referee engaged with the referral.
REGISTERED registered Referee registered an account.
CONVERTED converted Referrer received loyalty points for the referral.
LIMIT_PERIOD limitPeriod Referrer reached the referral limit for the current period - conversion will award 0 loyalty points.
LIMIT_LIFETIME limitLifetime Referrer reached the lifetime referral limit - conversion will award 0 loyalty points.
VOIDED voided Referral was voided due to referee registering for an account through other means.
UNKNOWN unknown Referral status is unknown.

Fetch a Single Referral

Fetch a single referral with referral ID. The referral object returned includes multiple attributes about the referral. Note that this method shares a callback with the method that fetches referrals, which is detailed in the callback section for Fetch Referrals. For information on the referrals it returns, see Referral/SMReferral Model.

Method

/*!
 @abstract Makes a request to fetch the referral with the specified identifier.
 @param referralID Required. The identifier of the referral to be fetched.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func fetchReferral(havingID referralID: String, completionHandler: @escaping (SMReferral?, SMError?) -> Void)
/**
 * Fetch referral with id
 *
 * @param referralID the referral id
 * @param listener   {@link OnReferralsFetchedListener}
 * @return {@link SessionMError}
 */
public SessionMError fetchReferralWithID(String referralID, OnReferralsFetchedListener listener)

Get Cached Referrals

Get a list of cached referrals along with their attributes. This method has no parameters, and it requires no callback since it returns a cached list of referrals. You may want to consult Referral/SMReferral Model for details on the model represented in the list of referrals returned by this method.

Method

/*!
 @property referrals
 @abstract Referrals that have been sent by the current user.
 @discussion This property is updated in response to a successful 'fetchReferralsWithCompletionHandler:' call.
 */
open var referrals: [SMReferral] { get }
public List<Referral> getReferrals()

Send Referrals

Send referrals. The SDK can send a referral via an email or an SMS message. Both types can provide the person receiving the referral (known as a referee) a URL or a code they can use to access and activate the referral.

This method presumes that the referral already exists in the system. Once sent, this method's associated callbacks can provide information on the status of the referral, including errors about any limits pertaining to the referral or the email account used to send it.

Method

/*!
 @abstract Makes a request to send the specified referrals.
 @param referrals Required. The referrals request to be sent.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func sendReferrals(_ referrals: SMReferralsRequest, completionHandler: ([SMReferral]?, [SMReferralError]?, SMError?) -> Void)
/**
 * Send referrals
 *
 * @param referralRequest {@link ReferralRequest}
 * @param listener        {@link OnReferralsSentListener}
 * @return {@link SessionMError}
 */
public SessionMError sendReferrals(ReferralRequest referralRequest, OnReferralsSentListener listener)


For more information on the referrals or referralRequest parameter, see the ReferralRequest/SMReferralRequest Model section below.

ReferralRequest Model

SMReferralRequest Model

Attribute java swift Description
email String String Referee email.
name String String? Name of person being referred.
phoneNumber String String? Referee phone number.
origin String String? Referral origin.
source String String? Referral source.
clientData String Any? Code client data.

Callback

CompletionHandler: (successfulReferrals: [SMReferral]?, referralErrors: [SMReferralError]?, error: SMError?) -> Void

Notification Name: sentReferralsNotification
Notification Data: key: kManagerNotificationData, value: [SMReferral]
                   key: kReferralErrors, value: [SMReferralError]
/**
 * Interface with callback from methods  {@link #sendReferrals(ReferralRequest, OnReferralsSentListener)}
 */
public interface OnReferralsSentListener {
    /**
     * On sent.
     *
     * @param successfulReferrals {@link List}
     * @param referralErrors      {@link List}
     * @param error               {@link SessionMError}
     */
    void onSent(List<Referral> successfulReferrals, List<ReferralError> referralErrors, SessionMError error);
}


Failures associated with this callback for sending referrals can be from one of the following conditions:

See Error Handling for more information.

You may also want to consult Referral/SMReferral Model for details on the model represented in the list of referrals returned by this method.

Loyalty Card Linking API

This API allows a 3rd party system to link loyalty cards to retailers.

The methods presented for the Loyalty Card Linking API facilitate the fetching of both retailers and loyalty card as well as linking/unlinking loyalty cards to retailers. These methods are available with LoyaltyCardsManager for Android and SMLoyaltyCardsManager for iOS.

The callbacks associated with these methods return data and are available with LoyaltyCardsListener for Android. For iOS, the delegate is deprecated. Use methods with completionHandler and/or NSNotification.

This API provides the following methods for work with loyalty cards and retailers:

You may find it helpful to review Android and iOS sample applications that implement this API.

Fetch Retailers

Fetch a list of retailers. Zip code is optional; otherwise, all retailers are returned.

Method

/*!
 @abstract Makes a request to update 'retailers' with retailers for which a user can link a loyalty card.
 @discussion Note: A cached value for 'retailers' will be provided if a fetch request was recently made. Use 'forceFetchRetailers(inZipCode:completionHandler:)' to force a fetch request to be sent.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func fetchRetailers(completionHandler: @escaping ([SMRetailer]?, SMError?) -> Void)

/*!
 @abstract Makes a request to update 'retailers' with retailers in the specified zip code for which a user can link a loyalty card.
 @discussion Note: A cached value for 'retailers' will be provided if a fetch request was recently made. Use 'forceFetchRetailers(inZipCode:completionHandler:)' to force a fetch request to be sent.
 @param zipCode Optional. Zip code in which to search for retailers.
 @param completionHandler Required.The block to execute after the request is processed.
 */
open func fetchRetailers(inZipCode zipCode: String, completionHandler: @escaping ([SMRetailer]?, SMError?) -> Void)

/*!
@abstract Makes a request to update 'retailers' with retailers in the specified zip code for which a user can link a loyalty card.
@param zipCode Optional. Zip code in which to search for retailers.
@param completionHandler Required.The block to execute after the request is processed.
*/
open func forceFetchRetailers(inZipCode zipCode: String, completionHandler: @escaping ([SMRetailer]?, SMError?) -> Void)
/**
 * Fetch retailers with listener. The SDK will decide if the offers are changes from the server.
 * If the cached copy and the server are the same, no request will be made and this returns the cached version.
 * Otherwise, a request will be sent to server to get the latest value.
 *
 * Note, if you want to force a real fetch to server, use {@link #forceFetchRetailers(String, OnRetailersFetchedListener)}
 *
 * @param listener {@link OnRetailersFetchedListener}
 * @return {@link SessionMError}
 */
public SessionMError fetchRetailers(OnRetailersFetchedListener listener)

/**
 * Fetch retailers with zipcode and listener. The SDK will decide if the offers are changes from the server.
 * If the cached copy and the server are the same, no request will be made and this returns the cached version.
 * Otherwise, a request will be sent to server to get the latest value.
 *
 * Note, if you want to force a real fetch to server, use {@link #forceFetchRetailers(String, OnRetailersFetchedListener)}
 *
 * @param zipCode  the zip code
 * @param listener {@link OnRetailersFetchedListener}
 * @return {@link SessionMError}
 */
public SessionMError fetchRetailers(String zipCode, OnRetailersFetchedListener listener)

/**
 * Force fetch retailers. This method guarantees the response is always from server with the latest value.
 *
 * @param zipCode  the zip code
 * @param listener {@link OnRetailersFetchedListener}
 * @return {@link SessionMError}
 */
public SessionMError forceFetchRetailers(String zipCode, OnRetailersFetchedListener listener)

Callback

CompletionHandler: (retailers: [SMRetailer]?, error: SMError?) -> Void

Notification Name: fetchedRetailersNotification
Notification Data: key: kManagerNotificationData, value: [SMRetailer]
/**
 * Interface with callback from methods {@link #fetchRetailers(OnRetailersFetchedListener)}, {@link #fetchRetailers(String, OnRetailersFetchedListener)}
 */
public interface OnRetailersFetchedListener {
    /**
     * On fetched.
     *
     * @param retailers the retailers
     * @param error     {@link SessionMError}
     */
    void onFetched(List<Retailer> retailers, SessionMError error);
}


The following table details this method's error:

Error for Callback

Code Reason
invalid zip code Zip code is invalid; must be 5 digits long.

For more information, see Error Handling.

Retailer Model

SMRetailer Model

Attribute java swift Description
retailerID String String Retailer ID.
name String String? Retailer name.
card String String? Loyalty card name.
icon String String? URL of retail icon.
image String String? URL of retail image.
isLinked boolean Bool Specifies if loyalty card is linked.
extras N/A [String : NSObject]? Any data values that do not have an associated class property.

Get Cached Retailers

Gets a list of cached retailers. Note that this method has no parameters, and, because it returns a cached list of retailers, it has no callbacks. For information on the retailers in the cached list it returns, see Retailer/SMRetailer Model.

Method

/*!
 @property retailers
 @abstract The retailers for which a user can link a loyalty card.
 @discussion This property is updated in response to a successful 'fetchRetailersWithCompletionHandler:' or 'fetchRetailersWithZipCode:completionHandler:' call.
 */
open var retailers: [SMRetailer] { get }
/**
 * Gets a list of cached {@link Retailer}.
 */
public List<Retailer> getRetailers()

Links a loyalty card to a retailer. Data associated with this method utilizes the LoyaltyCard/SMLoyaltyCard Model.

Method

/*!
 @abstract Makes a request to link a loyalty card issued by the specified retailer with the specified card number.
 @param cardNumber Required. Loyalty card number.
 @param retailerID Required. ID of retailer that issued the loyalty card.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func linkCard(havingNumber cardNumber: String, retailerID: String, completionHandler: @escaping (String?, SMError?) -> Void)
/**
 * Link loyalty card
 *
 * @param cardNumber the card number
 * @param retailerID the retailer id
 * @param listener   {@link OnLoyaltyCardLinkedListener}
 * @return OnLoyaltyCardTransactionsFetchedListener
 */
public SessionMError linkLoyaltyCard(String cardNumber, String retailerID, OnLoyaltyCardLinkedListener listener)

Callback

CompletionHandler: (cardNumber: String?, error: SMError?) -> Void

Notification Name: linkedCardNotification
Notification Data: key: kManagerNotificationData, value: String
/**
 * Interface with callback from methods {@link #linkLoyaltyCard(String, String, OnLoyaltyCardLinkedListener)}
 */
public interface OnLoyaltyCardLinkedListener {
    /**
     * On linked.
     *
     * @param cardNumber the card number
     * @param error      {@link SessionMError}
     */
    void onLinked(String cardNumber, SessionMError error);
}


The following table details this method's errors:

Errors for Callback

Code Reason
loyalty_card parameter missing Required parameters not sent in.
Retailer code is invalid Retailer code is missing an associated retailer program.
One card per customer/retailer limit Exceeds one card value for each retailer code and customer pairing.
card_value, can’t be blank Card value parameter required; can't be blank.
card_value, not recognized Card value not recognized in any retailer program.
card_value, Card Linked To Another User Card linked to another customer for the same retailer code.

For more information, see Error Handling.

Unlink a loyalty card from a retailer. Data associated with this method utilizes the LoyaltyCard/SMLoyaltyCard Model.

Method

/*!
 @abstract Makes a request to unlink the loyalty card with the specified loyalty card ID.
 @param cardID Required. The unique ID of the loyalty card to unlink.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func unlinkCard(havingID cardID: String, completionHandler: @escaping (SMError?) -> Void)
/**
  * Unlink loyalty card
  *
  * @param cardID   the card id
  * @param listener {@link OnLoyaltyCardUnlinkedListener}
  * @return OnLoyaltyCardTransactionsFetchedListener
  */
public SessionMError unlinkLoyaltyCard(String cardID, OnLoyaltyCardUnlinkedListener listener)

Callback

CompletionHandler: (error: SMError?) -> Void

Notification Name: unlinkedCardNotification
Notification Data: N/A
/**
 * Interface with callback from methods {@link #unlinkLoyaltyCard(String, OnLoyaltyCardUnlinkedListener)}
 */
public interface OnLoyaltyCardUnlinkedListener {
    /**
     * On unlinked.
     *
     * @param error {@link SessionMError}
     */
    void onUnlinked(SessionMError error);
}


The following table details this method's error:

Error for Callback

Code Reason
Card not found Card link ID not found.

For more information, see Error Handling.

Fetch Linked Cards

Fetch a list of linked cards. This method has no parameters.

Method

/*!
 @abstract Makes a request to fetch the current user's linked loyalty cards.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func fetchLinkedCards(completionHandler: @escaping ([SMLoyaltyCard]?, SMError?) -> Void)
/**
 * Fetch linked cards
 *
 * @param listener {@link OnLoyaltyCardsFetchedListener}
 * @return {@link SessionMError}
 */
public SessionMError fetchLinkedCards(OnLoyaltyCardsFetchedListener listener)

Callback

CompletionHandler: (cards: [SMLoyaltyCard]?, error: SMError?) -> Void

Notification Name: fetchedLinkedCardsNotification
Notification Data: key: kManagerNotificationData, value: [SMLoyaltyCard]
/**
 * Interface with callback from methods {@link #fetchCardTransactions(int, int, OnLoyaltyCardTransactionsFetchedListener)}
 */
public interface OnLoyaltyCardsFetchedListener {
    /**
     * On fetched.
     *
     * @param cards the cards
     * @param error {@link SessionMError}
     */
    void onFetched(List<LoyaltyCard> cards, SessionMError error);
}


If an error is returned, see Error Handling for more information.

LoyaltyCard Model

SMLoyaltyCard Model

Attribute java swift Description
cardID String String Unique ID for loyalty card.
cardNumber String String? Number associated with loyalty card (issued by retailer).
retailer Retailer SMRetailer? Retailer associated with loyalty card.
isLinked boolean Bool Indicates whether the current user has linked a loyalty card issued by the associated retailer.
extras N/A [String : NSObject]? Any data values that do not have an associated class property.

Get Cached Linked Cards

Gets a list of cached linked cards. Note that this method has no parameters, and, because it returns a cached list of loyalty cards, it has no callbacks. For information on the loyalty cards in the cached list it returns, see LoyaltyCard/SMLoyaltyCard Model.

Method

/*!
 @property loyaltyCards
 @abstract The current user's linked loyalty cards.
 @discussion This property is updated in response to a successful 'fetchLinkedCardsWithCompletionHandler:' call.
 */
open var loyaltyCards: [SMLoyaltyCard] { get }
public List<LoyaltyCard> getLoyaltyCards()

Fetch Loyalty Card Transactions

Fetch all loyalty card transactions. Note that this method has no parameters on iOS.

Method

/*!
 @abstract Makes a request to update 'loyaltyCardTransactions' with purchase data parsed from transactions made with the current user's linked loyalty cards.
 @param completionHandler The block to execute after the request is processed.
 */
open func fetchCardTransactions(completionHandler: @escaping ([SMLoyaltyCardTransaction]?, SMError?) -> Void)
/**
 * Fetch card transactions
 *
 * @param limit    the limit
 * @param page     the page
 * @param listener {@link OnLoyaltyCardTransactionsFetchedListener}
 * @return {@link SessionMError}
 */
public SessionMError fetchCardTransactions(int limit, int page, OnLoyaltyCardTransactionsFetchedListener listener)

Callback

CompletionHandler: (transactions: [SMLoyaltyCardTransaction]?, error: SMError?) -> Void

Notification Name: fetchedCardTransactionsNotification
Notification Data: key: kManagerNotificationData, value: [SMLoyaltyCardTransaction]
/**
 * Interface with callback from methods {@link #fetchCardTransactions(int, int, OnLoyaltyCardTransactionsFetchedListener)}
 */
public interface OnLoyaltyCardTransactionsFetchedListener {
    /**
     * On fetched.
     *
     * @param loyaltyCardTransactions the loyalty card transactions
     * @param error                   {@link SessionMError}
     */
    void onFetched(List<LoyaltyCardTransaction> loyaltyCardTransactions, SessionMError error);
}


If an error is returned, see Error Handling for more information.

LoyaltyCardTransaction Model

SMLoyaltyCardTransaction Model

Attribute java swift Description
transactionID String String Unique ID for transaction.
name String String? Item name.
details String String? Loyalty card transaction description.
price double Double Individual item price.
quantity int Int Amount of items purchased.
points int Int Amount of points user earned for the transaction.
transactionTime String String? Indicates when the transaction took place.
createdTime String String? Indicates when the transaction record was created.
updatedTime String String? Indicates when the transaction record was last updated.
extras N/A [String : NSObject]? Any data values that do not have an associated class property.

Receipts API

This API allows a customer to submit images for validation, such as receipt captures, and track these submissions through the process of validation. SessionM can work with a variety of partners to validate receipts, but the API is validation provider agnostic. Note that the process of submitting receipts occurs as a series of uploads that run in the background.

The methods presented for the Receipt API manage objects that represent receipt captures and their validations. These methods are available with ReceiptsManager for Android and SMReceiptsManager for iOS.

The callbacks associated with these methods return data and are available with ReceiptsListener for Android. For iOS, the delegate is deprecated. Use methods with completionHandler and/or NSNotification.

This API provides the following methods for fetching or uploading receipts:

You may find it helpful to review Android and iOS sample applications that implement this API.

Fetch Receipts

Fetch uploaded receipts. Offers parameters for specifying a limit or page condition.

Method

/*!
 @abstract Makes a request to update 'receipts' with the current user's uploaded receipts.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func fetchReceipts(completionHandler: @escaping ([SMReceipt]?, SMError?) -> Void)

/*!
 @abstract Makes a request to update 'receipts' with a limited number of the current user's uploaded receipts.
 @param limit Optional. The maximum amount of receipts to fetch.
 @param page Optional. 'limit ∙ (page-1)' most recent receipt records will be skipped for the fetch.
 @param completionHandler Required. The block to execute after the request is processed.
 */
open func fetchReceipts(limit: Int32, page: Int32, completionHandler: @escaping ([SMReceipt]?, SMError?) -> Void)
/**
 * Fetch receipts
 *
 * @param listener {@link OnReceiptsFetchedListener}
 * @return {@link SessionMError}
 */
public SessionMError fetchReceipts(OnReceiptsFetchedListener listener)

/**
 * Fetch receipts
 *
 * @param limit    the limit
 * @param page     the page
 * @param listener {@link OnReceiptsFetchedListener}
 * @return {@link SessionMError}
 */
public SessionMError fetchReceipts(int limit, int page, OnReceiptsFetchedListener listener)

Callback

CompletionHandler: (receipts: [SMReceipt]?, error: SMError?) -> Void

Notification Name: fetchedReceiptsNotification
Notification Data: key: kManagerNotificationData, value: [SMReceipt]
/**
 * Interface with callbacks from methods {@link #fetchReceipts(OnReceiptsFetchedListener)}, {@link #fetchReceipts(int, int, OnReceiptsFetchedListener)}
 */
public interface OnReceiptsFetchedListener {
    /**
     * On fetched.
     *
     * @param receipts {@link List}
     * @param error    {@link SessionMError}
     */
    void onFetched(List<Receipt> receipts, SessionMError error);
}


The following table details this method's errors:

Errors for Callback

Code Reason
unknown api_key The API key sent in cannot be found.
unknown user The customer ID sent in cannot be found.
unknown registered user The customer ID sent in is not registered.
no image validation data Required parameter is missing.
no active campaign found The campaign ID sent in could not be found.
campaign unavailable The customer is ineligible for this campaign or has hit the cap.
images, invalid image data Invalid image data sent in.
images, can’t be blank No image data sent in.
images, above maximum limit Too many images passed in.
images, image too large An image passed in is over 10 MB.
base, daily limit exceeded Customer has exceeded daily limit.

The following table lists the invalid image codes associated with this method:

Invalid Image Codes

Code Reason
0 Unknown
1 Receipt cannot be read clearly
2 Receipt is cropped
3 Receipt submitted twice
4 Receipt submitted outside of campaign dates
5 Image is not a receipt
6 No valid purchases found
7 Purchases are from a non-qualifying store
8 Image cannot be read clearly
9 Image is unrelated to campaign
10 Image submitted twice
11 Image submitted outside of campaign dates
12 Image has no valid purchases found, similar to code 6
13 Multiple submissions not allowed for this campaign

See Error Handling for more information.

Receipt Model

SMReceipt Model

Attribute java swift Description
receiptID String String Receipt identifier.
campaignID String String? Campaign identifier of the promotion this receipt is associated to.
placementID String String? Placement identifier of this receipt.
userID String String? Current customer identifier.
groupID String String? Group identifier for a group of images.
status ReceiptStatus SMReceiptStatus Status of the receipt.
imageCount int Int Number of images associates to current receipt.
imageURLs List<String> [String]? A list of URLs of the receipt images.
createdTime String String? Timestamp that this receipt is created on the SessionM server.
updatedTime String String? Timestamp that updated on the SessionM server.
receiptDate String String? If status is valid, the receipt's date is shown.
storeName String String? If status is valid, the associated store name is shown.
results List<ReceiptResult> [SMReceiptResult]? Receipts reside in a result set. If status is valid, a list of current receipts is shown.
invalidCode int Int If status is invalid, error code from server is shown.
invalidReason String String? If status is invalid, error message from server is shown.
extras N/A [String : NSObject]? Any data values that do not have an associated class property.

ReceiptStatus Enumeration

SMReceiptStatus Enumeration

java swift Description
UNKNOWN unknown Upload status of receipt is unknown.
PENDING pending Receipt is being reviewed.
VALID valid Receipt has been approved.
INVALID invalid Receipt was rejected. The reason for the rejection is available in the error property.
INCOMPLETE incomplete Image validation is incomplete while a receipt's image count is greater than the length of the image list. "Incomplete" changes to "Pending" once the image count is equal to the size of the image list, provided that all images are uploaded and added to the receipt object.

ReceiptResult Model

SMReceiptResult Model

Attribute java swift Description
resultID String String Receipt result identifier; associates to recordModelID in the Transactions API.
name String String? Receipt result name.
details String String? Receipt result description.
price double Float Receipt result price.
quantity int Int Receipt result quantity.
points int Int Receipt result point.
extras N/A [String : NSObject]? Any data values that do not have an associated class property.

Get Cached Receipts

Gets a list of cached receipts. This method has no parameters, and it requires no callback since it returns a cached list of receipts. You may want to consult Receipt/SMReceipt Model for details on the model represented in the list of receipts returned by this method.

Method

/*!
 @property receipts
 @abstract The current user's uploaded receipts.
 @discussion This property is updated in response to a successful 'fetchReceiptsWithCompletionHandler:' or 'fetchReceiptsWithLimit:page:completionHandler:' call.
 */
open var receipts: [SMReceipt] { get }
/**
 * Returns cached list of receipt.
 *
 * @return a list of immutable {@link Receipt}.
 */
public List<Receipt> getReceipts()

Upload Receipts

In Swift, SessionM supports both asset ID and file path for image files. In Java, we use URI for file's path.

Method

/*!
 @abstract Uploads the receipt images with the specified asset identifiers for the specified campaign.
 @param assetIDs Required. Array of 'PHObject localIdentifier' strings.
 @param campaignID Required. ID of promotional campaign for which receipt is being uploaded.
 @param placementID Optional. ID of receipt placement.
 @param data Optional. Custom, developer-defined data associated with the receipt.
 @param completionHandler Required. The block to execute after all images are uploaded.
 @param progressHandler Required. The block to execute after each image is uploaded.
 @result Returns upload group ID on success (returns 'nil' otherwise).
 */
open func uploadImages(havingAssetIDs assetIDs: [String], campaignID: String, placementID: String?, data: [String : NSObject]?, completionHandler: @escaping (SMReceipt?, SMError?) -> Void progressHandler: @escaping (SMReceipt?, SMError?) -> Void) -> String?

/*!
 @abstract Uploads the receipt images with the specified file paths for the specified campaign.
 @param paths Required. Array of image file paths.
 @param campaignID Required. ID of promotional campaign for which receipt is being uploaded.
 @param placementID Optional. ID of receipt placement.
 @param data Optional. Custom, developer-defined data associated with the receipt.
 @param completionHandler Required. The block to execute after all images are uploaded.
 @param progressHandler Required. The block to execute after each image is uploaded.
 @result Returns upload group ID on success (returns 'nil' otherwise).
 */
open func uploadImageFiles(atPaths paths: [String], campaignID: String, placementID: String?, data: [String : NSObject]?, completionHandler: @escaping (SMReceipt?, SMError?) -> Void progressHandler: @escaping (SMReceipt?, SMError?) -> Void) -> String?
/**
 * Upload receipt images string.
 *
 * @param uris            Required: A list of receipt images uris to be uploaded.
 * @param campaignID      Required: current campaignID.
 * @param placementID     Optional: placement id.
 * @param data            Optional: Any other extra data to send.
 * @param removeOnFailure true if receipt upload should be removed on failure
 * @param listener        Request: {@link OnReceiptUploadListener}
 * @return the string
 */
public String uploadReceiptImages(List<Uri> uris, String campaignID, String placementID, JSONObject data, boolean removeOnFailure, OnReceiptUploadListener listener)

Callback

CompletionHandler: (receipt: SMReceipt?, error: SMError?) -> Void

Notification Name: uploadedReceiptNotification
Notification Data: key: kManagerNotificationData, value: SMReceipt
/**
 * Interface with callbacks from methods {@link #uploadIncompleteReceipt(String, boolean)}
 */
public interface OnReceiptUploadListener {
    /**
     * On uploaded.
     *
     * @param receipt {@link Receipt}
     * @param error   {@link SessionMError}
     */
    void onUploaded(Receipt receipt, SessionMError error);

    /**
     * For multiple images uploading, returns count of images that have been uploaded successfully.
     *
     * @param receipt {@link Receipt}
     * @param error   {@link SessionMError}
     */
    void onProgress(Receipt receipt, SessionMError error);
}
ProgressHandler: (receipt: SMReceipt?, error: SMError?) -> Void

Notification Name: receiptUploadProgressNotification
Notification Data: key: kManagerNotificationData, value: SMReceipt


If an error is returned, see Error Handling for more information.

You may want to consult Receipt/SMReceipt Model for information on the model returned by both callbacks.

Retry Failed Upload Attempts

Retries failed upload attempts. It does, however, share the same callbacks as the method to upload receipts. You may want to consult Receipt Model for information on the model returned by this method's callbacks.

Method

/*!
 @abstract Resumes the incomplete receipt upload with the specified group ID.
 @param groupID Required. ID of receipt upload that will be resumed.
 @param completionHandler Required. The block to execute after all images are uploaded.
 @param progressHandler Optional. The block to execute after each image is uploaded.
 @result Returns upload group ID on success (returns 'nil' otherwise).
 */
open func resumeUpload(havingGroupID groupID: String, completionHandler: @escaping (SMReceipt?, SMError?) -> Void progressHandler: @escaping (SMReceipt?, SMError?) -> Void) -> String?
/**
 * Upload incomplete receipt
 * IMPORTANT: Make sure you have Permission Persisted for URIs, otherwise app will crash if user reboots the device.
 * https://developer.android.com/guide/topics/providers/document-provider.html#permissions
 *
 * @param groupID         Include to upload a specific receipt, otherwise starts with the oldest
 * @param removeOnFailure true if receipt upload should be removed on failure
 * @param listener        {@link OnReceiptUploadListener}
 * @return {@link SessionMError}
 */
public SessionMError uploadIncompleteReceipt(String groupID, boolean removeOnFailure, OnReceiptUploadListener listener)

Cleanup Incomplete Receipt Uploads

Cleans up any incomplete uploads of receipts. This method has neither a callback nor any associated model.

Method

/*!
 @abstract Makes a request to remove all incomplete receipt uploads from storage.
 @discussion All group IDs are removed from 'incompleteUploadGroupIDs' on success.
 */
open func removeAllIncompleteUploads()

/*!
 @abstract Makes a request to remove the incomplete receipt upload with the specified group ID from storage.
 @discussion Group ID is removed from 'incompleteUploadGroupIDs' on success.
 @param groupID Required. ID of receipt upload that will be removed.
 */
open func removeIncompleteUpload(havingGroupID groupID: String)
/**
 * Removes any outstanding receipt uploads.
 *
 * @return {@link SessionMError}
 */
public SessionMError cleanOutIncompleteReceiptUploads()

/**
 * Removes the outstanding uploads for groupID
 *
 * @param groupID group ID for incomplete images
 * @return {@link SessionMError}
 */
public SessionMError cleanOutIncompleteReceiptUpload(String groupID)

Advanced

The APIs featured in this grouping are advanced features.

Generic Request

The SessionM SDK provides a generic request mechanism to support interfaces developed on the server (S2S) but have not yet, or will not be, included in the SDK implementation. Each request takes a request object and a route. The SDK handles authentication and passing the request to the correct route. The SDK then returns a response object for the developer to use.

The flow of development steps follows:

  1. Create and populate request using the GenericRequestBuilder.
  2. Use GenericRequestManager to send request to the server.
  3. Server returns either a GenericResponse or an Error.

Call Generic Request

Make an HTTP request, providing the GenericRequest and route. Receive the results as a GenericResponse.

Method:

open func send(_ request: SMGenericRequest, completionHandler: @escaping (SMGenericResponse?, SMError?, [AnyHashable : Any]?) -> Void)
/**
 * Send the Request to the endpoint
 *
 * @param builder HttpRequest
 *
 * @return {@link SessionMError}
 */
public SessionMError sendRequest(HttpRequestBuilder builder)

public SessionMError sendRequest(HttpRequestBuilder builder, OnRequestCompleteListener callback)

Parameters

The request object must include the HTTP method and URL. It may also include a body, headers, (URL) parameters, and a Map of values that are held during the entire request. The request instance is created using a builder.

Attribute Type
Required/Optional
Description
method enum
required
An enumeration for POST/GET/PUT/DELETE.
baseURL String
required
The customer without parameters. For example, (https://api.sessionm.com/api/me).
body Map
required
The body of the request, a Map that is converted to a json string [* GET/DELETE = no, POST/PUT = required]
params Map
optional
The parameters that are added to the URL (?p1=a&p2=b).
headers Map
optional
Additional headers added to the request.
keepAround Map
optional
A Map of data that follows the request through the steps.
CompletionHandler: (kind: String, response: SMGenericResponse?, error: SMError?, other: [AnyHashable : Any]?) -> Void

Notification Name: genericRequestSuccessNotification
Notification Data: key: kGenericManagerNotificationResponse, value: SMGenericResponse
/**
 * Interface for results on calls to {@link GenericRequestManager#sendRequest(HttpRequestBuilder)} )}
 */
public interface OnRequestCompleteListener {
    /**
     * When request has completed.
     *
     * @param request  the request
     * @param response the response
     * @param error    {@link SessionMError}
     */
    void onCompletion(HttpRequest request, HttpResponse response, SessionMError error);
}

Callback

The result of the call is either a GenericResponse object or an Error callback.

The response object includes a body and a bodyString.

Attribute Type
Required/Optional
Description
body Map
required
The body from HTTP request result as a Map.

Note the following implementations for the body Map object:

Error Handling

Android: each SMP method callback returns the result, and SessionMError. If the method call is successful, error's value is null.

iOS: each SMP method completion handler returns the result, and error: SMError?. If the method call is successful, error's value is nil. Errors returned in a notification callback can be accessed with the kManagerNotificationError userInfo key.

Returned Callback Values

Attribute Android Description
type SessionMError.Type Values include: Network, Validation, Server and Unknown.
code String Error code; a developer friendly standardized string. For example, "email_already_exists".
message String Error message; a customer friendly message shows more details. For example, "Email already exists."
severity SessionMError.Severity Hard or soft error.
Exception Throwable Exception message.

Release Notes

Android Release Notes

Version: 3.0.0

Date: 05/11/2018

iOS Release Notes

Version: 3.0.0

Date: 05/11/2018

Developer Support

For development questions, guidance on best practices, or the procedure for reporting bugs/issues, please submit an email to: devsupport@sessionm.com

Please provide as much detail as possible, including:

Providing more detail up front expedites your issue.

If there is a platform issue which needs immediate emergency attention, please contact: external-support@sessionm.com

This email is monitored 24/7 and the appropriate staff at SessionM is paged. Emergencies are defined as: