@outseta/node-sdk 0.2.2 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -17
- package/dist/index.js +142 -2
- package/package.json +3 -2
- package/src/express.ts +140 -0
- package/src/index.ts +16 -1
- package/src/usage.ts +140 -0
package/README.md
CHANGED
|
@@ -1,25 +1,31 @@
|
|
|
1
1
|
# @outseta/node-sdk
|
|
2
2
|
|
|
3
|
-
Node.js SDK for the
|
|
3
|
+
Node.js SDK helpers for the Outseta API.
|
|
4
4
|
|
|
5
|
-
##
|
|
5
|
+
## Notes
|
|
6
6
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
7
|
+
- Use API key credentials only on the server. For user-scoped requests, create a client with an Outseta bearer `accessToken`.
|
|
8
|
+
- `trackUsage` is intentionally higher-level than the generated API call: it fetches the account, finds the matching subscription add-on, verifies it is usage-based, then creates the usage record.
|
|
9
|
+
- Webhook verification must use the exact raw request body. In Express, mount the webhook route with `express.text(outsetaWebhookTextParserOptions)` before `createOutsetaWebhookHandler`.
|
|
10
|
+
- Generated REST API functions are exported from `@outseta/api-client`; pass SDK clients to them with `withClient(client)`.
|
|
10
11
|
|
|
11
|
-
##
|
|
12
|
+
## Express webhook route
|
|
12
13
|
|
|
13
14
|
```ts
|
|
14
|
-
import
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
15
|
+
import express from "express";
|
|
16
|
+
import {
|
|
17
|
+
createOutsetaWebhookHandler,
|
|
18
|
+
outsetaWebhookTextParserOptions,
|
|
19
|
+
} from "@outseta/node-sdk";
|
|
20
|
+
|
|
21
|
+
app.post(
|
|
22
|
+
"/outseta/webhook",
|
|
23
|
+
express.text(outsetaWebhookTextParserOptions),
|
|
24
|
+
createOutsetaWebhookHandler({
|
|
25
|
+
signingKey: process.env.OUTSETA_WEBHOOK_SIGNING_KEY!,
|
|
26
|
+
async onWebhook(payload) {
|
|
27
|
+
// Handle Activity Notification payload.
|
|
28
|
+
},
|
|
29
|
+
}),
|
|
30
|
+
);
|
|
21
31
|
```
|
|
22
|
-
|
|
23
|
-
## License
|
|
24
|
-
|
|
25
|
-
[MIT](../../LICENSE)
|
package/dist/index.js
CHANGED
|
@@ -22,6 +22,9 @@ function createClient(creds) {
|
|
|
22
22
|
});
|
|
23
23
|
};
|
|
24
24
|
}
|
|
25
|
+
function withClient(client, init = {}) {
|
|
26
|
+
return { ...init, client };
|
|
27
|
+
}
|
|
25
28
|
// src/verify-webhook.ts
|
|
26
29
|
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
27
30
|
function verifyWebhookSignature(signature, body, signingKey) {
|
|
@@ -49,21 +52,158 @@ async function verifyJwtWithProfile(client, token) {
|
|
|
49
52
|
return { payload, profile };
|
|
50
53
|
}
|
|
51
54
|
// src/generate-token.ts
|
|
52
|
-
async function generateAccessToken(client,
|
|
55
|
+
async function generateAccessToken(client, email2) {
|
|
53
56
|
const response = await client("tokens", {
|
|
54
57
|
method: "POST",
|
|
55
58
|
headers: { "Content-Type": "application/json" },
|
|
56
|
-
body: JSON.stringify({ username:
|
|
59
|
+
body: JSON.stringify({ username: email2 })
|
|
57
60
|
});
|
|
58
61
|
if (!response.ok) {
|
|
59
62
|
throw new Error(`Failed to generate access token: ${response.status} ${response.statusText}`);
|
|
60
63
|
}
|
|
61
64
|
return await response.json();
|
|
62
65
|
}
|
|
66
|
+
// src/usage.ts
|
|
67
|
+
var USAGE_ACCOUNT_FIELDS = "Uid,Name,CurrentSubscription.*,CurrentSubscription.SubscriptionAddOns.*,CurrentSubscription.SubscriptionAddOns.AddOn.*";
|
|
68
|
+
async function readResponseBody(response) {
|
|
69
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
70
|
+
if (contentType.includes("application/json")) {
|
|
71
|
+
return await response.json().catch(() => {
|
|
72
|
+
return;
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
return await response.text().catch(() => {
|
|
76
|
+
return;
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
function getErrorMessage(body) {
|
|
80
|
+
if (body && typeof body === "object") {
|
|
81
|
+
const error = body;
|
|
82
|
+
return error.ErrorMessage ?? error.Message ?? "";
|
|
83
|
+
}
|
|
84
|
+
return typeof body === "string" ? body : "";
|
|
85
|
+
}
|
|
86
|
+
async function assertOk(response, endpoint) {
|
|
87
|
+
const body = await readResponseBody(response);
|
|
88
|
+
if (!response.ok) {
|
|
89
|
+
const message2 = getErrorMessage(body);
|
|
90
|
+
throw new Error(`${endpoint}: [${response.status}] ${message2 || response.statusText}`);
|
|
91
|
+
}
|
|
92
|
+
return body;
|
|
93
|
+
}
|
|
94
|
+
async function trackUsage(client, params) {
|
|
95
|
+
const fields = new URLSearchParams({ fields: USAGE_ACCOUNT_FIELDS });
|
|
96
|
+
const accountEndpoint = `crm/accounts/${params.accountUid}?${fields.toString()}`;
|
|
97
|
+
const accountResponse = await client(accountEndpoint, { method: "GET" });
|
|
98
|
+
const account2 = await assertOk(accountResponse, "/api/v1/crm/accounts/:accountUid");
|
|
99
|
+
const addOnSubscriptions = account2.CurrentSubscription?.SubscriptionAddOns ?? [];
|
|
100
|
+
const targetAddOnSubscription = addOnSubscriptions.find((subscriptionAddOn2) => subscriptionAddOn2.AddOn?.Uid === params.addOnUid);
|
|
101
|
+
if (!targetAddOnSubscription?.Uid) {
|
|
102
|
+
throw new Error(`Subscription for add-on with UID ${params.addOnUid} not found for account ${params.accountUid}`);
|
|
103
|
+
}
|
|
104
|
+
if (targetAddOnSubscription.AddOn?.BillingAddOnType !== 2) {
|
|
105
|
+
throw new Error(`Add-on with UID ${params.addOnUid} is not a usage add-on for account ${params.accountUid}`);
|
|
106
|
+
}
|
|
107
|
+
const usageDate = params.usageDate instanceof Date ? params.usageDate.toISOString() : params.usageDate ?? new Date().toISOString();
|
|
108
|
+
const usageResponse = await client("billing/usage", {
|
|
109
|
+
method: "POST",
|
|
110
|
+
headers: { "Content-Type": "application/json" },
|
|
111
|
+
body: JSON.stringify({
|
|
112
|
+
UsageDate: usageDate,
|
|
113
|
+
Amount: params.amount,
|
|
114
|
+
SubscriptionAddOn: {
|
|
115
|
+
Uid: targetAddOnSubscription.Uid
|
|
116
|
+
}
|
|
117
|
+
})
|
|
118
|
+
});
|
|
119
|
+
return await assertOk(usageResponse, "/api/v1/billing/usage");
|
|
120
|
+
}
|
|
121
|
+
function updateUsageBasedPricing(client, accountUid, addOnUid, amount, options = {}) {
|
|
122
|
+
return trackUsage(client, { accountUid, addOnUid, amount, ...options });
|
|
123
|
+
}
|
|
124
|
+
// src/express.ts
|
|
125
|
+
import { Buffer as Buffer2 } from "node:buffer";
|
|
126
|
+
var outsetaWebhookTextParserOptions = {
|
|
127
|
+
type: "application/json"
|
|
128
|
+
};
|
|
129
|
+
function getHeader(headers, name) {
|
|
130
|
+
const lowerName = name.toLowerCase();
|
|
131
|
+
const value = Object.entries(headers).find(([key]) => key.toLowerCase() === lowerName)?.[1];
|
|
132
|
+
if (Array.isArray(value))
|
|
133
|
+
return value[0];
|
|
134
|
+
return value;
|
|
135
|
+
}
|
|
136
|
+
function bodyToString(body) {
|
|
137
|
+
if (typeof body === "string")
|
|
138
|
+
return body;
|
|
139
|
+
if (Buffer2.isBuffer(body))
|
|
140
|
+
return body.toString("utf-8");
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
function getOutsetaWebhookSignature(request) {
|
|
144
|
+
return getHeader(request.headers, "x-hub-signature-256");
|
|
145
|
+
}
|
|
146
|
+
function getOutsetaWebhookBody(request) {
|
|
147
|
+
return bodyToString(request.rawBody) ?? bodyToString(request.body);
|
|
148
|
+
}
|
|
149
|
+
function verifyOutsetaWebhookRequest(request, signingKey) {
|
|
150
|
+
const signature = getOutsetaWebhookSignature(request);
|
|
151
|
+
const body = getOutsetaWebhookBody(request);
|
|
152
|
+
if (!signature || body === undefined)
|
|
153
|
+
return false;
|
|
154
|
+
return verifyWebhookSignature(signature, body, signingKey);
|
|
155
|
+
}
|
|
156
|
+
function createOutsetaWebhookHandler({
|
|
157
|
+
signingKey,
|
|
158
|
+
onWebhook,
|
|
159
|
+
successStatus = 200,
|
|
160
|
+
successBody = "ok",
|
|
161
|
+
onError
|
|
162
|
+
}) {
|
|
163
|
+
return async (request, response, next) => {
|
|
164
|
+
const signature = getOutsetaWebhookSignature(request);
|
|
165
|
+
const body = getOutsetaWebhookBody(request);
|
|
166
|
+
if (!signature) {
|
|
167
|
+
response.status(400).send("Missing signature header");
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
if (body === undefined) {
|
|
171
|
+
response.status(400).send("Missing raw webhook body");
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
if (!verifyWebhookSignature(signature, body, signingKey)) {
|
|
175
|
+
response.status(400).send("Webhook verification error");
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
try {
|
|
179
|
+
const payload = JSON.parse(body);
|
|
180
|
+
await onWebhook(payload, request);
|
|
181
|
+
response.status(successStatus).send(successBody);
|
|
182
|
+
} catch (error) {
|
|
183
|
+
if (onError) {
|
|
184
|
+
await onError(error, request, response);
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
if (next) {
|
|
188
|
+
next(error);
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
response.status(500).send("Webhook handler error");
|
|
192
|
+
}
|
|
193
|
+
};
|
|
194
|
+
}
|
|
63
195
|
export {
|
|
196
|
+
withClient,
|
|
64
197
|
verifyWebhookSignature,
|
|
198
|
+
verifyOutsetaWebhookRequest,
|
|
65
199
|
verifyJwtWithProfile,
|
|
66
200
|
verifyJwt,
|
|
201
|
+
updateUsageBasedPricing,
|
|
202
|
+
trackUsage,
|
|
203
|
+
outsetaWebhookTextParserOptions,
|
|
204
|
+
getOutsetaWebhookSignature,
|
|
205
|
+
getOutsetaWebhookBody,
|
|
67
206
|
generateAccessToken,
|
|
207
|
+
createOutsetaWebhookHandler,
|
|
68
208
|
createClient
|
|
69
209
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@outseta/node-sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Node.js SDK for the Outseta API",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -19,9 +19,10 @@
|
|
|
19
19
|
},
|
|
20
20
|
"dependencies": {
|
|
21
21
|
"jose": "^6.2.1",
|
|
22
|
-
"@outseta/api-client": "0.
|
|
22
|
+
"@outseta/api-client": "0.3.0"
|
|
23
23
|
},
|
|
24
24
|
"devDependencies": {
|
|
25
|
+
"@types/node": "^25.9.1",
|
|
25
26
|
"typescript": "^5.7.0"
|
|
26
27
|
},
|
|
27
28
|
"files": [
|
package/src/express.ts
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { Buffer } from "node:buffer";
|
|
2
|
+
import { verifyWebhookSignature } from "./verify-webhook.js";
|
|
3
|
+
|
|
4
|
+
export const outsetaWebhookTextParserOptions = {
|
|
5
|
+
type: "application/json",
|
|
6
|
+
} as const;
|
|
7
|
+
|
|
8
|
+
type HeaderValue = string | string[] | undefined;
|
|
9
|
+
|
|
10
|
+
export type OutsetaWebhookRequest = {
|
|
11
|
+
headers: Record<string, HeaderValue>;
|
|
12
|
+
body?: unknown;
|
|
13
|
+
rawBody?: unknown;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export type OutsetaWebhookResponse = {
|
|
17
|
+
status: (code: number) => OutsetaWebhookResponse;
|
|
18
|
+
send: (body?: unknown) => unknown;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
export type OutsetaWebhookNext = (error?: unknown) => void;
|
|
22
|
+
|
|
23
|
+
export type OutsetaWebhookHandlerOptions<TPayload = unknown> = {
|
|
24
|
+
/** Webhook signing key from Outseta webhook settings. */
|
|
25
|
+
signingKey: string;
|
|
26
|
+
/** Called after the signature is verified and the JSON payload is parsed. */
|
|
27
|
+
onWebhook: (
|
|
28
|
+
payload: TPayload,
|
|
29
|
+
request: OutsetaWebhookRequest,
|
|
30
|
+
) => void | Promise<void>;
|
|
31
|
+
/** HTTP status returned after successful processing. Defaults to 200. */
|
|
32
|
+
successStatus?: number;
|
|
33
|
+
/** Response body returned after successful processing. Defaults to "ok". */
|
|
34
|
+
successBody?: unknown;
|
|
35
|
+
/** Optional custom error hook. If omitted, Express `next` is used when present. */
|
|
36
|
+
onError?: (
|
|
37
|
+
error: unknown,
|
|
38
|
+
request: OutsetaWebhookRequest,
|
|
39
|
+
response: OutsetaWebhookResponse,
|
|
40
|
+
) => void | Promise<void>;
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
function getHeader(
|
|
44
|
+
headers: Record<string, HeaderValue>,
|
|
45
|
+
name: string,
|
|
46
|
+
): string | undefined {
|
|
47
|
+
const lowerName = name.toLowerCase();
|
|
48
|
+
const value = Object.entries(headers).find(
|
|
49
|
+
([key]) => key.toLowerCase() === lowerName,
|
|
50
|
+
)?.[1];
|
|
51
|
+
|
|
52
|
+
if (Array.isArray(value)) return value[0];
|
|
53
|
+
return value;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function bodyToString(body: unknown): string | undefined {
|
|
57
|
+
if (typeof body === "string") return body;
|
|
58
|
+
if (Buffer.isBuffer(body)) return body.toString("utf-8");
|
|
59
|
+
return undefined;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function getOutsetaWebhookSignature(
|
|
63
|
+
request: OutsetaWebhookRequest,
|
|
64
|
+
): string | undefined {
|
|
65
|
+
return getHeader(request.headers, "x-hub-signature-256");
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function getOutsetaWebhookBody(
|
|
69
|
+
request: OutsetaWebhookRequest,
|
|
70
|
+
): string | undefined {
|
|
71
|
+
return bodyToString(request.rawBody) ?? bodyToString(request.body);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function verifyOutsetaWebhookRequest(
|
|
75
|
+
request: OutsetaWebhookRequest,
|
|
76
|
+
signingKey: string,
|
|
77
|
+
): boolean {
|
|
78
|
+
const signature = getOutsetaWebhookSignature(request);
|
|
79
|
+
const body = getOutsetaWebhookBody(request);
|
|
80
|
+
|
|
81
|
+
if (!signature || body === undefined) return false;
|
|
82
|
+
return verifyWebhookSignature(signature, body, signingKey);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Creates an Express-compatible webhook handler for Outseta Activity
|
|
87
|
+
* Notifications.
|
|
88
|
+
*
|
|
89
|
+
* Use with `express.text(outsetaWebhookTextParserOptions)` so the raw JSON
|
|
90
|
+
* string is available for signature verification.
|
|
91
|
+
*/
|
|
92
|
+
export function createOutsetaWebhookHandler<TPayload = unknown>({
|
|
93
|
+
signingKey,
|
|
94
|
+
onWebhook,
|
|
95
|
+
successStatus = 200,
|
|
96
|
+
successBody = "ok",
|
|
97
|
+
onError,
|
|
98
|
+
}: OutsetaWebhookHandlerOptions<TPayload>) {
|
|
99
|
+
return async (
|
|
100
|
+
request: OutsetaWebhookRequest,
|
|
101
|
+
response: OutsetaWebhookResponse,
|
|
102
|
+
next?: OutsetaWebhookNext,
|
|
103
|
+
) => {
|
|
104
|
+
const signature = getOutsetaWebhookSignature(request);
|
|
105
|
+
const body = getOutsetaWebhookBody(request);
|
|
106
|
+
|
|
107
|
+
if (!signature) {
|
|
108
|
+
response.status(400).send("Missing signature header");
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
if (body === undefined) {
|
|
113
|
+
response.status(400).send("Missing raw webhook body");
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
if (!verifyWebhookSignature(signature, body, signingKey)) {
|
|
118
|
+
response.status(400).send("Webhook verification error");
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
try {
|
|
123
|
+
const payload = JSON.parse(body) as TPayload;
|
|
124
|
+
await onWebhook(payload, request);
|
|
125
|
+
response.status(successStatus).send(successBody);
|
|
126
|
+
} catch (error) {
|
|
127
|
+
if (onError) {
|
|
128
|
+
await onError(error, request, response);
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
if (next) {
|
|
133
|
+
next(error);
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
response.status(500).send("Webhook handler error");
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { createClient } from "@outseta/api-client";
|
|
1
|
+
export { createClient, withClient } from "@outseta/api-client";
|
|
2
2
|
export type {
|
|
3
3
|
OutsetaCredentials,
|
|
4
4
|
OutsetaApiKeyCredentials,
|
|
@@ -10,3 +10,18 @@ export { verifyWebhookSignature } from "./verify-webhook.js";
|
|
|
10
10
|
export { verifyJwt, verifyJwtWithProfile } from "./verify-jwt.js";
|
|
11
11
|
export type { JWTPayload } from "./verify-jwt.js";
|
|
12
12
|
export { generateAccessToken } from "./generate-token.js";
|
|
13
|
+
export { trackUsage, updateUsageBasedPricing } from "./usage.js";
|
|
14
|
+
export type { TrackUsageParams, TrackUsageResult } from "./usage.js";
|
|
15
|
+
export {
|
|
16
|
+
createOutsetaWebhookHandler,
|
|
17
|
+
getOutsetaWebhookBody,
|
|
18
|
+
getOutsetaWebhookSignature,
|
|
19
|
+
outsetaWebhookTextParserOptions,
|
|
20
|
+
verifyOutsetaWebhookRequest,
|
|
21
|
+
} from "./express.js";
|
|
22
|
+
export type {
|
|
23
|
+
OutsetaWebhookHandlerOptions,
|
|
24
|
+
OutsetaWebhookNext,
|
|
25
|
+
OutsetaWebhookRequest,
|
|
26
|
+
OutsetaWebhookResponse,
|
|
27
|
+
} from "./express.js";
|
package/src/usage.ts
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import type { OutsetaClient } from "@outseta/api-client";
|
|
2
|
+
|
|
3
|
+
const USAGE_ACCOUNT_FIELDS =
|
|
4
|
+
"Uid,Name,CurrentSubscription.*,CurrentSubscription.SubscriptionAddOns.*,CurrentSubscription.SubscriptionAddOns.AddOn.*";
|
|
5
|
+
|
|
6
|
+
type OutsetaErrorBody = {
|
|
7
|
+
ErrorMessage?: string;
|
|
8
|
+
Message?: string;
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
type SubscriptionAddOnForUsage = {
|
|
12
|
+
Uid?: string;
|
|
13
|
+
AddOn?: {
|
|
14
|
+
Uid?: string;
|
|
15
|
+
BillingAddOnType?: number;
|
|
16
|
+
};
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
type AccountForUsage = {
|
|
20
|
+
CurrentSubscription?: {
|
|
21
|
+
SubscriptionAddOns?: SubscriptionAddOnForUsage[] | null;
|
|
22
|
+
} | null;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
export type TrackUsageParams = {
|
|
26
|
+
/** Account UID that owns the usage-based add-on subscription. */
|
|
27
|
+
accountUid: string;
|
|
28
|
+
/** Add-on UID configured as usage-based billing in Outseta. */
|
|
29
|
+
addOnUid: string;
|
|
30
|
+
/** Usage amount to record. */
|
|
31
|
+
amount: number;
|
|
32
|
+
/** Usage date. Defaults to the current time. */
|
|
33
|
+
usageDate?: Date | string;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
export type TrackUsageResult = Record<string, unknown>;
|
|
37
|
+
|
|
38
|
+
async function readResponseBody(response: Response): Promise<unknown> {
|
|
39
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
40
|
+
|
|
41
|
+
if (contentType.includes("application/json")) {
|
|
42
|
+
return await response.json().catch(() => undefined);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
return await response.text().catch(() => undefined);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function getErrorMessage(body: unknown): string {
|
|
49
|
+
if (body && typeof body === "object") {
|
|
50
|
+
const error = body as OutsetaErrorBody;
|
|
51
|
+
return error.ErrorMessage ?? error.Message ?? "";
|
|
52
|
+
}
|
|
53
|
+
return typeof body === "string" ? body : "";
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async function assertOk(response: Response, endpoint: string): Promise<unknown> {
|
|
57
|
+
const body = await readResponseBody(response);
|
|
58
|
+
|
|
59
|
+
if (!response.ok) {
|
|
60
|
+
const message = getErrorMessage(body);
|
|
61
|
+
throw new Error(
|
|
62
|
+
`${endpoint}: [${response.status}] ${message || response.statusText}`,
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
return body;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Records usage for an Outseta usage-based add-on.
|
|
71
|
+
*
|
|
72
|
+
* The helper fetches the account's current subscription, finds the matching
|
|
73
|
+
* subscription add-on by add-on UID, verifies it is usage-based
|
|
74
|
+
* (`BillingAddOnType === 2`), then creates a billing usage entry.
|
|
75
|
+
*/
|
|
76
|
+
export async function trackUsage(
|
|
77
|
+
client: OutsetaClient,
|
|
78
|
+
params: TrackUsageParams,
|
|
79
|
+
): Promise<TrackUsageResult> {
|
|
80
|
+
const fields = new URLSearchParams({ fields: USAGE_ACCOUNT_FIELDS });
|
|
81
|
+
const accountEndpoint = `crm/accounts/${params.accountUid}?${fields.toString()}`;
|
|
82
|
+
|
|
83
|
+
const accountResponse = await client(accountEndpoint, { method: "GET" });
|
|
84
|
+
const account = await assertOk(
|
|
85
|
+
accountResponse,
|
|
86
|
+
"/api/v1/crm/accounts/:accountUid",
|
|
87
|
+
) as AccountForUsage;
|
|
88
|
+
|
|
89
|
+
const addOnSubscriptions =
|
|
90
|
+
account.CurrentSubscription?.SubscriptionAddOns ?? [];
|
|
91
|
+
const targetAddOnSubscription = addOnSubscriptions.find(
|
|
92
|
+
(subscriptionAddOn) => subscriptionAddOn.AddOn?.Uid === params.addOnUid,
|
|
93
|
+
);
|
|
94
|
+
|
|
95
|
+
if (!targetAddOnSubscription?.Uid) {
|
|
96
|
+
throw new Error(
|
|
97
|
+
`Subscription for add-on with UID ${params.addOnUid} not found for account ${params.accountUid}`,
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
if (targetAddOnSubscription.AddOn?.BillingAddOnType !== 2) {
|
|
102
|
+
throw new Error(
|
|
103
|
+
`Add-on with UID ${params.addOnUid} is not a usage add-on for account ${params.accountUid}`,
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const usageDate = params.usageDate instanceof Date
|
|
108
|
+
? params.usageDate.toISOString()
|
|
109
|
+
: params.usageDate ?? new Date().toISOString();
|
|
110
|
+
|
|
111
|
+
const usageResponse = await client("billing/usage", {
|
|
112
|
+
method: "POST",
|
|
113
|
+
headers: { "Content-Type": "application/json" },
|
|
114
|
+
body: JSON.stringify({
|
|
115
|
+
UsageDate: usageDate,
|
|
116
|
+
Amount: params.amount,
|
|
117
|
+
SubscriptionAddOn: {
|
|
118
|
+
Uid: targetAddOnSubscription.Uid,
|
|
119
|
+
},
|
|
120
|
+
}),
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
return await assertOk(
|
|
124
|
+
usageResponse,
|
|
125
|
+
"/api/v1/billing/usage",
|
|
126
|
+
) as TrackUsageResult;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Compatibility helper mirroring the original toolkit example name.
|
|
131
|
+
*/
|
|
132
|
+
export function updateUsageBasedPricing(
|
|
133
|
+
client: OutsetaClient,
|
|
134
|
+
accountUid: string,
|
|
135
|
+
addOnUid: string,
|
|
136
|
+
amount: number,
|
|
137
|
+
options: Pick<TrackUsageParams, "usageDate"> = {},
|
|
138
|
+
) {
|
|
139
|
+
return trackUsage(client, { accountUid, addOnUid, amount, ...options });
|
|
140
|
+
}
|