@voucherify/sdk
TypeScript icon, indicating that this package has built-in type declarations

2.7.2 • Public • Published

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.

client.vouchers.create(voucher)

Check voucher object.

client.vouchers.get(code)
client.vouchers.update(voucher)
client.vouchers.delete(code)
client.vouchers.delete(code, params)
client.vouchers.list()
client.vouchers.list(params)
client.vouchers.enable(code)
client.vouchers.disable(code)
client.vouchers.balance.create(code, params)
client.vouchers.import(vouchers)
client.vouchers.qualifications.examine(body, params)
client.vouchers.bulkUpdateMetadata(params)
client.vouchers.bulkUpdate(vouchers)
client.vouchers.releaseValidationSession(code, sessionKey)
client.vouchers.importCSV(filePath)
client.vouchers.listTransactions(code, query)
client.vouchers.exportTransactions(code, body)

Campaigns

Methods are provided within client.campaigns.* namespace.

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

Method will update only fields passed to campaign argument.

client.campaigns.get(name)
client.campaigns.delete(campaignName)
client.campaigns.delete(campaignName, params)
client.campaigns.addVoucher(campaignName)
client.campaigns.addVoucher(campaignName, body)
client.campaigns.addVoucher(campaignName, body, params)
client.campaigns.addCertainVoucher(campaignName, code, codeParams)
client.campaigns.addCertainVoucher(campaignName, code)
client.campaigns.importVouchers(campaignName, vouchers)
client.campaigns.list()
client.campaigns.list(params)
client.campaigns.importVouchersCSV(campaignId, filePath)
client.campaigns.enable(campaignId)
client.campaigns.disable(campaignId)
client.campaigns.qualifications.examine(body)
client.campaigns.qualifications.examine(body, params)

Distributions

Methods are provided within client.distributions.* namespace.

client.distributions.exports.create(exportObject)

Check the export object.

client.distributions.exports.list()
client.distributions.exports.get(exportId)
client.distributions.exports.delete(exportId)
client.distributions.publications.list()
client.distributions.publications.list(params)
client.distributions.publications.create(params)

Categories

Methods are provided within client.categories.* namespace.

client.categories.create(params)
client.categories.update(categoryId, params)
client.categories.get(categoryId)
client.categories.delete(categoryId)
client.categories.list()

Qualifications

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

client.qualifications.checkEligibility(body)

Validations

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

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

Other possibility

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

Other possibility

client.validations.validate(params)
client.validations.validateStackable(params)

Redemptions

Methods are provided within client.redemptions.* namespace.

client.redemptions.redeem(code)
client.redemptions.redeem(code, params)
client.redemptions.redeemStackable(params)
client.redemptions.get(redemptionId)
client.redemptions.list()
client.redemptions.list(params)
client.redemptions.getForVoucher(code)
client.redemptions.rollback(redemptionId)
client.redemptions.rollback(redemptionId, params)
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

client.promotions.create(promotionCampaign)

Check promotion campaign object.

client.promotions.tiers.list(promotionCampaignId)

Check promotion's tier object

client.promotions.tiers.get(tierId)

Check promotion's tier object

client.promotions.tiers.listAll()
client.promotions.tiers.listAll(params)
client.promotions.tiers.create(promotionId, params)
client.promotions.tiers.redeem(promotionsTierId, params)
client.promotions.tiers.update(promotionsTier)
client.promotions.tiers.delete(promotionsTierId)

Customers

Methods are provided within client.customers.* namespace.

client.customers.create(customer)

Check customer object.

client.customers.get(customerId)
client.customers.update(customer)

customer object must contain id or source_id.

client.customers.delete(customerId)
client.customers.deletePermanently(customerId)
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.

client.customers.updateConsents(customer, consents)
client.customers.listActivities(customerId)
client.customers.listActivities(customerId, params)
client.customers.importCSV(filePath)
client.customers.updateInBulk(customers)
client.customers.updateMetadataInBulk(sourceIdsAndMetadata)
client.customers.listRedeemables(id, params)

Consents

Methods are provided within client.consents.* namespace.

You can update Customer's consents in client.customer.* namespace.

client.consents.list()

Orders

Methods are provided within client.orders.* namespace.

client.orders.create(order)

Check the order object.

client.orders.get(orderId)
client.orders.update(order)

order object must contain id or source_id.

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

Products

Methods are provided within client.products.* namespace.

client.products.create(product)

Check product object.

client.products.get(productId)
client.products.update(product)

Delete Product

client.products.delete(productId)
client.products.delete(productId, { force: true })
client.products.bulkUpdate(products)
client.products.list()
client.products.list(params)
client.products.createSku(productId, sku)

Check SKU object.

client.products.getSku(productId, skuId)
client.products.updateSku(productId, sku)
client.products.deleteSku(productId, skuId)
client.products.deleteSku(productId, skuId, { force: true })
client.products.listSkus(productId)
client.products.importSkusCSV(filePath)
client.products.importCSV(filePath)

Product Collections

Methods are provided within client.productCollections.* namespace.

client.productCollections.list()
client.productCollections.create(productCollection)
client.productCollections.get(productCollectionId)
client.productCollections.delete(productCollectionId)
client.productCollections.listProducts(productCollectionId)

Rewards

Methods are provided within client.rewards.* namespace.

client.rewards.create(reward)

Check reward object.

client.rewards.get(rewardId)
client.rewards.update(reward)
client.rewards.delete(rewardId)
client.rewards.list()
client.rewards.list(params)
client.rewards.getAssignment(rewardId, assignment)
client.rewards.createAssignment(rewardId, assignment)

Check reward assignment object.

client.rewards.updateAssignment(rewardId, assignment)
client.rewards.deleteAssignment(rewardId, assignmentId)
client.rewards.listAssignments(rewardId)
client.rewards.listAssignments(rewardId, params)

Loyalties

Methods are provided within client.loyalties.* namespace.

client.loyalties.create(campaign)
client.loyalties.get(campaignId)
client.loyalties.update(campaign)
client.loyalties.delete(campaignId)
client.loyalties.list()
client.loyalties.list(params)
client.loyalties.createRewardAssignments(campaignId, assignment)
client.loyalties.updateRewardAssignment(campaignId, assignment)
client.loyalties.deleteRewardAssignment(campaignId, assignmentId)
client.loyalties.getRewardAssignment(campaignId, assignmentId)
client.loyalties.listRewardAssignments(campaignId)
client.loyalties.listRewardAssignments(campaignId, params)
client.loyalties.createEarningRule(campaignId, earningRules)
client.loyalties.updateEarningRule(campaignId, earningRule)
client.loyalties.deleteEarningRule(campaignId, earningRuleId)
client.loyalties.getEarningRule(campaignId, earningRuleId)
client.loyalties.enableEarningRule(campaignId, earningRuleId)
client.loyalties.disableEarningRule(campaignId, earningRuleId)
client.loyalties.listEarningRules(campaignId)
client.loyalties.listEarningRules(campaignId, params)
client.loyalties.createMember(campaignId, 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)
client.loyalties.listMembers(campaignId)
client.loyalties.listMembers(campaignId, params)

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.

client.loyalties.listMemberRewards(memberId, params)

memberId referrers to Loyalty Card code.


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.

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

memberId referrers to Loyalty Card code.

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

memberId referrers to Loyalty Card code.


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

client.loyalties.listLoyaltyTierRewards(campaignId, tierId)

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.


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.


client.loyalties.getRewardAssignment(campaignId, assignmentId)

client.loyalties.getRewardDetails(campaignId, assignmentId)

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

client.loyalties.getTier(campaignId, tierId)

client.loyalties.createTiers(campaignId, tiers)

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

client.loyalties.listMemberLoyaltyTiers(memberId)

memberId referrers to Loyalty Card code.


Segments

Methods are provided within client.segments.* namespace.

client.segments.create(segment)

Check the segment object.

client.segments.get(segmentId)
client.segments.delete(segmentId)

Validation Rules

Methods are provided within client.validationRules.* namespace.

client.validationRules.create(validationRule)

Check validation rule object.

client.validationRules.get(validationRuleId)
client.validationRules.update(validationRule)
client.validationRules.delete(validationRuleId)
client.validationRules.createAssignment(validationRuleId, assignment)
client.validationRules.deleteAssignment(validationRuleId, assignmentId)
client.validationRules.list()
client.validationRules.list(params)
client.validationRules.listAssignments(validationRuleId)
client.validationRules.listAssignments(validationRuleId, params)
client.validationRules.listRulesAssignments(validationRuleId)
client.validationRules.listRulesAssignments(validationRuleId, params)

Events

Methods are provided within client.events.* namespace.

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.

client.asyncActions.get(asyncActionId)
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)
client.validate(params)
client.validateStackable(params)
client.redeem(code, payload)
client.redeemStackable(params)

Publish

client.publish(campaignName, payload)
client.publish(campaignName, payload, queryParams)
client.listVouchers()
client.listVouchers(params)
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.

client.listConsents()
client.updateConsents(idOrSourceId, consents)
client.track(eventName, metadata, customer)
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

Readme

Keywords

Package Sidebar

Install

npm i @voucherify/sdk

Weekly Downloads

5,396

Version

2.7.2

License

MIT

Unpacked Size

824 kB

Total Files

74

Last publish

Collaborators

  • rspective