0.3.0 • Published 2 years ago

@beaconsmind/ionic-sdk v0.3.0

Weekly downloads
-
License
MIT
Repository
gitlab
Last release
2 years ago

@beaconsmind/ionic-sdk

Beaconsmind SDK for Ionic.

Prerequisites

As a Beaconsmind client, a contained environment is provided for Beaconsmind services being hosted and maintained by Beaconsmind.

The hostname of the provided environment is required to properly access Beaconsmind API and to use Beaconsmind SDK

example: https://adidas.bms.beaconsmind.com

Please contact Beaconsmind support for the required information about acquiring a valid environment and hostname.

1. Installing

npm install @beaconsmind/ionic-sdk
npx cap sync

Make sure your iOS Deployment Target is 11.0 or above.

Make sure your Android minSdkVersion is 23 or above.

2. Permissions

Beaconsmind SDK requires bluetooth and location permission (whenInUse or always) to detect nearby beacon devices and notification permission to send offers. Consider using a package of choice to request those permissions. Make sure to follow the setup required for native iOS & Android.

3. Initialize the SDK

This will initialize the SDK and try to retrieve the logged-in user. Call this method as soon as your app starts, so the sdk can track all touchpoints and beacon events correctly.

import { Beaconsmind } from '@beaconsmind/ionic-sdk';

const initializeResponse = await Beaconsmind.initialize({
  hostname: 'https://test-develop-suite.azurewebsites.net/',
  appVersion: '0.0.1',
  platformOptions: {
    android: {
      usePassiveScanning: true,
      notification: {
        androidNotificationBadgeName: 'ic_beacons',
        androidNotificationChannelName: 'beaconsmind',
        androidNotificationTitle: 'Beaconsmind sdk demo',
        androidNotificationText: 'Listening to beacons',
      },
    },
  },
});

console.log(initializeResponse);

See:

4. Authentication

When using Beaconsmind authentication

This approach implies that the customer data is kept in Beaconsmind backend. Use UserManager.login method to perform customer authentication.

To login existing user.

const loginResponse = await Beaconsmind.login({
  username: usernameValue,
  password: passwordValue,
});

console.log(loginResponse);

See:

To register a new user.

const signUpResponse = await Beaconsmind.instance.signup({
    username: usernameValue,
    firstName: firstNameValue,
    lastName: lastnameValue,
    password: passwordValue,
    confirmPassword: confirmPasswordValue,
  });

console.log(signUpResponse);

See:

When using own authentication mechanism

This approach implies that the customer data is kept in clients backend. The authentication is done by the client app before the Beaconsmind API is used. Whenever customer is authenticated, use Beaconsmind.importAccount method to send basic customer data to Beaconsmind. The customer data is updated only the first time the method is called. The client app can track if the customer was imported before and omit personal data from following importAccount calls.

const importAccountResponse = await Beaconsmind.importAccount({
  id: '3287e422-961a-4d47-8eaa-a58e0bd536a1',
  email: 'account@example.com',
  firstName: 'John',
  lastName: 'Doe',
  language: 'en',
  gender: 'male',
  // UNIX timestamp represented in seconds.
  birthDateSeconds: 831589200, 
});

console.log(importAccountResponse);

See:

Log out

In order to log out the current account and stop listening for beacons, call the Beaconsmind.logout() method.

See:

6. Notifications

The SDK uses APNS for iOS, and Firebase for Android. You can use the @capacitor/push-notifications package in order to configure it.

Setting device token

import { Beaconsmind } from '@beaconsmind/ionic-sdk';
import { PushNotifications } from '@capacitor/push-notifications';

PushNotifications.addListener('registration', async token => {
  alert('Registration token: ' + token.value);

  const registerDeviceTokenResponse = await Beaconsmind.registerDeviceToken({
    deviceToken: token.value,
  });

  console.log(registerDeviceTokenResponse);
});

See:

Supporting multiple push notification providers

Issue

On Android, if there is more than one package used to receive push notifications, for example: capacitor-moengage-core & @capacitor/push-notifications, then only one package will be notified about a push notification.

Explanation

Each package used to receive push notifications has it’s on AndroidManifest.xml file (manifest) where it declares a service that should receive and handle the FCM messages — here is an example from the @capacitor/push-notifications package.

When app is built, the app’s manifest is merged with each manifest from packages that it depends on. As a result, the final manifest will contain multiple services declared to receive FCM messages, but the system will deliver push notification only to one of them, the one that is declared earlier.

If there is a service declaration at the app’s manifest, then it will take a precedence over service declarations from packages’ manifest.

Solution

In order to deliver push notifications to services declared by each package, a proxy service declared at the app’s manifest needs to be introduced. It will be responsible for intercepting push notifications and forwarding them to other services coming from used packages.

Implementation

  1. Add FirebaseMessagingServiceProxy.kt file to your Android app project.
  2. In the FirebaseMessagingServiceProxy file, update messagingServices list with push notification services that you want to notify. Make sure to add necessary imports at the top of the file in order to access them.
  3. Register the FirebaseMessgingServiceProxy in the app’s manifest.

7. Offers

Beacons ranging is used to pick up offers. In respect to offers, when users receive pushes about a new offer, read an offer and consume an offer, API calls need to be sent to recognize user activity.

Getting offers

Interacting with offers

8. Beacons

Interacting with beacons

Beacons feature uses BLE transmitters which can be picked up by devices. In Beaconsmind, BLE transmitters are used to present offers based on a physical location of a device.

Every beacon is defined by it's UUID and major and minor numbers. A list of beacons is persisted and maintained on Beaconsmind environment for each client.

In order to start monitoring nearby beacon devices, call Beaconsmind.startListeningBeacons(). Make sure that the bluetooth & location permissions have been granted. To stop the monitoring process, call Beaconsmind.stopListeningBeacons(). In order to obtain a list of beacon devices that are within range, call Beaconsmind.getBeaconContactsSummary().

See:

Read more about beacons

Deployment

Log in into the npm package registry by running

npm login

In the root directory, run:

npx release-it

For the wizard questions, answer in the following way:

  • Publish @beaconsmind/ionic-sdk to npm? Yes
  • Commit? Yes
  • Tag (x.y.z)? Yes
  • Push? Yes

API

setMinLogLevel(...)

setMinLogLevel({ minLogLevel }: { minLogLevel: LogLevel; }) => Promise<Response>

Sets the minimum log level.

ParamType
__0{ minLogLevel: LogLevel; }

Returns: Promise<Response>


initialize(...)

initialize(options: InitializeOptions) => Promise<Response>

Initializes the SDK.

Call this method as soon as your app starts, so the sdk can track all touchpoints and beacon events correctly.

ParamType
optionsInitializeOptions

Returns: Promise<Response>


initializeDevelop(...)

initializeDevelop(options: InitializeOptions) => Promise<Response>

For development purposes only. Alternative initialization method.

Kickstart sdk testing and integration by a single method call. Invokes initialize and sets the sdk in development mode.

When initialized with this method the sdk requests permissions on it own by.

ParamType
optionsInitializeOptions

Returns: Promise<Response>


login(...)

login({ username, password }: { username: string; password: string; }) => Promise<Response>

Performs login and immediately starts listening for beacons

ParamType
__0{ username: string; password: string; }

Returns: Promise<Response>


signUp(...)

signUp(options: SignUpOptions) => Promise<UserIdResponse>

Creates a new account login and immediately starts listening for beacons.

ParamType
optionsSignUpOptions

Returns: Promise<UserIdResponse>


importAccount(...)

importAccount(options: ImportAccountOptions) => Promise<UserIdResponse>

When the customer is using 3rd party authentication and not relying on Beaconsmind to keep the customer's private data, this endpoint is used to import the customer into Beaconsmind and to obtain a token with which the app can send tracking data to us. The token does NOT provide access to any personal customer info. If personal data is present in the request, it will only be updated the first time the endpoint is invoked for that customer. Once the authentication is done by the app, the username is sent to Beaconsmind using /api/accounts/import to receive a JWT for access to Beaconsmind backend. In this case, Beaconsmind will not allow any personal data to be accessed and it’s the apps responsibility to only send personal data the first time /api/accounts/import is used. When using import, editing profile is disabled.

ParamType
optionsImportAccountOptions

Returns: Promise<UserIdResponse>


logout()

logout() => Promise<Response>

Logs out the current account and stops listening for beacons.

Returns: Promise<Response>


getOAuthContext()

getOAuthContext() => Promise<UserIdResponse>

Returns the currently logged in user id.

Returns: Promise<UserIdResponse>


getProfile()

getProfile() => Promise<ProfileResponse>

Returns the currently logged in user profile data.

Returns: Promise<ProfileResponse>


updateProfile(...)

updateProfile(options: any) => Promise<ProfileResponse>

Updates the currently logged in user profile data.

ParamType
optionsany

Returns: Promise<ProfileResponse>


registerDeviceToken(...)

registerDeviceToken({ deviceToken }: { deviceToken: string; }) => Promise<Response>

Register the device token in Beaconsmind servers in order receive offers push notifications.

ParamType
__0{ deviceToken: string; }

Returns: Promise<Response>


loadOffers()

loadOffers() => Promise<OffersResponse>

Loads the list of offers for the current user.

Returns: Promise<OffersResponse>


loadOffer(...)

loadOffer({ offerId }: { offerId: number; }) => Promise<Offer>

Loads the offer details for the given offer id.

ParamType
__0{ offerId: number; }

Returns: Promise<Offer>


markOfferAsReceived(...)

markOfferAsReceived({ offerId }: { offerId: number; }) => Promise<Response>

Marks the offer as received.

Call this when an offer is received via push notification.

ParamType
__0{ offerId: number; }

Returns: Promise<Response>


markOfferAsRead(...)

markOfferAsRead({ offerId }: { offerId: number; }) => Promise<Response>

Marks the offer as read.

Call this when the user opens the offer.

ParamType
__0{ offerId: number; }

Returns: Promise<Response>


markOfferAsRedeemed(...)

markOfferAsRedeemed({ offerId }: { offerId: number; }) => Promise<Response>

Marks the offer as redeemed.

Call this when the user redeems the offer.

ParamType
__0{ offerId: number; }

Returns: Promise<Response>


startListeningBeacons()

startListeningBeacons() => Promise<Response>

Starts listening for beacons devices. It requires the following permissions to work:

  • location (whenInUse/always)
  • bluetooth

Returns: Promise<Response>


stopListeningBeacons()

stopListeningBeacons() => Promise<Response>

Stops listening for beacons devices.

Returns: Promise<Response>


updateHostname(...)

updateHostname({ hostname }: { hostname: string; }) => Promise<Response>

Updates the hostname that the SDK will use to connect to the Beaconsmind servers.

ParamType
__0{ hostname: string; }

Returns: Promise<Response>


getBeaconContactsSummary()

getBeaconContactsSummary() => Promise<BeaconContactSummaryResponse>

Get a list of all the beacons that are currently in range.

Returns: Promise<BeaconContactSummaryResponse>


Interfaces

InitializeOptions

PropType
appVersionstring
hostnamestring
platformOptionsInitializePlatformOptions

InitializePlatformOptions

PropType
androidInitializeAndroidOptions

InitializeAndroidOptions

PropTypeDescription
notificationAndroidNotificationOptions | nullOptions that describe the content of the native Android notification that is displayed to user when a foreground service responsible for scanning. The notification is displayed when usePassiveScanning is set to false.
usePassiveScanningbooleanThe SDK supports two types of BLE scanning: - active scanning, - passive scanning. When scanning actively, the Beaconsmind SDK will start a foreground service and show a pinned notification described by notificationOptions. By default, the SDK uses passive scanning, i.e. usePassiveScanning is set to true.

AndroidNotificationOptions

PropTypeDescription
androidNotificationBadgeNamestringName of the native icon resource. Default value: "ic_beacons". Reference: https://developer.android.com/reference/androidx/core/app/NotificationCompat.Builder#setSmallIcon(int)
androidNotificationTitlestringTitle of the notification (first row). Default value: "Beaconsmind". Reference: https://developer.android.com/reference/androidx/core/app/NotificationCompat.Builder#setContentTitle(java.lang.CharSequence)
androidNotificationTextstringBody of the notification (second row). Default value: "Listening for Beacons". Reference: https://developer.android.com/reference/androidx/core/app/NotificationCompat.Builder#setContentText(java.lang.CharSequence)
androidNotificationChannelNamestringThe user visible name of the channel. Default value: "beaconsmind". Reference: https://developer.android.com/reference/android/app/NotificationChannel#NotificationChannel(java.lang.String,%20java.lang.CharSequence,%20int)

SignUpOptions

PropType
usernamestring
firstNamestring
lastNamestring
passwordstring
confirmPasswordstring
languagestring
genderstring
favoriteStoreIDnumber
birthDateSecondsnumber
countryCodestring

ImportAccountOptions

PropType
idstring
emailstring
firstNamestring
lastNamestring
languagestring
genderstring
birthDateSecondsnumber

ProfileResponse

PropType
idstring
userNamestring
claimsstring[]
rolesstring[]
genderstring | null
firstNamestring
lastNamestring
fullNamestring
streetstring | null
houseNumberstring | null
zipCodestring | null
citystring | null
countrystring | null
landlinePhonestring | null
phoneNumberstring | null
urlstring | null
disablePushNotificationsboolean
newsLetterSubscriptionboolean
joinDateDate
birthDateDate | null
clubIdstring | null
favoriteStorestring | null
favoriteStoreIdnumber | null

Date

Enables basic storage and retrieval of dates and times.

MethodSignatureDescription
toString() => stringReturns a string representation of a date. The format of the string depends on the locale.
toDateString() => stringReturns a date as a string value.
toTimeString() => stringReturns a time as a string value.
toLocaleString() => stringReturns a value as a string value appropriate to the host environment's current locale.
toLocaleDateString() => stringReturns a date as a string value appropriate to the host environment's current locale.
toLocaleTimeString() => stringReturns a time as a string value appropriate to the host environment's current locale.
valueOf() => numberReturns the stored time value in milliseconds since midnight, January 1, 1970 UTC.
getTime() => numberGets the time value in milliseconds.
getFullYear() => numberGets the year, using local time.
getUTCFullYear() => numberGets the year using Universal Coordinated Time (UTC).
getMonth() => numberGets the month, using local time.
getUTCMonth() => numberGets the month of a Date object using Universal Coordinated Time (UTC).
getDate() => numberGets the day-of-the-month, using local time.
getUTCDate() => numberGets the day-of-the-month, using Universal Coordinated Time (UTC).
getDay() => numberGets the day of the week, using local time.
getUTCDay() => numberGets the day of the week using Universal Coordinated Time (UTC).
getHours() => numberGets the hours in a date, using local time.
getUTCHours() => numberGets the hours value in a Date object using Universal Coordinated Time (UTC).
getMinutes() => numberGets the minutes of a Date object, using local time.
getUTCMinutes() => numberGets the minutes of a Date object using Universal Coordinated Time (UTC).
getSeconds() => numberGets the seconds of a Date object, using local time.
getUTCSeconds() => numberGets the seconds of a Date object using Universal Coordinated Time (UTC).
getMilliseconds() => numberGets the milliseconds of a Date, using local time.
getUTCMilliseconds() => numberGets the milliseconds of a Date object using Universal Coordinated Time (UTC).
getTimezoneOffset() => numberGets the difference in minutes between the time on the local computer and Universal Coordinated Time (UTC).
setTime(time: number) => numberSets the date and time value in the Date object.
setMilliseconds(ms: number) => numberSets the milliseconds value in the Date object using local time.
setUTCMilliseconds(ms: number) => numberSets the milliseconds value in the Date object using Universal Coordinated Time (UTC).
setSeconds(sec: number, ms?: number | undefined) => numberSets the seconds value in the Date object using local time.
setUTCSeconds(sec: number, ms?: number | undefined) => numberSets the seconds value in the Date object using Universal Coordinated Time (UTC).
setMinutes(min: number, sec?: number | undefined, ms?: number | undefined) => numberSets the minutes value in the Date object using local time.
setUTCMinutes(min: number, sec?: number | undefined, ms?: number | undefined) => numberSets the minutes value in the Date object using Universal Coordinated Time (UTC).
setHours(hours: number, min?: number | undefined, sec?: number | undefined, ms?: number | undefined) => numberSets the hour value in the Date object using local time.
setUTCHours(hours: number, min?: number | undefined, sec?: number | undefined, ms?: number | undefined) => numberSets the hours value in the Date object using Universal Coordinated Time (UTC).
setDate(date: number) => numberSets the numeric day-of-the-month value of the Date object using local time.
setUTCDate(date: number) => numberSets the numeric day of the month in the Date object using Universal Coordinated Time (UTC).
setMonth(month: number, date?: number | undefined) => numberSets the month value in the Date object using local time.
setUTCMonth(month: number, date?: number | undefined) => numberSets the month value in the Date object using Universal Coordinated Time (UTC).
setFullYear(year: number, month?: number | undefined, date?: number | undefined) => numberSets the year of the Date object using local time.
setUTCFullYear(year: number, month?: number | undefined, date?: number | undefined) => numberSets the year value in the Date object using Universal Coordinated Time (UTC).
toUTCString() => stringReturns a date converted to a string using Universal Coordinated Time (UTC).
toISOString() => stringReturns a date as a string value in ISO format.
toJSON(key?: any) => stringUsed by the JSON.stringify method to enable the transformation of an object's data for JavaScript Object Notation (JSON) serialization.

OffersResponse

PropType
offersOffer[]

Offer

PropType
offerIdnumber
titlestring
textstring
imageUrlstring
thumbnailUrlstring
validitystring
isRedeemedboolean
isRedeemableboolean
isVoucherboolean
tileAmountnumber
callToAction{ title: string; link: string; } | null

BeaconContactSummaryResponse

PropType
beaconsBeaconContactSummary[]

BeaconContactSummary

A class that holds information about the beacon device.

It consists of the beacon unique identifier (uuid, minor, major), the beacon's name (name) and the name of the store that it is located in.

Additionally, it contains data related to its signal strength and the number of times it was contacted.

PropTypeDescription
uuidstringBeacon's uuid.
majorstringBeacon's major.
minorstringBeacon's minor.
namestringBeacon's name.
storestringThe name of the store that the beacon is located in.
currentRSSInumber | nullBeacon's current signal strength in dB. Null if the beacon has not been contacted yet. RSSI is an abbreviation from Received Signal Strength Indicator. See: https://en.wikipedia.org/wiki/Received_signal_strength_indication
averageRSSInumber | nullBeacon's average signal strength in dB (based on the last contacts). Null if the beacon has not been contacted yet.
lastContactTimestampnumber | nullLast beacon contact timestamp represented as unix timestamp in milliseconds. Null when the beacon has not been contacted yet.
contactFrequencyPerMinutenumberContacts frequency per minute.
contactsCountnumberIndicates how many times the beacon was contacted.
isInRangebooleanReturns if the beacon is within range.

Type Aliases

Response

{ result: boolean }

UserIdResponse

{ userId: string } | null

Enums

LogLevel

MembersValueDescription
debug'debug'Any developer-level debug info, repeating events, e.g.: - monitoring/location callbacks, - networking success results.
info'info'Bigger events/steps in the SDK lifecycle, e.g.: - starting/stopping services, - initializing SDK, - one-time events.
warning'warning'Allowed, but not-optimal, inconsistent state, e.g.: - trying to start monitoring without permissions.
error'error'Not allowed state (any error).
silent'silent'No logging at all.
0.3.0

2 years ago

0.2.0

2 years ago

0.1.0

3 years ago

0.0.1

3 years ago