0.22.1 • Published 3 months ago

@chargespot/spjs v0.22.1

Weekly downloads
-
License
ISC
Repository
-
Last release
3 months ago

Spot JS SDK

Usage

ESM (recommanded)

Install from npm:

npm i @chargespot/spjs

Use it as a normal dependency:

import { showToast } from '@chargespot/spjs'

showToast({ title: 'Hello SPOT' })

Or you want to use it in a scope:

import * as sp from '@chargespot/spjs'

sp.showToast({ title: 'Hello SPOT' })

We write the SDK with TypeScript so all definations are out-of-box.

UMD

The Global module name is sp (window.sp).

You can find a basic UMD example here: https://3ji4i.csb.app/.

<script src="https://unpkg.com/@chargespot/spjs@latest/umd/index.min.js"></script>
<script>
  sp.showToast({ title: 'Hello SPOT' })
</script>

API

There are two styles of API:

  • Promise style: Post a message and wait / not wait for the Payload Response.
  • Event style: Listening to an event and unlistening with the same callback function.

Promise Style

Resolve with SuccesssPayload and reject with ErrorPayload.

getLocation().then(
  (payload: SuccessPayload) => {
    console.log(payload)
  },
  (error: ErrorPayload) => {
    console.log(error)
  }
)

ErrorPayload

Especially, the type of ErrorPayload is:

KeyValue TypeValue ExampleComment
errCodenumber10002
errMsgstring'no device'duraction in millisecond

Event Style

Pass a callback function which will be called with the SuccessPayload.

Event style API name will always start with on like onFoo.

onLocationChange((payload: SuccessPayload) => {
  console.log(payload)
})

You can cancel the listening by passing same function later.

const handleLocationChange = (payload: SuccessPayload) => {
  console.log(payload)
}

onLocationChange(handleLocationChange)

setTimeout(() => {
  offLocationChange(handleLocationChange)
}, 1000)

Permission

There are many permision scopes related to API call.

SpotApp will show a pop-up asking for user permission for the first time, and return an error message if user deny.

Notice that you will not get the real reason behind the deny response from three of:

  1. SpotApp does not have the permission from the native OS.
  2. User deny the first time pop-up.
  3. The pop-up will be only shown once, and the request will be auto rejected after first time.
Scope ValueScene Enum (for TypeScript)Related APIComment
'scope.userProfile'Scope.UserProfilegetUserProfile()-
'scope.userLocation'Scope.UserLocationgetLocation()-
'scope.bluetooth'Scope.BluetoothopenBluetoothAdapter()-
'scope.camera'Scope.CamerascanCode()Always given, and can not switch on/off in miniapp openSetting

Permission Deny ErrorPayload

errCodeerrMsgValue ExampleComment
errCodenumber-2Always -2 for permission deny
errMsgstring'no permission for scope.userLocation'May vary

permit

Pre-asking the specific scope permission, without really calling relatede API

Param

KeyValue TypeValue ExampleRequiredDefaultComment
scopeScope'scope.bluetooth'true-only one scope

Setting

getSetting

Get the current mini-app scope setting.

SuccessPayload

KeyValue TypeValue ExampleComment
permissionSettingRecord<Scope, boolean>{'scope.camera': false}-

openSetting

Open mini-app scope setting page, and get the result of setting.

SuccessPayload

KeyValue TypeValue ExampleComment
permissionSettingRecord<Scope, boolean>{'scope.userLocation': true}-
import { getLocation, openSetting } from '@chargespot/spjs'

getLocation().catch((e) => {
  if (e.errCode === -2) {
    confirm('the mini-app needs location permission').then(() => {
      openSetting().then(({ permissionSetting }) => {
        if (permissionSetting['scope.userLocation']) {
          toast('thanks!')
          // re-execuate location flow
          // getLocation()
        }
      })
    })
  }
})

Base

canIUse

Check if a function or message name is available.

Both function name or message name are accpeted, JS SDK will convert the function name to the related message name

  • function name: chooseCoupon
  • message name (with scope): coupon/chooseCoupon
import { canIUse, chooseCoupon } from '@chargespot/spjs'

async function useCoupon() {
  const { available } = await canIUse('chooseCoupon')
  if (!available) return

  // continue
  const { couponId } = await chooseCoupon()
}

Param

KeyValue TypeValue ExampleRequiredDefaultComment
namestring'chooseCoupon'truespjs sdk function name or message name

SuccessPayload

KeyValue TypeValue ExampleComment
availablebooleantrue-

getSystemInfo

Get the current enviroment information

SuccessPayload

KeyValue TypeValue ExampleComment
versionstring'1.23.4'-
languageLanguage'ja_JP'-
enviroment'sharespot' | 'chargespot''chargespot''chargespot' means current miniapp running in ChargeSPOT

Language will be one of:

enum Language {
  EnUS = 'en_US',
  JaJP = 'ja_JP',
  ThTH = 'th_TH',
  ZhCN = 'zh_CN',
  ZhHK = 'zh_HK',
  ZhTW = 'zh_TW',
}

getLaunchOptions

Get the environment information of how the mini-app launched.

The example below shows a scenario that the mini-app launched by a SpotApp camera scan result:

import { getLaunchOptions } from '@chargespot/spjs'

getLaunchOptions().then((launchOptions) => {
  if (launchOptions.scene === 1011) {
    // https://api.charge-spot.com/device?type=3&uuid=foo
    const launchUrl = launchOptions.query.result
    // uuid === 'foo'
    const { uuid } = parseDeviceUrl(launchUrl)
    window.location.href = `/devicePage/${uuid}`
  }
})

with TypeScript:

import { getLaunchOptions, Scene, ScanSceneQuery } from '@chargespot/spjs'

getLaunchOptions().then((launchOptions) => {
  if (launchOptions.scene === Scene.Scan) {
    const query = launchOptions.query as ScanSceneQuery
    // https://api.charge-spot.com/device?type=3&uuid=foo
    const launchUrl = launchOptions.query.result
    // uuid === 'foo'
    const { uuid } = parseDeviceUrl(launchUrl)
    window.location.href = `/devicePage/${uuid}`
  }
})

SuccessPayload

KeyValue TypeValue ExampleComment
sceneScene1001-
querySceneQuery?--

Scene and SceneQuery

Scene ValueScene Enum (for TypeScript)SceneQuery TypeComment
1001Scene.Home-Top of the Home Page
1011Scene.ScanScanSceneQuerySpotApp Scan Result
1029Scene.CouponDetailCouponSceneQuery?Spot Coupon Page (with Spot Coupon ID)
1065Scene.UrlSchemeUrlSchemeSceneQuery?SpotApp Launched by URL Scheme (Universal Links or spotapp://miniApp custom scheme)
1146Scene.MapMapSceneQueryPOI information
1151Scene.OrderDetailOrderSceneQueryOrder information
2000Scene.UsingOrderOrderSceneQueryOrder information, without status
2001Scene.ReservationReservationSceneQuery?Reservation information, optional
2002Scene.PayDetail-Payment Detail Page
2003Scene.MapInstantLaunchMapSceneQuery?Instant Launch (すぐ利用する) Button in Map Page, within or outside POI panel
2004Scene.Help-Help Page in ShareSPOT My Page
ScanSceneQuery

Notice: You have to register the QR code format (e.g URL prefix) to SpotApp first

KeyValue TypeValue ExampleComment
resultstring'https://api.charge-spot.com/device?type=3&uuid=foo'Value of the Scan Result
CouponSceneQuery

You could use the coupon ID here as the defaultValue of chooseCoupon()

KeyValue TypeValue ExampleComment
couponIdstring'1517390046445137921'The Spot Coupon ID, it is a number style string
UrlSchemeSceneQuery

You will get the whole url scheme and should parse its query by yourself.

You could launch your mini app by two ways:

  • Universal Links: https://sharespot.jp/miniapp?appId=${YOUR_MINI_APP_ID}
  • Spot App URL Scheme: spotapp://miniapp?appId=${YOUR_MINI_APP_ID}

Add the launch query on the launchData url query parameter like:

  • Universal Links: https://sharespot.jp/miniapp?appId=${YOUR_MINI_APP_ID}&launchData=${encodeURIComponent('fooBar?')}
  • Spot App URL Scheme: spotapp://miniapp?appId=${YOUR_MINI_APP_ID}&launchData=${encodeURIComponent('fooBar?')}

And you will obtain the whole value of launchData.

Note: only the value on launchData will be accpeted.

KeyValue TypeValue ExampleComment
launchDatastring'fooBar?'Value of the launch Data
MapSceneQuery
KeyValue TypeValue ExampleComment
merchantPoiIdMiniAppPoiId'123'MiniApp POI Id
OrderSceneQuery
KeyValue TypeValue ExampleComment
merchantOrderIdMiniAppOrderId-MiniApp Order Id
orderNoOrderNo-MiniApp Order No (for display)
statusOrderStatus?0SpotApp Order Status
OrderStatus
ValueEnum (for TypeScript)Comment
0OrderStatus.Complete-
1OrderStatus.Unpaid-
2OrderStatus.Canceled-
ReservationSceneQuery
KeyValue TypeValue ExampleComment
merchantReservationIdMiniAppReservationId-MiniApp Reservation Id

openAction

Redirect to ShareSPOT Native Page with url and related launch options.

URL provided in other documents.

Param

KeyValue TypeValue ExampleRequiredDefaultComment
urlstring'spotapp://usagelist?type=3'true-ShareSPOT Action Url
launchOptionsobject-false-

ErrorPayload

ErrCodeErrMessage
-1URL is not supported, with no action

UI

showToast

Show a native toast.

Param

KeyValue TypeValue ExampleRequiredDefaultComment
durationNumber300false1500duraction in millisecond
titleString'Hello SPOT'true-

setNavigationBarColor

Change color of the Top Navigation Bar.

Param

KeyValue TypeValue ExampleRequiredDefaultComment
frontColorString'#000000'false-color in HEX
backgroundColorString'#ffffff'false-

Auth

login

Get the code for the auth flow. A basic auth flow is like:

  1. Your Web Application: When the miniapp launching, call the login() and send the code to your backend.
  2. Your Backend Service: Send the code with other information to the SPOT Open API.
  3. Your Backend Service: Get the SPOT User Identity for your service. Register or obtain the User in your service.
  4. Your Web Application: Get your user information.

Check the SPOT Open API Document for more detailed information.

// Call the login() when the miniapp launched
async function getUser() {
  const localUserString = window.localStorage.getItem('user')
  if (localUserString) return JSON.parse(localUserString)
  const {code} = await login()

  // pass the code to your back-end
  const user = fetch(`/user/login?spot_login_code=${code}`)

  // save to the local
  window.localStorage.setItem('user', JSON.stringify(user))
  return user
}

Code Expired

The code you recevied:

  1. Could only be used one time.
  2. Should be used in 5 minutes.

Therefore, the code will be expired (You will get 401 from our SPOT Open API) when:

  1. The code has been used once time.
  2. The code is issued 5 miniutes ago.

SuccessPayload

KeyValue TypeValue ExampleComment
codestring--

getUserProfile

Get non-sensitive user info in the Spot App.

SuccessPayload

KeyValue TypeValue ExampleComment
userInfoUserInfo--

UserInfo

KeyValue TypeValue ExampleComment
namestring-User name in the Spot App
avatarstring-User avatar image URL in the Spot App

Device

scanCode

Call a native QR code reader and get the result

SuccessPayload

KeyValue TypeValue ExampleComment
scanType'barCode' | 'qrCode'-code type
resultstring'https://chargespot.jp'code value

setClipboardData

Set string data into the clipboard

Param

KeyValue TypeValue ExampleComment
datastring-string value set to clipboard

makePhoneCall

Make a phone call like tel: URI in <a> tag.

Param

KeyValue TypeValue ExampleComment
phoneNumberstring-phone number value after tel: URI, hyphens or country code may included
makePhoneCall({ phoneNumber: '+81-90-0000-0000' })

sendMail

Send email like mailto: in <a> tag, but only few fields (in https://datatracker.ietf.org/doc/html/rfc6068) are supported.

Only one recipent is supported, separators like , or ; in to field are not working.

Param

KeyValue TypeValue ExampleRequiredComment
tostring'sharespot_partner@inforichjapan.com'trueMultiple recipients are not supported
subjectstring-falseMail Subject
bodystring-falseMail Body

Share

setShareInfo

Set the information for twitter / facebook share.

Param

KeyValue TypeValue ExampleRequiredDefaultComment
titlestring'Campaign Title'truecurrent Web cocument title
urlstring?'https://chargespot.jp/campaign'falsecurrent Web Page URL
descriptionstring?-false-
imagestring?-false-Image URL

showShareMenu

Show Share Bottom Menu, value from setShareInfo

shareTo

Directly call the native share method, it behaviours equivalent to call showShareMenu() and click the platform

setShareInfo({ title: 'my mini app' })

function onTwitterButtonClick() {
  shareTo({ platform: 'twitter' })
}

function onShareButtonClick() {
  showShareMenu()
}

Param

KeyValue TypeValue ExampleRequiredDefaultComment
platformSharePlatform'twitter'true-

SharePlatform will be one of:

type SharePlatform =
  | 'line'
  | 'twitter'
  | 'facebook'
  | 'messenger'
  | 'mail'
  | 'wechatMessage'
  | 'wechatMoments'
  | 'copyLink'
  | 'system'

Coupon

chooseCoupon

Open a native dialog to guide user choose their coupon.

There are 4 scenes of calling the method:

  1. SuccessPayload with couponId: User has coupon and select a coupon.
  2. SuccessPayload with no couponId: User has coupon and decide not using.
  3. ErrorPayload with -1 ErrCode: User close the native dialog with exit current flow.
  4. SuccessPayload with no couponId: User has no coupon. native dialog will not be shown.

A typical code example will be:

async function makePayment() {
  const { couponId } = await chooseCoupon({ defaultCouponId: 'foo' })
  // if an cancel error occur, the flow will not continue
  await request('/make-my-mini-app-payment', { data: { couponId } })
}

Param

KeyTypeExampleRequiredDefaultComment
defaultCouponIdstring?"1517390046445137921"false-If user has the coupon when calling the method, it will be selected by default.

SuccessPayload

KeyTypeExampleComment
couponIdstring?--

ErrorPayload

ErrCodeErrMessage
-1user cancel choosing coupon, not continue with no coupon

Payment

requestBindPayment

Call a native Popover to help user add / bind or update a legal payment method.

You should call this method after your back-end request SPOT payment failed, and:

  • Re-call your back-end after this method successed
  • Show error message after this method failed

ErrorPayload

ErrCodeErrMessage
-1user cancel this payment

Location

getLocation

Get current location.

SuccessPayload

KeyValue TypeValue ExampleComment
latitudenumber--
longitudenumber--

ErrorPayload

ErrCodeErrMessage
-2Permission deny, check "Permission" Section

startLocationUpdate

Enable location real-time updating feature

stopLocationUpdate

Disable location real-time updating feature

onLocationChange

Get the real-time location result

SuccessPayload

As same as getLocation

offLocationChange

Stop listening location change event

navigateLocation

Navigate to specific location, from current location.

Param

KeyValue TypeValue ExampleRequiredDefaultComment
latitudenumber35.680323true-Destination latitude
longitudenumber139.764582true-Destination longitude
namestring?'Yurakucho'false-Optional destination name
navigateLocation({
  latitude: 35.680323,
  longitude 139.764582,
  name: 'Yurakucho',
})

Bluetooth

A simplest Bluetooth flow is:

  1. openBluetoothAdapter()
  2. startBluetoothDevicesDiscovery()
  3. getBluetoothDevices()
  4. createBLEConnection()
  5. getBLEDeviceServices()
  6. getBLEDeviceCharacteristics()
  7. readBLECharacteristicValue()
  8. writeBLECharacteristicValue()

openBluetoothAdapter

Open Bluetooth adpater.

closeBluetoothAdapter

Close Bluetooth adapter

getBluetoothAdapterState

Get current bluetooth adapter state

SuccessPayload

KeyValue TypeValue ExampleComment
stateAdapterState--

AdapterState

KeyValue TypeValue ExampleComment
discoveringboolean--
availableboolean--

onBluetoothAdapterStateChange

Listen Bluetooth adapter state change event

SuccessPayload

KeyValue TypeValue ExampleComment
stateAdapterState--

offBluetoothAdapterStateChange

Unlisten Bluetooth adapter state change event

startBluetoothDevicesDiscovery

Start discovering devices

Param

KeyValue TypeValue ExampleRequiredDefaultComment
allowDuplicatesKeybooleanfalsefalsefalse-
intervalnumber1000false0interval in millseconds
startBluetoothDevicesDiscovery({
  allowDuplicatesKey: false,
  interval: 300,
}).catch((error: ErrorPayload) => {
  console.log(error)
})

stopBluetoothDevicesDiscovery

Stop discv

Error Payload

TBD.

CodeMessageComment
10001'not available'-

getBluetoothDevices

Get discovered devices during start and end

SuccessPayload

KeyValue TypeValue ExampleComment
devicesDevice[]-device list

Device

KeyValue TypeValue ExampleComment
namestring'My MacBook Pro'-
deviceIdstring--
RSSInumber--
advertisDatastring--
advertisServiceUUIDsstring[]--
localNamestring[]--
serviceDatastring[]--

Example

async function getDevices() {
  await startBluetoothDevicesDiscovery()

  const { devices } = await getBluetoothDevices()
  devices.map((device) => {
    console.log(device.name) // 'My MacBook Pro'
  })
}

onBluetoothDeviceFound

New devices found event

SuccessPayload

KeyValue TypeValue ExampleComment
devicesDevice[]-device list

offBluetoothDeviceFound

Pair with onBluetoothDeviceFound

createBLEConnection

Create BLE Connection with device

Param

KeyValue TypeValue ExampleRequiredDefaultComment
deviceIdstring'629FA080-FACC-8DEB-8C57-40985EC4A153'true-device id

Example

createBLEConnection({ deviceId: '629FA080-FACC-8DEB-8C57-40985EC4A153' })

closeBLEConnection

close connection with the specific device.

Param

KeyValue TypeValue ExampleRequiredDefaultComment
deviceIdstring'629FA080-FACC-8DEB-8C57-40985EC4A153'true-device id

onBLEConnectionStateChange

Listen to the connection state change event

SuccessPayload

KeyValue TypeValue ExampleComment
deviceIdstring'629FA080-FACC-8DEB-8C57-40985EC4A153'device id
connectedbooleantrue-

Example

createBLEConnection({ deviceId: '629FA080-FACC-8DEB-8C57-40985EC4A153' })

onBLEConnectionStateChange((payload) => {
  console.log(payload.deviceId) // '629FA080-FACC-8DEB-8C57-40985EC4A153'
  console.log(payload.connected) // true
})

offBLEConnectionStateChange

Pair with onBLEConnectionStateChange

getBLEDeviceRSSI

Get device RSSI

Param

KeyValue TypeValue ExampleRequiredDefaultComment
deviceIdstring'629FA080-FACC-8DEB-8C57-40985EC4A153'true-device id

SuccessPayload

KeyValue TypeValue ExampleComment
RSSInumber-Received Signal Strength Indicator

getBLEDeviceServices

Get device service list

Param

KeyValue TypeValue ExampleRequiredDefaultComment
deviceIdstring'629FA080-FACC-8DEB-8C57-40985EC4A153'true-device id

SuccessPayload

KeyValue TypeValue ExampleComment
servicesDeviceService[]-service list

DeviceService

KeyValue TypeValue ExampleComment
uuidstring--
isPrimaryboolean--

getBLEDeviceCharacteristics

Get device service list

Param

KeyValue TypeValue ExampleRequiredDefaultComment
deviceIdstring-true-device id
serviceIdstring-true-service id

SuccessPayload

KeyValue TypeValue ExampleComment
characteristicsDeviceCharacteristic[]-characteristics list

DeviceCharacteristic

KeyValue TypeValue ExampleComment
uuidstring--
propertiesDeviceCharacteristicProperty--

DeviceCharacteristicProperty

KeyValue TypeValue ExampleComment
readboolean--
writeboolean--
notifyboolean--
indicateboolean--

readBLECharacteristicValue

Read characteristic value.

Notice: You will get response on onBLECharacteristicValueChange event

Param

KeyValue TypeValue ExampleRequiredDefaultComment
deviceIdstring-true-device id
serviceIdstring-true-service id
characteristicIdstring-true-characteristic id

onBLECharacteristicValueChange

Listen characteristic changing.

SuccessPayload

KeyValue TypeValue ExampleComment
deviceIdstring-device id
serviceIdstring-service id
characteristicIdstring-characteristic id
valuestring'YmFzZTY0IGRlY29kZXI='Bytecode dharacteristic value encoded in Base64

Example

readBLECharacteristicValue({
  deviceId: 'foo',
  serviceId: 'bar',
  characteristicId: 'baz',
})

// get the read result from the event
onBLECharacteristicValueChange(
  ({ deviceId, serviceId, characteristicId, value }) => {
    console.log(deviceId) // 'foo'
    console.log(serviceId) // 'bar'
    console.log(characteristicId) // 'baz'
    console.log(value) // 'YmFzZTY0IGRlY29kZXI='
  }
)

offBLECharacteristicValueChange

Pair with onBLECharacteristicValueChange

writeBLECharacteristicValue

Param

KeyValue TypeValue ExampleRequiredDefaultComment
deviceIdstring-true-device id
serviceIdstring-true-service id
characteristicIdstring-true-characteristic id
valuestring'YmFzZTY0IGRlY29kZXI='true-Bytecode dharacteristic value encoded in Base64

notifyBLECharacteristicValueChange

KeyValue TypeValue ExampleComment
deviceIdstring-device id
serviceIdstring-service id
characteristicIdstring-characteristic id
statebooleantruestart characteristic notify event (if supported)
0.22.1

3 months ago

0.22.0

4 months ago

0.21.1

5 months ago

0.21.0

5 months ago

0.20.0

7 months ago

0.19.0

10 months ago

0.19.1

10 months ago

0.18.1

11 months ago

0.18.0

11 months ago

0.17.1

1 year ago

0.17.0

1 year ago

0.16.0

1 year ago

0.13.0

2 years ago

0.13.1

2 years ago

0.15.0

2 years ago

0.13.2

2 years ago

0.11.4

2 years ago

0.11.5

2 years ago

0.12.0

2 years ago

0.14.0

2 years ago

0.14.1

2 years ago

0.14.2

2 years ago

0.11.2

2 years ago

0.11.3

2 years ago

0.11.0

2 years ago

0.10.1

2 years ago

0.11.1

2 years ago

0.10.2

2 years ago

0.10.0

2 years ago

0.8.11

2 years ago

0.8.10

2 years ago

0.9.0

2 years ago

0.9.1

2 years ago

0.8.9

2 years ago

0.8.8

2 years ago

0.8.5

2 years ago

0.8.4

2 years ago

0.8.7

2 years ago

0.8.6

2 years ago

0.8.1

2 years ago

0.8.0

2 years ago

0.7.1

2 years ago

0.8.3

2 years ago

0.8.2

2 years ago

0.7.0

2 years ago

0.6.0

2 years ago

0.5.0

2 years ago

0.4.1

3 years ago

0.4.0

3 years ago

0.3.0

3 years ago

0.3.1

3 years ago

0.2.2

3 years ago

0.2.1

3 years ago

0.1.0

3 years ago

0.0.3

3 years ago

0.2.0

3 years ago

0.0.2

3 years ago

0.0.4

3 years ago

0.0.1

3 years ago