• Stars
    star
    263
  • Rank 155,624 (Top 4 %)
  • Language
    JavaScript
  • Created almost 11 years ago
  • Updated 6 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

In-app purchase validation for Apple, Google, Amazon, Roku

In-app purchase verification

Inspired by the iap_verifier CoffeeScript module written by Paul Crawford, I wanted a pure JavaScript implementation of in-app purchase verification. I also wanted to add support for other app stores, and not just limit this to Apple. The iap module is exactly that. Pull requests to add support for other platforms are very welcome!

Installation

npm install iap

Usage

Initialisation

var iap = require('iap');

var platform = 'apple';
var payment = {
	receipt: 'receipt data', // always required
	productId: 'abc',
	packageName: 'my.app',
	secret: 'password',
	subscription: true,	// optional, if google play subscription
	keyObject: {}, // required, if google
	userId: 'user id', // required, if amazon
	devToken: 'developer id' // required, if roku
};

Purchase verification ( all platforms )

A method is exposed to verify purchase receipts:

iap.verifyPayment(platform, payment, function (error, response) {
	/* your code */
});

Or, if you prefer a promise-based alternative:

iap.verifyPayment(platform, payment)
.then(
    response => {	
        /* your code */ 
    },
    error => {
        /* your code */ 
    }
)

The receipt you pass must conform to the requirements of the backend you are verifying with. Read the next chapter for more information on the format.

Subscription cancellation ( Google Play only )

Google exposes an API for server side cancellation of recurring suscriptions. This might be be used to enable users to easily cancel subscriptions from within the app ( without going to Play Store ), or to allow subscriptions to be canceled by support people when users request it ( when for some reason the users are unable or unwilling to do so themselves).

iap.cancelSubscription("google", payment, function (error, response) {
	/* your code */
});

Or, if you prefer a promise-based alternative:

iap.cancelSubscription(platform, payment)
.then(
    response => {    
        /* your code */ 
    },
    error => {
        /* your code */ 
    }
)

Supported platforms

Amazon

The payment object

The receipt string represents the transaction returned from a channel or product purchase.

A Shared secret and user ID is required.

The response

The response passed back to your callback will also be Amazon specific. The entire parsed receipt will be in the result object:

{
	"receipt": {
		"betaProduct": false,
		"cancelDate": null,
		"parentProductId": null,
		"productId": "com.amazon.iapsamplev2.gold_medal",
		"productType": "CONSUMABLE",
		"purchaseDate": 1399070221749,
		"quantity": 1,
		"receiptId": "wE1EG1gsEZI9q9UnI5YoZ2OxeoVKPdR5bvPMqyKQq5Y=:1:11",
		"renewalDate": null,
		"term": null,
		"termSku": null,
		"testTransaction": false
	},
	"transactionId": "wE1EG1gsEZI9q9UnI5YoZ2OxeoVKPdR5bvPMqyKQq5Y=:1:11",
	"productId": "com.amazon.iapsamplev2.gold_medal",
	"platform": "amazon"
}

Apple

The payment object

The receipt string passed may be either the base64 string that Apple really wants, or the decoded receipt as returned by the iOS SDK (in which case it will be automatically base64 serialized).

Both productId and packageName (bundle ID) are optional, but when provided will be tested against. If the receipt does not match the provided values, an error will be returned.

To verify auto-renewable subscriptions you need to provide secret field that contains your In-App Purchase Shared Secret

Apple supports returning only the most recent transaction for auto-renewable subscriptions via their exclude-old-transactions option. This can greatly save on bandwidth for users that have more than one transaction. To enable this, pass excludeOldTransactions on the payment object:

let payment = {
  ...
  excludeOldTransactions: true
}

The response

The response passed back to your callback will also be Apple specific. The entire parsed receipt will be in the result object. Applications that support monthly and yearly subscription access will represent auto-renewable terms in either the in_app or latestReceiptInfo property.

{
	"receipt": {
		"original_purchase_date_pst": "2016-10-29 15:46:57 America/Los_Angeles",
		"purchase_date_ms": "1477802802000",
		"unique_identifier": "78abf2209323434771637ee22f0ee8b8341f14b4",
		"original_transaction_id": "120000257973875",
		"bvrs": "0.0.1",
		"transaction_id": "120000265421254",
		"quantity": "1",
		"unique_vendor_identifier": "206FED24-2EAB-4FC6-B946-4AF61086DF21",
		"item_id": "820817285",
		"product_id": "abc",
		"purchase_date": "2016-10-29 22:46:57 Etc/GMT",
		"original_purchase_date": "2016-10-29 22:46:57 Etc/GMT",
		"purchase_date_pst": "2016-10-29 15:46:57 America/Los_Angeles",
		"bid": "test.myapp",
		"original_purchase_date_ms": "1477781217000",
		"in_app": [
			{
				"quantity": "1",
				"product_id": "abc",
				"transaction_id": "120000265421254",
				"original_transaction_id": "120000257973875",
				"purchase_date": "2016-10-30 04:46:42 Etc/GMT",
				"purchase_date_ms": "1477802802000",
				"purchase_date_pst": "2016-10-29 21:46:42 America/Los_Angeles",
				"original_purchase_date": "2016-10-29 22:46:57 Etc/GMT",
				"original_purchase_date_ms": "1477781217000",
				"original_purchase_date_pst": "2016-10-29 15:46:57 America/Los_Angeles",
				"expires_date": "2016-11-30 05:46:42 Etc/GMT",
				"expires_date_ms": "1480484802000",
				"expires_date_pst": "2016-11-29 21:46:42 America/Los_Angeles",
				"web_order_line_item_id": "820817285",
				"is_trial_period": "false"
			},
		]
	},
	"latestReceiptInfo": [
		{
			"quantity": "1",
			"product_id": "abc",
			"transaction_id": "120000233230473",
			"original_transaction_id": "120000233230473",
			"purchase_date": "2016-06-12 22:36:58 Etc/GMT",
			"purchase_date_ms": "1465771018000",
			"purchase_date_pst": "2016-06-12 15:36:58 America/Los_Angeles",
			"original_purchase_date": "2016-06-12 22:36:58 Etc/GMT",
			"original_purchase_date_ms": "1465771018000",
			"original_purchase_date_pst": "2016-06-12 15:36:58 America/Los_Angeles",
			"expires_date": "2016-07-12 22:36:58 Etc/GMT",
			"expires_date_ms": "1468363018000",
			"expires_date_pst": "2016-07-12 15:36:58 America/Los_Angeles",
			"web_order_line_item_id": "120000034778618",
			"is_trial_period": "true"
		},
	],
	"pendingRenewalInfo": [
		{
		  "expiration_intent": "1",
 			"auto_renew_product_id": "abc",
			"original_transaction_id": "120000233230473",
			"is_in_billing_retry_period": "0",
			"product_id": "abc",
			"auto_renew_status": "0"
		}
	],
	"transactionId": "120000233230473",
	"productId": "abc",
	"platform": "apple",
	"environment": "production"
}

Google Play

The payment object

The receipt string is the purchase token that Google Play returns to the mobile application when a purchase is made.

Both packageName and productId are compulsory.

Lastly you must provide keyObject which is the Google API Service Account JSON key file linked to your Google Play account for authentication. This property can be either a string, file buffer or an object. If provided a string or file buffer, the call will automatically parse it into an object for use.

The response

The response passed back to your callback will also be Google Play specific. The entire parsed response will be in the receipt sub-object.

{
        "receipt": {
                "kind": "androidpublisher#productPurchase",
                "purchaseTimeMillis": "1410835105408",
                "purchaseState": 0,
                "consumptionState": 1,
                "developerPayload": ""
        },
        "transactionId": "ghbbkjheodjokkipdmlkjajn.AO-J1OwfrtpJd2fkzzZqv7i107yPmaUD9Vauf9g5evoqbIVzdOGYyJTSEMhSTGFkCOzGtWccxe17dtbS1c16M2OryJZPJ3z-eYhEJYiSLHxEZLnUJ8yfBmI",
        "productId": "abc",
        "platform": "google"
}

Roku

The receiept string represents the transaction returned from a channel or product purchase.

A developer ID is required.

The response

The response passed back to your callback will also be Roku specific. The entire parsed receipt will be in the result object:

{
	"receipt": {
		"errorCode": null,
		"errorDetails": null,
		"errorMessage": "",
		"status": 0,
		"amount": 4.99,
		"cancelled": false,
		"channelId": 70391,
		"channelName": "abc",
		"couponCode": null,
		"currency": "usd",
		"expirationDate": 1488337344000,
		"originalPurchaseDate": 1483153344000,
		"partnerReferenceId": null,
		"productId": "5KAZUPGB.0RF0",
		"productName": "BASIC - US MONTHLY",
		"purchaseDate": 1483153344000,
		"quantity": 1,
		"rokuCustomerId": "5e56c4c4d7d1504f813c630c2790e54a",
		"tax": 0,
		"total": 0,
		"transactionId": "380e9932-ed9a-48e8-bd66-a6ec00b5efd1"
	},
	"transactionId": "380e9932-ed9a-48e8-bd66-a6ec00b5efd1",
	"productId": "abc",
	"platform": "roku"
}

All Platforms

Regardless of the platform used, besides the platform-specific receipt, the following properties will be included:

Property Type Description
receipt object Data returned by platforms
platform string One of: 'apple', 'google', 'amazon', 'roku'
productId string Id of the product
transactionId string Id to uniquely identify transaction
purchaseDate int Date of purchase in millis
expirationDate int Date of expiration in millis

License

MIT

References

Amazon References

Code Inspiration

API Reference

Apple References

Code Inspiration

API Reference

Google Play References

Code Inspiration

API Reference

Receipt Generation

Roku References

API Reference

More Repositories

1

phonegap-facebook-plugin

The official plugin for Facebook in Apache Cordova/PhoneGap
Java
1,907
star
2

japanese-dev-lingo

Japanese Lingo for Developers
378
star
3

Ejecta-X

A Fast, Open Source JavaScript, Canvas & Audio Implementation
C
186
star
4

locks

Mutex locks, Read/Write locks, Condition variables and Semaphores in JavaScript
JavaScript
105
star
5

cordova-plugin-wizviewmanager

PhoneGap plugin for creating/showing/hiding/messaging/animating additional views outside of the main window.
Objective-C
57
star
6

frontrunner

Automated HAProxy reconfiguration for Marathon
JavaScript
57
star
7

node-pivotal

NodeJS API library for PivotalTracker
JavaScript
44
star
8

phonegap-plugin-wizCanvas

WizCanvas allows a developer to create a ultra-performant native canvas component. The view is based on the Ejecta framework and has WebGL support.
JavaScript
43
star
9

phonegap-plugin-localNotifications

PhoneGap plugin for providing native local notification system to JavaScript.
Java
38
star
10

safe-timers

Timers with near-infinite duration support
JavaScript
37
star
11

phonegap-plugin-wizSpinner

PhoneGap plugin for creating and manipulating native loader/spinner.
Java
35
star
12

codependency

Optional Peer Dependencies for Node.js middleware
JavaScript
33
star
13

WebViewForUnity3D

Android & iOS webview plugin for unity3D
Objective-C++
24
star
14

Jeff

Json Extraction From Flash
JavaScript
23
star
15

cordova-plugin-wizpurchase

Cross-platform mobile application payment API for iOS IAP and Android Billing.
Java
23
star
16

phonegap-plugin-wizAssets

PhoneGap plugin for managing application assets with javascript asset maps. Includes (background threaded) downloadFile, getFileURI, getFileURIs, deleteFile.
Java
18
star
17

constrained

JavaScript
15
star
18

phonegap-plugin-wizUtils

PhoneGap plugin for general utility functions to access information from the native OS.
Objective-C
15
star
19

libbash

Collection of bash libraries aimed at making your life easier
Shell
14
star
20

tina.js

Tweening and INterpolations for Animation
JavaScript
12
star
21

unitydemo-SurvivalShooter

Unity demo project: Survival Shooter
C#
12
star
22

byuu-web

C++
11
star
23

AudioManager

play sounds using Web Audio, fallback on HTML5 Audio
JavaScript
11
star
24

node-tomes

Evented storage agnostic data API
JavaScript
10
star
25

avltree-js

Javascript impl of AVL tree
JavaScript
9
star
26

megadata

Smart messaging for games
TypeScript
8
star
27

Dawn

Docker-based infrastructure setup and operation
Python
8
star
28

marathon-client.py

Python
8
star
29

cordova-plugin-yanap

Yet Another Native Audio Plugin for Cordova
Java
8
star
30

git-signed

Signing commits made easy
JavaScript
8
star
31

phonegap-plugin-iRate

PhoneGap plugin for customer/client app rating. [iOS ONLY]
Objective-C
7
star
32

Eruditio

Algorithms for Machine Learning
Python
6
star
33

dom-loader

HTML DOM element loader for Webpack
JavaScript
5
star
34

component-uglifyjs

UglifyJS plugin for component-builder
JavaScript
5
star
35

git-message

Set a custom git commit message template.
JavaScript
4
star
36

phonegap-plugin-wizDevTools

PhoneGap plugin for adding assistive development tools.
Objective-C
4
star
37

node-localcache

Local in-memory key/value data caching system for Node.js with TTL support
JavaScript
4
star
38

andever

A minimalistic daemonizer that will run your Node apps forever and ever!
JavaScript
4
star
39

xor128

XOR128 Pseudo-Random Number Generator
JavaScript
3
star
40

curlyfile

Direct download in Node.js, using libcurl
C++
3
star
41

unitydemo-AngryBots

Unity demo project: Angry Bots
JavaScript
3
star
42

terraform-provider-ncloud

Terraform provider for Naver Cloud Platform (also known as NCloud).
Go
3
star
43

cordova-plugin-webviewselector

Cordova plugin allowing an Android app user to switch between system webview and Crosswalk's webview
Java
3
star
44

component-extractor

This tool will generate component.json files of your project.
JavaScript
3
star
45

node-memcached-transactions

Transaction support for node-memcached
JavaScript
3
star
46

phonegap-plugin-wizUniqueIdentifier

PhoneGap plugin for generating a unique identifier and storing it in the device keychain
Objective-C
3
star
47

phonegap-plugin-wizNavi

PhoneGap plugin for building native navigation component.
Objective-C
3
star
48

cachepuncher

Punch browser caching straight in the cache!
JavaScript
3
star
49

phonegap-plugin-wizAnalytics

PhoneGap plugin to load plug and play Ad tracker SDKs
Objective-C
3
star
50

filter-builder

JavaScript
2
star
51

panopticon

Node.js data acquisition for applications that use the cluster module.
JavaScript
2
star
52

es-apm-decorators

TypeScript
2
star
53

typescript-primer

Quick primer on the why, what and how of TypeScript
TypeScript
2
star
54

mocha-reporter

Mocha reporter, enhanced.
JavaScript
2
star
55

express-rested

Manage resources with REST through Express
JavaScript
2
star
56

network-interfaces

Utility functions for dealing with network interfaces and IP addresses in Node.js
JavaScript
2
star
57

phonegap-plugin-wizSplash

PhoneGap plugin for manipulating native splash.
Objective-C
2
star
58

TileSystem

C# Tile system for use with Unity
C#
2
star
59

cordova-plugin-moodstocks

Cordova plugin to use Moodstocks (https://moodstocks.com/)
Objective-C
2
star
60

list-AvlTree

JavaScript
2
star
61

unitydemo-2DPlatformer

Unity demo project: 2D Platformer
C#
2
star
62

phonegap-plugin-wizBootStrap

PhoneGap plugin for bootstrapping various html environments.
Objective-C
2
star
63

node-chagama

Git flow, GitHub and PivotalTracker, all in one teapot
JavaScript
2
star
64

StyleGuides

Wizcorp JavaScript styleguide
2
star
65

tomesweeper

Catch mistakes you've made with tomes.
JavaScript
1
star
66

docker-blend

NODE_ENV + compose + service
JavaScript
1
star
67

watch-redux

Watch Redux for granular changes
JavaScript
1
star
68

phonegap-plugin-apsalar

PhoneGap plugin for event and session tracking with Apsalar.
Objective-C
1
star
69

noise-simplex2D

JavaScript
1
star
70

my-type

Yet another JS schema assertion library
JavaScript
1
star
71

timed-number

JavaScript
1
star
72

workshops

Workshops
1
star
73

enable-async

Turns on async/await on Node.js 7
JavaScript
1
star
74

list-SortedArray

JavaScript
1
star
75

training_git

1
star
76

deep-copy.js

Perform deep copies of JavaScript objects
JavaScript
1
star
77

component-hint

Linting tool for component projects and packages
JavaScript
1
star
78

gettextlight.js

GetText support for Node.js and component
JavaScript
1
star
79

WebviewAndroidPlugin

Java
1
star
80

component-less

Less transpiler for component-builder
JavaScript
1
star
81

Recorder

It allows recording and playing object properties over time
JavaScript
1
star
82

math-bezier

JavaScript
1
star
83

itd

Improvised Testing Device: timed locks with a fun, bomb-style interface.
JavaScript
1
star
84

image-preloader

Preload your images with the ImagePreloader
JavaScript
1
star
85

cordova-plugin-memory-alert

Cordova plugin dispatching native memory events to javascript
Objective-C
1
star
86

markdown-jsdoc

Markdown template for jsdoc
JavaScript
1
star
87

swarm-announcer

Announce containers using a specific Docker network to a Consul server
1
star
88

phonegap-plugin-wizStatbar

PhoneGap plugin for building gaming stats bar.
Objective-C
1
star
89

Banalize

Bash code analyzer
Ruby
1
star
90

simple-filter

A small wrapper around crossfilter to make querying simpler
JavaScript
1
star
91

wizard-academy-2018-flying-cats

ウイザードアカデミー2018年スペースシューター・Flying Catsチームのレポジトリー!
TypeScript
1
star
92

wizard-academy-2018-co-op-creators

ウイザードアカデミー2018年スペースシューター・Co-op Creatorsチームのレポジトリー!
PLSQL
1
star
93

node-rumplestiltskin

Reveals an object's true name
JavaScript
1
star