Skip to content

Commit

Permalink
update node sdk to v1.0.0 (#11)
Browse files Browse the repository at this point in the history
removes deprecated methods
removes ability to set environments, keep ability to specify api host
add createHostedTransaction method

Co-authored-by: Lukas Herman <lherman.cs@gmail.com>
Co-authored-by: ChristianHansen <chris@berbix.com>
  • Loading branch information
3 people committed Mar 11, 2021
1 parent 7c184a2 commit 99a0ea1
Show file tree
Hide file tree
Showing 3 changed files with 87 additions and 93 deletions.
10 changes: 7 additions & 3 deletions README.md
Expand Up @@ -65,10 +65,14 @@ Supported options:
- `phone` - Previously verified phone number for a user.
- `customerUid` - An ID or identifier for the user in your system.
- `templateKey` - The template key for this transaction.
- `hostedOptions` - Optional configuration object for creating hosted transactions. The `hostedOptions` object can optionally include the following fields:
- Deprecated: `hostedOptions` - Optional configuration object for creating hosted transactions. The `hostedOptions` object can optionally include the following fields:
- `completionEmail` - Email address to which completion alerts will be sent for this transaction.
- `redirectUrl` - URL to redirect the user to after they complete the transaction. If not specified, the URL specified in the Berbix dashboard will be used instead.

##### `createHostedTransaction(options : object): {tokens: Tokens, hostedUrl: string}`

Creates a hosted transaction within Berbix to initialize the client SDK. This works the same as `createTransaction()` except that the object returned includes an explicit `hostedUrl` property for hosted transactions.

##### `fetchTransaction(tokens: Tokens): object`

Fetches all of the information associated with the transaction. If the user has already completed the steps of the transaction, then this will include all of the elements of the transaction payload as described on the [Berbix developer docs](https://developers.berbix.com).
Expand Down Expand Up @@ -131,9 +135,9 @@ This is the long-lived token that allows you to create new tokens after the shor

The internal Berbix ID number associated with the transaction.

##### `expiry: Date`
##### `expiry: number`

The time at which the access and client tokens will expire.
The Unix timestamp in seconds at which the access and client tokens will expire.

#### Static methods

Expand Down
29 changes: 10 additions & 19 deletions examples/transactions.js
Expand Up @@ -5,7 +5,6 @@ var run = async function () {
var client = new berbix.Client({
apiSecret: process.env.BERBIX_DEMO_CLIENT_SECRET,
apiHost: process.env.BERBIX_DEMO_API_HOST,
//environment: 'sandbox',
});

console.log("created client");
Expand All @@ -19,43 +18,35 @@ var run = async function () {
console.log(e);
}

console.log(tokens);

try {
var tokens = await client.createTransaction({
var hostedTransactionResponse = await client.createHostedTransaction({
customerUid: "this is a customer uid",
templateKey: "hi_6xP9A8y3Lzd2yoQFRRxlDZ_kqZAAP",
hostedOptions: {
completionEmail: "eric@berbix.com",
completionEmail: "andrew@berbix.com",
},
});
} catch (e) {
console.log(e);
}

console.log(tokens);

try {
var continuation = await client.createContinuation(tokens);
console.log(continuation);
} catch (e) {
console.log(e);
}

var fetchedTokens = await client.exchangeCode(process.env.BERBIX_DEMO_CODE);

console.log(fetchedTokens);

var toRefresh = new berbix.Tokens.fromRefresh(fetchedTokens.refreshToken);
console.log(hostedTransactionResponse);

try {
var transaction = await client.fetchTransaction(toRefresh);
var fetchResponse = await client.fetchTransaction(tokens);
} catch (e) {
console.log(e);
}

console.log(transaction);
console.log(fetchResponse);

try {
console.log(await client.deleteTransaction(tokens));
console.log(
await client.deleteTransaction(hostedTransactionResponse.tokens)
);
} catch (e) {
console.log(e);
}
Expand Down
141 changes: 70 additions & 71 deletions lib/berbix.js
Expand Up @@ -4,13 +4,41 @@ var https = require("https");
var url = require("url");
var crypto = require("crypto");

var SDK_VERSION = "0.0.14";
var SDK_VERSION = "1.0.0";
var CLOCK_DRIFT = 300;

function now() {
return new Date().getTime() / 1000;
}

function optionsToPayloadObject(opts) {
var payload = {};
if (opts.email != null) {
payload.email = opts.email;
}
if (opts.phone != null) {
payload.phone = opts.phone;
}
if (opts.customerUid != null) {
payload.customer_uid = "" + opts.customerUid;
}
if (opts.templateKey != null) {
payload.template_key = opts.templateKey;
}
if (opts.hostedOptions != null) {
var hostedOptions = {};
if (opts.hostedOptions.completionEmail != null) {
hostedOptions.completion_email = opts.hostedOptions.completionEmail;
}
if (opts.hostedOptions.redirectUrl != null) {
hostedOptions.redirect_url = opts.hostedOptions.redirectUrl;
}
payload.hosted_options = hostedOptions;
}

return payload;
}

function HTTPClient() {}

HTTPClient.prototype.request = function (host, method, path, headers, data) {
Expand Down Expand Up @@ -101,35 +129,19 @@ Tokens.fromRefresh = function (refreshToken) {
return new Tokens(refreshToken);
};

function TransactionResponse(tokens, hostedProperties) {
this.tokens = tokens;
this.hostedProperties = hostedProperties;
}

function Client(opts) {
opts = opts || {};

this.apiSecret = opts.apiSecret || opts.clientSecret;
this.apiHost = this._apiHost(opts);
this.apiHost = opts.apiHost || "https://api.berbix.com";
this.httpClient = opts.httpClient || new HTTPClient();
}

Client.prototype._apiHost = function (opts) {
if (opts.apiHost != null) {
return opts.apiHost;
}

if (opts.environment != null) {
switch (opts.environment) {
case "production":
return "https://api.berbix.com";
case "staging":
return "https://api.staging.berbix.com";
case "sandbox":
return "https://api.sandbox.berbix.com";
default:
throw "invalid environment value specified";
}
}

return "https://api.berbix.com";
};

Client.prototype._request = function (method, path, headers, payload = null) {
var body = null;
if (method == "POST" || method == "PATCH") {
Expand Down Expand Up @@ -159,35 +171,45 @@ Client.prototype._fetchTokens = async function (path, payload) {
);
};

Client.prototype._createTransaction = async function (path, payload) {
var headers = {
Authorization:
"Basic " + new Buffer.from(`${this.apiSecret}:`).toString("base64"),
"User-Agent": "BerbixNode/" + SDK_VERSION,
};
var result = await this._request("POST", path, headers, payload);
var tokens = new Tokens(
result.refresh_token,
result.access_token,
result.client_token,
now() + result.expires_in,
result.transaction_id,
result
);
return new TransactionResponse(tokens, {
hosted_url: result["hosted_url"],
});
};

Client.prototype.createTransaction = function (opts) {
var payload = {};
if (opts.email != null) {
payload.email = opts.email;
}
if (opts.phone != null) {
payload.phone = opts.phone;
}
if (opts.customerUid != null) {
payload.customer_uid = "" + opts.customerUid;
}
if (opts.templateKey != null) {
payload.template_key = opts.templateKey;
var payload = optionsToPayloadObject(opts);
var txnPromise = this._createTransaction("/v0/transactions", payload);
async function respTokens() {
var txnRes = await txnPromise;
return txnRes.tokens;
}
if (opts.hostedOptions != null) {
var hostedOptions = {};
if (opts.hostedOptions.completionEmail != null) {
hostedOptions.completion_email = opts.hostedOptions.completionEmail;
}
if (opts.hostedOptions.redirectUrl != null) {
hostedOptions.redirect_url = opts.hostedOptions.redirectUrl;
}
payload.hosted_options = hostedOptions;
}
return this._fetchTokens("/v0/transactions", payload);
return respTokens();
};

// createUser is deprecated, please use createTransaction
Client.prototype.createUser = Client.prototype.createTransaction;
Client.prototype.createHostedTransaction = function (opts) {
var payload = optionsToPayloadObject(opts);
var txnPromise = this._createTransaction("/v0/transactions", payload);
async function hostedResp() {
var txnRes = await txnPromise
return {tokens: txnRes.tokens, hostedUrl: txnRes.hostedProperties["hosted_url"]}
}
return hostedResp();
};

Client.prototype.refreshTokens = function (tokens) {
return this._fetchTokens("/v0/tokens", {
Expand All @@ -196,14 +218,6 @@ Client.prototype.refreshTokens = function (tokens) {
});
};

// exchangeCode is deprecated, please createTransaction prior to invoking client instead
Client.prototype.exchangeCode = function (code) {
return this._fetchTokens("/v0/tokens", {
grant_type: "authorization_code",
code: code,
});
};

Client.prototype._refreshIfNecessary = async function (tokens) {
if (tokens.needsRefresh()) {
var refreshed = await this.refreshTokens(tokens);
Expand Down Expand Up @@ -270,19 +284,6 @@ Client.prototype.overrideTransaction = function (tokens, params) {
);
};

// fetchUser is deprecated, please use fetchTransaction
Client.prototype.fetchUser = Client.prototype.fetchTransaction;

// createContinuation is deprecated, please use clientToken from Tokens instead
Client.prototype.createContinuation = async function (tokens) {
var result = await this._tokenAuthRequest(
"POST",
tokens,
"/v0/continuations"
);
return result.value;
};

Client.prototype.validateSignature = function (secret, body, header) {
var hmac = crypto.createHmac("sha256", secret);
var parts = header.split(",");
Expand All @@ -304,6 +305,4 @@ Client.prototype.validateSignature = function (secret, body, header) {
module.exports = {
Tokens: Tokens,
Client: Client,
// UserTokens is deprecated, please use Tokens
UserTokens: Tokens,
};

0 comments on commit 99a0ea1

Please sign in to comment.