Options
All
  • Public
  • Public/Protected
  • All
Menu

@voucherify/sdk - v2.8.1

Official Voucherify JS SDK

Build Status SDK NPM Version SDK NPM Downloads


Documentation | Installation | Marketer-ready Voucherify snippet | Migration | Typescript | Error handling | Contributing | Changelog

Server side: Setup | Methods | Vouchers | Campaigns | Distributions | Validations | Redemptions | Customers | Consents | Orders | Products | Rewards | Loyalties | Segments | Validation Rules | Promotions | Events | Async Actions | Metadata Schemas | Api Limits Handler

Client side: Setup | Methods

Voucherify JS SDK is a JavaScript SDK which is fully consistent with restful API Voucherify provides and has fully integrated TypeScript support. It also combines together our previously maintained Voucherify Node.js SDK and Voucherify.js.

Learn more about Voucherify by visiting our site.

๐Ÿ“ Documentation

You will find detailed description and example responses at our official documentation. Most method headers point to more detailed descriptions of arguments you can use.

You can also use our detailed documentation provided by our package here.

๐Ÿ“š Want to learn more? Visit our official site or our Success Portal.

๐Ÿ‘ฝ Having troubles? Check our Help center.

๐Ÿงช Looking for promotion ideas? Check our Cookbook to get an inspiration.

โš™๏ธ Installation

Local installation:

npm install @voucherify/sdk --save

CDN installation:

<script
    type="text/javascript"
    src="https://unpkg.com/@voucherify/sdk/dist/voucherifysdk.umd.production.min.js"
    crossorigin
></script>

Then, login to your Voucherify Dashboard and get your API keys from Configuration.

๐Ÿค– Server Side

Setup

const { VoucherifyServerSide } = require('@voucherify/sdk')

// import { VoucherifyServerSide } from '@voucherify/sdk' ES6 compatible

const client = VoucherifyServerSide({
    applicationId: 'YOUR-APPLICATION-ID',
    secretKey: 'YOUR-SECRET-KEY',
    apiUrl: 'https://<region>.api.voucherify.io', // optional
    apiVersion: 'v2018-08-01', // optional
    channel: 'e-commerce', // optional
    customHeaders: { "MY_CUSTOM_HEADER": "my_value" }, // optional
    timeoutMs: 10000 // optional
})

Methods

Vouchers

Methods are provided within client.vouchers.* namespace.

Create Voucher

client.vouchers.create(voucher)

Check voucher object.

Get Voucher

client.vouchers.get(code)

Update Voucher

client.vouchers.update(voucher)

Delete Voucher

client.vouchers.delete(code)
client.vouchers.delete(code, params)

List Vouchers

client.vouchers.list()
client.vouchers.list(params)

Enable Voucher

client.vouchers.enable(code)

Disable Voucher

client.vouchers.disable(code)

Add Gift Voucher Balance

client.vouchers.balance.create(code, params)

Import Vouchers

client.vouchers.import(vouchers)

Examine Vouchers Qualification

client.vouchers.qualifications.examine(body, params)

Update Vouchers Metadata in bulk

client.vouchers.bulkUpdateMetadata(params)

Update Vouchers in bulk

client.vouchers.bulkUpdate(vouchers)

Release Validation Session

client.vouchers.releaseValidationSession(code, sessionKey)

Import Vouchers using CSV

client.vouchers.importCSV(filePath)

List Voucher Transactions

client.vouchers.listTransactions(code, query)

Export Voucher Transactions

client.vouchers.exportTransactions(code, body)

Campaigns

Methods are provided within client.campaigns.* namespace.

Create Campaign

client.campaigns.create(campaign)

Update Campaign

client.campaigns.update(campaignId, campaign)
client.campaigns.update(campaignName, campaign)

Method will update only fields passed to campaign argument.

Get Campaign

client.campaigns.get(name)

Delete Campaign

client.campaigns.delete(campaignName)
client.campaigns.delete(campaignName, params)

Add Voucher to Campaign

client.campaigns.addVoucher(campaignName)
client.campaigns.addVoucher(campaignName, body)
client.campaigns.addVoucher(campaignName, body, params)

Add certain Voucher to Campaign

client.campaigns.addCertainVoucher(campaignName, code, codeParams)
client.campaigns.addCertainVoucher(campaignName, code)

Import Vouchers to Campaign

client.campaigns.importVouchers(campaignName, vouchers)

List Campaigns

client.campaigns.list()
client.campaigns.list(params)

Import Vouchers to Campaign by CSV

client.campaigns.importVouchersCSV(campaignId, filePath)

Enable campaign

client.campaigns.enable(campaignId)

Disable campaign

client.campaigns.disable(campaignId)

Examine Campaigns Qualification

client.campaigns.qualifications.examine(body)
client.campaigns.qualifications.examine(body, params)

Distributions

Methods are provided within client.distributions.* namespace.

Create Export

client.distributions.exports.create(exportObject)

Check the export object.

List Exports

client.distributions.exports.list()

Get Export

client.distributions.exports.get(exportId)

Delete Export

client.distributions.exports.delete(exportId)

List publications

client.distributions.publications.list()
client.distributions.publications.list(params)

Create publication

client.distributions.publications.create(params)

Categories

Methods are provided within client.categories.* namespace.

Create Category

client.categories.create(params)

Update Category

client.categories.update(categoryId, params)

Get Category

client.categories.get(categoryId)

Delete Category

client.categories.delete(categoryId)

List Categories

client.categories.list()

Qualifications

Methods are provided within client.qualifications.* or client.promotions.* namespace.

Check Eligibility

client.qualifications.checkEligibility(body)

Validations

Methods are provided within client.validations.* or client.promotions.* namespace.

Validate Voucher

client.validations.validateVoucher(code)
client.validations.validateVoucher(code, params)

Other possibility

client.validations.validate(code)
client.validations.validate(code, params)

Validate Promotion Campaign

client.promotions.validate(params)

Other possibility

client.validations.validate(params)

Validate Stackable

client.validations.validateStackable(params)

Redemptions

Methods are provided within client.redemptions.* namespace.

Redeem Voucher

client.redemptions.redeem(code)
client.redemptions.redeem(code, params)

Redeem Stackable

client.redemptions.redeemStackable(params)

Get Redemption

client.redemptions.get(redemptionId)

List Redemptions

client.redemptions.list()
client.redemptions.list(params)

Get Voucher's Redemptions

client.redemptions.getForVoucher(code)

Rollback Redemption

client.redemptions.rollback(redemptionId)
client.redemptions.rollback(redemptionId, params)

Rollback Stackable

client.redemptions.rollbackStackable(parentRedemptionId)
client.redemptions.rollbackStackable(parentRedemptionId, params, queryParams)

Check redemption rollback object.


Promotions

Methods are provided within client.promotions.* namespace.

Read how to Validate Promotion Campaign in Validations section

Create Promotion Campaign

client.promotions.create(promotionCampaign)

Check promotion campaign object.

List Promotion's Tiers

client.promotions.tiers.list(promotionCampaignId)

Check promotion's tier object

Get Promotion Tier

client.promotions.tiers.get(tierId)

Check promotion's tier object

List All Promotion Tiers

client.promotions.tiers.listAll()
client.promotions.tiers.listAll(params)

Add Promotion Tier to Campaign

client.promotions.tiers.create(promotionId, params)

Redeem Promotion

client.promotions.tiers.redeem(promotionsTierId, params)

Update Promotion Tier

client.promotions.tiers.update(promotionsTier)

Delete Promotion Tier

client.promotions.tiers.delete(promotionsTierId)

Customers

Methods are provided within client.customers.* namespace.

Create Customer

client.customers.create(customer)

Check customer object.

Get Customer

client.customers.get(customerId)

Update Customer

client.customers.update(customer)

customer object must contain id or source_id.

Delete Customer

client.customers.delete(customerId)

Delete Customer Permanently

client.customers.deletePermanently(customerId)

List Customers

client.customers.list()
client.customers.list(params)

Standard list customers API has limitation of available pages to be shown equal to 100. To cover cases when you would like to fetch more, you must use scroll capabilities as shown below.

Scroll through customers

async function () {
  for await (const customer of client.customers.scroll(params)) {
    console.log('Customer', customer)
  }
}

With optional arguments

async function () {
  for await (const customer of client.customers.scroll({
    starting_after: "2020-01-01", // optional
    order: "created_at" // default: "-created_at"
    ...params})
  ) {
    console.log('Customer', customer)
  }
}

params argument is consistent with client.customers.list() method.

You can optionally define scrolling cursor based on customer creation date using property starting_after. By default returned customers are in descending order, if you want to change it to ascending define order equal to created_at.

Keep in mind this operation may drain your API call limits fairly quickly - each api call fetches 100 customers. So if you have 100.000 customers, you will use 1000 API calls.

Update Customer's Consents - Deprecated

client.customers.updateConsents(customer, consents)

List Customer's Activity

client.customers.listActivity(customerIdOrSourceId, params)

List Customers Activities - Deprecated - use listActivity

client.customers.listActivities(customerId)
client.customers.listActivities(customerId, params)

Import and Update Customers using CSV

client.customers.importCSV(filePath)

Update Customers in bulk

client.customers.updateInBulk(customers)

Update Customers' Metadata in bulk

client.customers.updateMetadataInBulk(sourceIdsAndMetadata)

List Redeemables

client.customers.listRedeemables(id, params)

Consents - Deprecated

Methods are provided within client.consents.* namespace.

Get Consents - Deprecated

client.consents.list()

Orders

Methods are provided within client.orders.* namespace.

Create Order

client.orders.create(order)

Check the order object.

Get Order

client.orders.get(orderId)

Update Order

client.orders.update(order)

order object must contain id or source_id.

List Orders

client.orders.list()
client.orders.list(params)

Import Orders

client.orders.import(orders)

Products

Methods are provided within client.products.* namespace.

Create Product

client.products.create(product)

Check product object.

Get Product

client.products.get(productId)

Update Product

client.products.update(product)

Delete Product

client.products.delete(productId)
client.products.delete(productId, { force: true })

Update Products in Bulk

client.products.bulkUpdate(products)

List Products

client.products.list()
client.products.list(params)

Create SKU

client.products.createSku(productId, sku)

Check SKU object.

Get SKU

client.products.getSku(productId, skuId)

Update SKU

client.products.updateSku(productId, sku)

Delete SKU

client.products.deleteSku(productId, skuId)
client.products.deleteSku(productId, skuId, { force: true })

List all product SKUs

client.products.listSkus(productId)

Import SKUs using CSV

client.products.importSkusCSV(filePath)

Import Products using CSV

client.products.importCSV(filePath)

Product Collections

Methods are provided within client.productCollections.* namespace.

List Product Collections

client.productCollections.list()

Create Product Collection

client.productCollections.create(productCollection)

Get Product Collection

client.productCollections.get(productCollectionId)

Delete Product Collection

client.productCollections.delete(productCollectionId)

List Products in Collection

client.productCollections.listProducts(productCollectionId)

Rewards

Methods are provided within client.rewards.* namespace.

Create Reward

client.rewards.create(reward)

Check reward object.

Get Reward

client.rewards.get(rewardId)

Update Reward

client.rewards.update(reward)

Delete Reward

client.rewards.delete(rewardId)

List Rewards

client.rewards.list()
client.rewards.list(params)

Get Reward Assignment

client.rewards.getAssignment(rewardId, assignment)

Create Reward Assignment

client.rewards.createAssignment(rewardId, assignment)

Check reward assignment object.

Update Reward Assignment

client.rewards.updateAssignment(rewardId, assignment)

Delete Reward Assignment

client.rewards.deleteAssignment(rewardId, assignmentId)

List Reward Assignments

client.rewards.listAssignments(rewardId)
client.rewards.listAssignments(rewardId, params)

Loyalties

Methods are provided within client.loyalties.* namespace.

Create Loyalty Program

client.loyalties.create(campaign)

Get Loyalty Program

client.loyalties.get(campaignId)

Update Loyalty Program

client.loyalties.update(campaign)

Delete Loyalty Program

client.loyalties.delete(campaignId)

List Loyalty Programs

client.loyalties.list()
client.loyalties.list(params)

Create Loyalty Program Reward Assignment

client.loyalties.createRewardAssignments(campaignId, assignment)

Update Loyalty Program Reward Assignment

client.loyalties.updateRewardAssignment(campaignId, assignment)

Delete Loyalty Program Reward Assignment

client.loyalties.deleteRewardAssignment(campaignId, assignmentId)

Get Loyalty Program Reward Assignment

client.loyalties.getRewardAssignment(campaignId, assignmentId)

List Loyalty Program Reward Assignments

client.loyalties.listRewardAssignments(campaignId)
client.loyalties.listRewardAssignments(campaignId, params)

Create Loyalty Program Earning Rules

client.loyalties.createEarningRule(campaignId, earningRules)

Update Loyalty Program Earning Rule

client.loyalties.updateEarningRule(campaignId, earningRule)

Delete Loyalty Program Earning Rule

client.loyalties.deleteEarningRule(campaignId, earningRuleId)

Get Loyalty Program Earning Rule

client.loyalties.getEarningRule(campaignId, earningRuleId)

Enable Loyalty Program Earning Rule

client.loyalties.enableEarningRule(campaignId, earningRuleId)

Disable Loyalty Program Earning Rule

client.loyalties.disableEarningRule(campaignId, earningRuleId)

List Loyalty Program Earning Rules

client.loyalties.listEarningRules(campaignId)
client.loyalties.listEarningRules(campaignId, params)

Create Loyalty Program Member

client.loyalties.createMember(campaignId, member)

Get Loyalty Program Member

Depending on the parameters, this method sends requests to v1/loyalties/members/{memberId} or v1/loyalties/{campaignId}/members/{memberId} API endpoint

client.loyalties.getMember(campaignId, memberId)

List Loyalty Program Members

client.loyalties.listMembers(campaignId)
client.loyalties.listMembers(campaignId, params)

Get Loyalty Program Member Activities

Depending on the parameters, this method sends requests to v1/loyalties/members/{memberId}/activities or v1/loyalties/{campaignId}/members/{memberId}/activities API endpoint

client.loyalties.getMemberActivities(campaignId, memberId)

memberId referrers to Loyalty Card code.

List Member Rewards

client.loyalties.listMemberRewards(memberId, params)

memberId referrers to Loyalty Card code.


Add Or Remove Loyalty Card Balance

Depending on the parameters, this method sends requests to v1/loyalties/members/{memberId}/balance or v1/loyalties/{campaignId}/members/{memberId}/balance API endpoint

client.loyalties.addOrRemoveCardBalance(memberId, balance, campaignId)

memberId referrers to Loyalty Card code.

Add Loyalty Card Balance

client.loyalties.addPoints(campaignId, memberId, balance)

memberId referrers to Loyalty Card code.

Transfer Loyalty Points

client.loyalties.transferPoints(campaignId, memberId, transferLoyaltyPoints)

memberId referrers to Loyalty Card code.


Get Loyalty Points Expiration

client.loyalties.getPointsExpiration(campaignId, memberId)

memberId referrers to Loyalty Card code.


[Redeem Loyalty Card]

client.loyalties.redeemReward(campaignId, memberId, params)

memberId referrers to Loyalty Card code.

When redeeming reward with type COIN you need to provide additional order object in the params

List Loyalty Tier Rewards

client.loyalties.listLoyaltyTierRewards(campaignId, tierId)

List Loyalty Card Transactions

Depending on the parameters, this method sends requests to v1/loyalties/members/{memberId}/transactions or v1/loyalties/{campaignId}/members/{memberId}/transactions API endpoint

client.loyalties.listCardTransactions(memberId, campaignId, params)

memberId referrers to Loyalty Card code.


Export Loyalty Card Transactions

Depending on the parameters, this method sends requests to v1/loyalties/members/{memberId}/transactions/export or v1/loyalties/{campaignId}/members/{memberId}/transactions/export API endpoint

client.loyalties.exportCardTransactions(memberId, campaignId, params)

memberId referrers to Loyalty Card code.


Get Reward Assignment

client.loyalties.getRewardAssignment(campaignId, assignmentId)

Get Reward Details

client.loyalties.getRewardDetails(campaignId, assignmentId)

List Loyalty Tiers

client.loyalties.listTiers(campaignId, params)
client.loyalties.listTiers(campaignId)

Get Loyalty Tier

client.loyalties.getTier(campaignId, tierId)

Create Loyalty Tiers

client.loyalties.createTiers(campaignId, tiers)

List Loyalty Tier Earning Rules

client.loyalties.listLoyaltyTierEarningRules(campaignId, tierId, params)
client.loyalties.listLoyaltyTierEarningRules(campaignId, tierId)

List Member Loyalty Tiers

client.loyalties.listMemberLoyaltyTiers(memberId)

memberId referrers to Loyalty Card code.


Segments

Methods are provided within client.segments.* namespace.

Create Segment

client.segments.create(segment)

Check the segment object.

Get Segment

client.segments.get(segmentId)

Delete Segment

client.segments.delete(segmentId)

Validation Rules

Methods are provided within client.validationRules.* namespace.

Create Validation Rule

client.validationRules.create(validationRule)

Check validation rule object.

Get Validation Rule

client.validationRules.get(validationRuleId)

Update Validation Rule

client.validationRules.update(validationRule)

Delete Validation Rule

client.validationRules.delete(validationRuleId)

Create Validation Rule Assignment

client.validationRules.createAssignment(validationRuleId, assignment)

Delete Validation Rule Assignment

client.validationRules.deleteAssignment(validationRuleId, assignmentId)

List Validation Rules

client.validationRules.list()
client.validationRules.list(params)

List Validation Rule Assignments

client.validationRules.listAssignments(validationRuleId)
client.validationRules.listAssignments(validationRuleId, params)

List Validation Rules Assignments

client.validationRules.listRulesAssignments(validationRuleId)
client.validationRules.listRulesAssignments(validationRuleId, params)

Events

Methods are provided within client.events.* namespace.

Create Custom Event

client.events.create(eventName, { customer })
client.events.create(eventName, { customer, metadata })
client.events.create(eventName, { customer, referral, metadata })
client.events.create(eventName, { customer, referral, loyalty, metadata })

Check customer object.

Async Actions

Methods are provided within client.asyncActions.* namespace.

Get Async Action

client.asyncActions.get(asyncActionId)

List Async Actions

client.asyncActions.list()
client.asyncActions.list(params)

Metadata Schemas

Methods are provided within client.metadataSchemas.* namespace.

List Metadata Schemas

client.metadataSchemas.list()

Get Metadata Schema by schema name

client.metadataSchemas.get(schemaName)

Api Limits Handler

Methods are provided within client.apiLimitsHandler.* namespace.

Are Limits Available

client.apiLimitsHandler.areLimitsAvailable()

This method should be called each time beforehand Get Rate Limit or Get Rate Limit Remaining or Get Retry After to ensure limit data are available.

Get Rate Limit

if(client.apiLimitsHandler.areLimitsAvailable()){
  client.apiLimitsHandler.getRateLimit()
}

Get Rate Limit Remaining

if(client.apiLimitsHandler.areLimitsAvailable()){
  client.apiLimitsHandler.getRateLimitRemaining()
}

Get Retry After

if(client.apiLimitsHandler.areLimitsAvailable()){
  client.apiLimitsHandler.getRetryAfter()
}

๐Ÿ’… Client Side

Setup

const { VoucherifyClientSide } = require('@voucherify/sdk')

const client = VoucherifyClientSide({
    clientApplicationId: 'YOUR-APPLICATION-ID',
    clientSecretKey: 'YOUR-CLIENT-SECRET-KEY',
    apiUrl: 'https://<region>.api.voucherify.io', // optional
    origin: 'example.com', // read more below
    customHeaders: { "MY_CUSTOM_HEADER": "my_value" } // optional
    timeoutMs: 10000 // optional
})

The origin property is required in Node.js, but when using in client-side environment (in browser) this option will be ignored.

We are tracking users which are validating vouchers with those who consume them by a tracking_id. For that we are setting up an identity for the user.

client.setIdentity('gustav@purpleson.com')

Methods

Methods are provided within client.* namespace.

Set Identity

client.setIdentity(trackingId)

Validate

client.validate(params)

Validate Stackable Client Side

client.validateStackable(params)

Redeem

client.redeem(code, payload)

Redeem Stackable Client Side

client.redeemStackable(params)

Publish

client.publish(campaignName, payload)
client.publish(campaignName, payload, queryParams)

List vouchers

client.listVouchers()
client.listVouchers(params)

Create customer

client.createCustomer(customer)
client.createCustomer(customer, enableDoubleOptIn)

enableDoubleOptIn sets request header to {X-Voucherify-Double-Opt-In: true}, which forces user to confirm registration / subscription.

List consents

client.listConsents()

Update consents

client.updateConsents(idOrSourceId, consents)

Track custom events

client.track(eventName, metadata, customer)

Qualifications

client.qualifications(body)

๐ŸŽ Marketer-ready Voucherify snippet

Go here for more HTML-based examples

<body>
  <div id="voucher-validate"></div>

  <link rel="stylesheet" type="text/css" href="https://unpkg.com/@voucherify/react-widget@0.0.5/dist/voucherify.css" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/qs/6.5.1/qs.min.js" crossorigin></script>
  <script src="https://unpkg.com/react@17/umd/react.production.min.js" crossorigin></script>
  <script src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js" crossorigin></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js" crossorigin></script>
  <script type="text/javascript" src="https://unpkg.com/@voucherify/sdk@0.0.5/dist/voucherifysdk.umd.production.min.js" crossorigin></script>
  <script type="text/javascript" src="https://unpkg.com/@voucherify/react-widget@0.0.5/dist/voucherifywidget.umd.production.min.js" crossorigin></script>

  <script type="text/javascript">
    window.ReactDOM.render(
      window.React.createElement(VoucherifyWidget.VoucherifyValidate, {
        clientApplicationId: 'CLIENT-APPLICATION-ID',
        clientSecretKey: 'CLIENT-SECRET-KEY',
        amount: true,
      }),
      document.querySelector('#voucher-validate'),
    )
  </script>
</body>

โ†”๏ธ Migration

Check our MIGRATION GUIDE to learn more about switching to our newest SDK.

๐Ÿฆธ TypeScript

Voucherify JS SDK includes TypeScript declarations for our latest API. We recommend using TypeScript Version 4.2.

You can find TS example in examples/with-nodejs-typescript.

๐Ÿ˜จ Error handling

Voucherify error object always has consistent structure, described in details in our API reference.

If you wish to see code examples for server-side error handling, you can check it here:

Structure / typing for error returned from Voucherify API can be seen here:

If you wish to receive original AxiosError when VoucherifyError is thrown then you need to explicitly set exposeErrorCause property to true when creating instance of VouchierfyClient, ie:

const voucherify = VoucherifyServerSide({
    applicationId: 'APPLICATION-ID',
    secretKey: 'SECRET-KEY',
    exposeErrorCause: true
})

Original AxiosError will be available under cause property of VoucherifyError

๐Ÿ‘ด Legacy Voucherify JS SDKs

Legacy client-side Voucherify JS SDK is available here: voucherify.js.

Legacy server-side Voucherify JS SDK is available here: voucherify-nodejs-sdk.

๐Ÿ› ๏ธ Contributing

Bug reports and pull requests are welcome through GitHub Issues.

Read more about how to Contribute to Voucherify JS SDK by visiting CONTRIBUTING.md

๐Ÿ—„๏ธ Changelog

Visit CHANGELOG to learn more about new changes.

Voucherify React Widget CHANGELOG can be found here