Start typing to search...

@withkoji/iap (deprecated)

Warning

This package is deprecated and is included only for backwards compatibility. For new templates, use withkoji-koji-core.html.

The @withkoji/iap package enables you to implement in-app purchases from your Koji templates. For example, require a purchase to unlock a premium asset or a game. This package provides frontend methods, for managing transactions with users, and backend methods, for validating purchases against receipts.

To implement a basic purchase flow in your template, use getToken on the frontend to obtain the current user’s token. Then, use the callback function to route a request to the backend. On the backend, use resolveReceipts to determine whether the user has purchased the product and return appropriate information to the frontend. Finally, on the frontend, display the appropriate experience based on whether or not the product has been purchased. For example, display a premium image that has been purchased. Or, if the user hasn’t purchased the image, display a Purchase button and use startPurchase to initiate a transaction when the user clicks the button.

Install

Install the package in the frontend and backend services of your Koji project.

npm install --save @withkoji/iap
Important
To support instant remixes of your template, you must also install the withkoji-vcc-package.html package and implement the VccMiddleware on your backend server. This middleware maintains the environment variables for instant remixes, ensuring that purchases are applied to the correct remix version.

Iap

To enable in-app purchases for your Koji template, you must implement the Iap class and define the InAppPurchases entitlements.

new Iap(projectID, projectToken)

Instantiates Iap.

Parameters

  • projectID – (Backend only) String, unique identifier for the Koji.

  • projectToken – (Backend only) String, secret key for the Koji.

Tip
When instantiating Iap on the backend, you must provide these parameters, which are available as environment variables at runtime. For instant remixes, you must implement VccMiddleware to manage these variables. See withkoji-vcc-package.html.

Example

import Iap from '@withkoji/iap';

// Frontend
const iap = new Iap();

// Backend
const iap = new Iap(
  res.locals.KOJI_PROJECT_ID,
  res.locals.KOJI_PROJECT_TOKEN,
);

Iap methods

.getToken(handler, forceRefresh)

Gets a token identifying the current user, and invokes a callback function to handle backend requests for the user’s purchases.

Parameters

  • handlerFunction, handles backend requests for the user’s purchases. Receives the following property as input:

    • userTokenString, temporary token for the current user’s session.

      Note
      A user token is created when a logged-in user loads a Koji app, and destroyed when the user closes the app. If the user revisits the Koji app, a different token is generated. Tokens are specific to a user and a Koji app, so the same user will have different tokens for different apps. To resolve purchases for a given user, both the user token, obtained on the frontend, and the project token, obtained from environment variables on the backend, are necessary.
  • forceRefresh – (Optional) Boolean, indicates whether to generate a new user token before invoking the callback function (false by default).

Example

iap.getToken((token) => {
  // Request user's purchases and update template based on what has or has not been purchased
});

.loadProduct(sku)

Gets the properties for a specified product to enable the template to leverage dynamic product information. For example, you can check the stock for a product with limited quantity (via the numAvailable property), and indicate the number of remaining items.

Parameters

  • skuString, identifier for the product.

Returns

(Async) IapProduct object, properties of the specified product.

Example

const product = await iap.loadProduct(sku);

.resolveReceipts(userToken)

Retrieves the user’s receipts, which can be used to validate purchases for specific products.

Parameters

  • userTokenString, temporary token for the current user’s session. See getToken.

Returns

(Async) Array of IapReceipt objects, the user’s purchases.

Example

const receipts = await iap.resolveReceipts(token);
// Look for the SKU to determine whether the user has purchased the product
hasPurchased = !!(receipts.find(({ product }) => product.sku === 'productID'));

.resolveReceiptById(receiptId)

Retrieves a specific transaction receipt, which can be used to facilitate fulfillment. For example, use a dynamic receipt to upload a video response from the seller and then share that response with the buyer.

Parameters

  • receiptIdString, unique identifier for the receipt.

Returns

(Async) IapReceipt object for the specified receipt.

Example

const receipt = await iap.resolveReceiptById(token);
// Use custom attributes for a video response
this.setState({
  instructions: receipt.attributes.message,
  video: receipt.attributes.video,
});

.resolveReceiptsBySku(sku)

Retrieves all receipts for a specified product, which can be used to aggregate sales data.

Parameters

  • skuString, identifier for the product. Products are defined in the entitlements and registered or updated when the project is deployed.

Returns

(Async) Array of IapReceipt objects for the specified product.

Example

const receipts = await iap.resolveReceiptsBySku(sku);

.startPurchase(sku, handler, purchaseOptions)

Prompts the user to purchase a product, and invokes a callback function to handle the results of the purchase.

Parameters

  • skuString, identifier for the product to purchase. Products are defined in the entitlements and registered or updated when the project is deployed.

  • handlerFunction, handles the results of the purchase. Receives the following properties as input:

    • successBoolean, indicates whether the purchase was successful.

    • userTokenString, temporary token for the current user’s session. See getToken.

    • receiptIdString, unique identifier for the receipt, if the purchase was successful, or undefined, if not.

  • purchaseOptionsObject, custom information to add to the transaction receipt. Contains the following properties:

    • amountNumber, (Optional) amount of the purchase.

    • customMessageString, (Optional) custom message associated with the purchase. This value is stored as a custom attribute on the transaction receipt.

Example

iap.startPurchase(sku, (success, token, purchaseOptions) => {
  // Update template based on whether the purchase was successful
});

.updateReceipt(receiptId, attributes, notificationMessage)

Updates the custom attributes for a specified receipt. For example, if a user purchases a "power up" and then uses it in a game, you can update the receipt to indicate that the product has been consumed and is not available for future sessions.

Parameters

  • receiptIdString, unique identifier for the receipt.

  • attributesObject, list of key-value pairs to update.

  • notificationMessageString, (Optional) custom message to sent the user when the receipt is updated (up to 80 characters). If undefined, the message will read: Your receipt for PRODUCT_NAME was updated.

Returns

(Async) Any, confirmation of the update, if the request was successful, or an error message, if not.

Example

const receipt = await iap.updateReceipt(receiptId, { isConsumed: true }, 'Your power up has been used');

Iap objects

IapReceipt

An IapReceipt object represents a receipt for a user’s purchase of a product. To determine whether a user has purchased a specific product, you can use resolveReceipts to retrieve the IapReceipt objects associated with the user’s token, and then look for a receipt with the product’s SKU.

The IapReceipt object includes the following properties.

Tip
Be sure to implement appropriate error handling to account for differences in object structure or empty values.
{
  id: string; (1)
  userId: string; (2)
  productId: string; (3)
  purchasedPrice: number; (4)
  attributes: { [index: string]: any }; (5)
  datePurchased: Date; (6)
  product?: IapProduct; (7)
  transaction?: Transaction|null; (8)
  transactionIds: { (9)
    credit: string;
    debit: string;
  };
}
  1. id – Unique identifier for the receipt.

  2. userId – Koji user name of the user who purchased the product. The userId return value will always be unavailable. To avoid leaking/fingerprinting users at a global level, Kojis must interact with users via a short-lived user token. See getToken.

  3. productId – Unique identifier for the product.

  4. purchasedPrice – Price the user paid for the product.

  5. attributes – Object containing a list of custom key-value pairs associated with the receipt. You can use updateReceipt to update these values. Additionally, the fulfillment information (email, phone, or address) and customMessage are included this object, if set at purchase time.

  6. datePurchased – Date of the purchase.

  7. productIapProduct object that represents the purchased product.

  8. transaction – Object that represents the transaction information, if available.

  9. transactionIds – Object containing references to the associated transaction receipts – credit for the user receiving the funds (seller), debit for the user sending the funds (buyer). To link to the transaction receipt in the user’s Koji wallet, use the format https://withkoji.com/payments/transactions/TXN_ID.

IapProduct

An IapProduct object represents a specific product for purchase. Products are defined in the entitlements and registered or updated when the project is deployed. You can use loadProduct to retrieve the properties associated with the product’s SKU.

The IapProduct object includes the following properties.

{
  id: string; (1)
  appId: string; (2)
  ownerUserId: string; (3)
  price: number; (4)
  priceIsUnset: boolean; (5)
  isConsumable: boolean; (6)
  name: string; (7)
  sku: string; (8)
  dateCreated: Date; (9)
  isActive: boolean; (10)
  fulfillment?: 'email'|'phone'|'address'; (11)
  quantity?: number; (12)
  numAvailable?: number; (13)
  owner?: UserArtifact; (14)
  purchases?: IapReceipt[]; (15)
}
  1. id – Unique identifier for this version of the product.

  2. appId – Name of the Koji from which the product was purchased.

  3. ownerUserId – Koji user name of the creator.

  4. price – Purchase price of the product. Defined in the entitlements file of the template.

  5. priceIsUnset – Indicator of whether a purchase price is defined for the product. Defined in the entitlements file of the template.

  6. isConsumable – Indicator of whether a product can be purchased more than once. Defined in the entitlements file of the template.

  7. name – Description displayed when the user was prompted to purchase the product. Defined in the entitlements file of the template.

  8. sku – Identifier of the purchased product. Defined in the entitlements file of the template.

  9. dateCreated – Date the product was registered or updated, which happens when the project is deployed.

  10. isActive – Indicator of whether the product is still available for purchase.

  11. fulfillment – Type of user information collected for order fulfillment. Defined in the entitlements file of the template.

  12. quantity – Total number of times the product can be sold (inventory threshold). Defined in the entitlements file of the template.

  13. numAvailable – Remaining number of times the product can be sold. Calculated based on the total inventory defined in the entitlements file, less the number of purchases.

  14. owner – Object that represents the template publisher ("seller").

  15. purchases – Array of IapReceipt objects representing purchases of the product.