@dintero/node-sdk 1.0.2

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/LICENSE ADDED
@@ -0,0 +1,19 @@
1
+ Copyright (C) 2024 Dintero AS. (https://dintero.com)
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in
11
+ all copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19
+ THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,120 @@
1
+ # Dintero Node.js SDK
2
+
3
+ [![Build Status](https://github.com/dintero/Dintero.Node.SDK/workflows/CI/badge.svg)](https://github.com/dintero/Dintero.Node.SDK/actions?query=workflow%3ACI+branch%3Amaster)
4
+
5
+ The Dintero Node SDK provides convenient access to the Dintero API from
6
+ applications written in server-side Javascript
7
+
8
+ ## Installation
9
+
10
+ Install the package with:
11
+
12
+ ```sh
13
+ npm install @dintero/node-sdk
14
+ # or
15
+ yarn add @dintero/node-sdk
16
+ ```
17
+
18
+ ## Usage
19
+
20
+ To use the Dintero Node.js SDK, you will need to configure it with your **API credentials** that can be created in the Dintero Backoffice. These credentials include the **Client ID**, **Client Secret**, and **Audience**, which are required for authenticating your requests to the Dintero API.
21
+
22
+ ### Example: Client Setup
23
+
24
+ You first need to create a client with the required credentials:
25
+
26
+ ```ts
27
+ import { createClient } from "@dintero/node-sdk";
28
+
29
+ const client = createClient({
30
+ clientId: 'your_client_id', // Replace with your actual client ID
31
+ clientSecret: 'your_client_secret', // Replace with your actual client secret
32
+ audience: 'https://api.dintero.com/v1/accounts/your_account_id',
33
+ });
34
+
35
+ export default client;
36
+
37
+ ```
38
+
39
+ ### Example: Session Profile
40
+
41
+ ```ts
42
+ import { createClient } from '@dintero/node-sdk';
43
+
44
+ const client = createClient({
45
+ clientId: 'your_client_id', // Replace with your actual client ID
46
+ clientSecret: 'your_client_secret', // Replace with your actual client secret
47
+ audience: 'https://api.dintero.com/v1/accounts/your_account_id',
48
+ });
49
+
50
+ const sessionProfileResponse = await client.checkout.POST('/sessions-profile', {
51
+ method: 'POST',
52
+ body: {
53
+ url: {
54
+ return_url: 'https://example.com', // Replace with actual return URL
55
+ },
56
+ order: {
57
+ amount: 1000,
58
+ currency: 'NOK',
59
+ items: [
60
+ {
61
+ id: 'item1',
62
+ line_id: 'line1',
63
+ description: 'Item 1',
64
+ amount: 1000,
65
+ quantity: 1,
66
+ vat_amount: 0,
67
+ vat: 0,
68
+ eligible_for_discount: false,
69
+ },
70
+ ],
71
+ partial_payment: false,
72
+ merchant_reference: 'ref123', // Replace with actual merchant reference
73
+ },
74
+ profile_id: 'profile123', // Replace with actual profile ID
75
+ },
76
+ headers: {
77
+ 'Content-Type': 'application/json',
78
+ 'Accept': 'application/json',
79
+ },
80
+ });
81
+
82
+ console.log('Session Profile Response:', sessionProfileResponse.data);
83
+ ```
84
+
85
+ ### Example: Fetching Settlement
86
+
87
+
88
+ ```ts
89
+ import { createClient } from '@dintero/node-sdk';
90
+
91
+ const client = createClient({
92
+ clientId: 'your_client_id', // Replace with your actual client ID
93
+ clientSecret: 'your_client_secret', // Replace with your actual client secret
94
+ audience: 'https://api.dintero.com/v1/accounts/your_account_id',
95
+ });
96
+
97
+ const settlementsResponse = await client.core.GET(`/accounts/${client.accountId}/settlements`, {
98
+ method: 'GET',
99
+ headers: {
100
+ 'Accept': 'application/json',
101
+ },
102
+ }
103
+ );
104
+ console.log('Settlements Response:', settlementsResponse.data);
105
+ ```
106
+
107
+ ## Bugs
108
+
109
+ Bugs can be reported to https://github.com/Dintero/Dintero.Node.SDK/issues
110
+
111
+ ## Security
112
+
113
+ Contact us at [security@dintero.com](mailto:security@dintero.com)
114
+
115
+ ## Building from source
116
+
117
+ ```bash
118
+ yarn install
119
+ yarn run build
120
+ ```
@@ -0,0 +1,9 @@
1
+ import type { paths } from "./generated/payments";
2
+ import type { ClientOptions } from "./types";
3
+ export type CheckoutPaths = Pick<paths, "/sessions-profile" | "/accounts/{oid}/auth/token" | "/sessions/{session_id}" | "/sessions/{session_id}/cancel" | "/transactions/{id}/capture" | "/transactions/{id}/authorization" | "/transactions/{id}/refund" | "/transactions/{id}/void" | "/transactions/{id}" | "/transactions">;
4
+ export type CorePaths = Pick<paths, "/accounts/{aid}/settlements" | "/accounts/{oid}/auth/token" | "/accounts/{aid}/reports/metadata" | "/accounts/{aid}/settlements/reports/configuration" | "/accounts/{aid}/settlements/reports/configuration/{id}" | "/accounts/{aid}/management/settings/approvals/payout-destinations" | "/accounts/{aid}/settlements/{settlementid}/attachments/{attachmentid}" | "/v2/accounts/{aid}/payout/fund-transfer" | "/v2/accounts/{aid}/payout/payout-destinations/{payout_destination_id}/balances" | "/v2/accounts/{aid}/payout/payout-destinations/{payout_destination_id}/transfers">;
5
+ export declare const createClient: (options: ClientOptions) => {
6
+ checkout: import("openapi-fetch").Client<CheckoutPaths, `${string}/${string}`>;
7
+ core: import("openapi-fetch").Client<CorePaths, `${string}/${string}`>;
8
+ accountId: string;
9
+ };
package/dist/client.js ADDED
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.createClient = void 0;
7
+ const openapi_fetch_1 = __importDefault(require("openapi-fetch"));
8
+ const middleware_1 = require("./middleware");
9
+ const createClient = (options) => {
10
+ const config = {
11
+ checkout: { baseUrl: "https://checkout.dintero.com" },
12
+ core: { baseUrl: "https://api.dintero.com" },
13
+ ...options,
14
+ };
15
+ const authMiddleware = (0, middleware_1.createAuthMiddleware)(config);
16
+ const versionPrefixMiddleware = (0, middleware_1.createVersionPrefixMiddleware)();
17
+ const checkout = (0, openapi_fetch_1.default)(config.checkout);
18
+ const core = (0, openapi_fetch_1.default)(config.core);
19
+ const accountId = (0, middleware_1.extractAccountId)(config.audience);
20
+ core.use(versionPrefixMiddleware, authMiddleware);
21
+ checkout.use(versionPrefixMiddleware, authMiddleware);
22
+ return { checkout, core, accountId };
23
+ };
24
+ exports.createClient = createClient;
@@ -0,0 +1 @@
1
+ export { createClient } from "./client";
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createClient = void 0;
4
+ var client_1 = require("./client");
5
+ Object.defineProperty(exports, "createClient", { enumerable: true, get: function () { return client_1.createClient; } });
@@ -0,0 +1,9 @@
1
+ import type { Middleware } from "openapi-fetch";
2
+ import type { ClientOptions } from "./types";
3
+ export declare const extractAccountId: (audience: string) => string;
4
+ export declare const fetchAccessToken: (config: Required<ClientOptions>) => Promise<{
5
+ accessToken: any;
6
+ expiresIn: any;
7
+ }>;
8
+ export declare const createAuthMiddleware: (config: Required<ClientOptions>) => Middleware;
9
+ export declare const createVersionPrefixMiddleware: () => Middleware;
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createVersionPrefixMiddleware = exports.createAuthMiddleware = exports.fetchAccessToken = exports.extractAccountId = void 0;
4
+ const extractAccountId = (audience) => {
5
+ if (!audience || !audience.includes("://")) {
6
+ throw new Error("Account ID could not be extracted from the audience URL.");
7
+ }
8
+ const audienceUrl = new URL(audience);
9
+ const pathParts = audienceUrl.pathname.split("/").filter(Boolean);
10
+ const accountId = audienceUrl.username || (pathParts.length >= 3 ? pathParts[2] : null);
11
+ if (!accountId) {
12
+ throw new Error("Account ID could not be extracted from the audience URL.");
13
+ }
14
+ return accountId;
15
+ };
16
+ exports.extractAccountId = extractAccountId;
17
+ const fetchAccessToken = async (config) => {
18
+ const accountId = (0, exports.extractAccountId)(config.audience);
19
+ const url = `${config.core.baseUrl}/v1/accounts/${accountId}/auth/token`;
20
+ const authToken = Buffer.from(`${config.clientId}:${config.clientSecret}`).toString("base64");
21
+ const response = await fetch(url, {
22
+ method: "POST",
23
+ headers: {
24
+ "Content-Type": "application/json",
25
+ Accept: "application/json",
26
+ Authorization: `Basic ${authToken}`,
27
+ },
28
+ body: JSON.stringify({
29
+ grant_type: "client_credentials",
30
+ audience: config.audience,
31
+ }),
32
+ });
33
+ const responseText = await response.text();
34
+ if (response.status !== 200) {
35
+ throw new Error(`Failed to fetch access token: ${response.statusText}. Details: ${responseText}`);
36
+ }
37
+ const json = JSON.parse(responseText);
38
+ return {
39
+ accessToken: json.access_token,
40
+ expiresIn: json.expires_in,
41
+ };
42
+ };
43
+ exports.fetchAccessToken = fetchAccessToken;
44
+ const createAuthMiddleware = (config) => {
45
+ let accessToken = undefined;
46
+ let tokenExpiry = 0;
47
+ return {
48
+ async onRequest({ request }) {
49
+ if (request.headers.get("Authorization")) {
50
+ return request;
51
+ }
52
+ const currentTime = Math.floor(Date.now() / 1000);
53
+ if (!accessToken || tokenExpiry < currentTime) {
54
+ const tokenData = await (0, exports.fetchAccessToken)(config);
55
+ accessToken = tokenData.accessToken;
56
+ tokenExpiry = currentTime + Math.floor(tokenData.expiresIn / 2);
57
+ }
58
+ request.headers.set("Authorization", `Bearer ${accessToken}`);
59
+ return request;
60
+ },
61
+ };
62
+ };
63
+ exports.createAuthMiddleware = createAuthMiddleware;
64
+ const createVersionPrefixMiddleware = () => ({
65
+ async onRequest({ request, schemaPath }) {
66
+ if (schemaPath.startsWith("/v")) {
67
+ return request;
68
+ }
69
+ const url = new URL(request.url);
70
+ url.pathname = `/v1${url.pathname ?? "/"}`;
71
+ return new Request(url.toString(), request);
72
+ },
73
+ });
74
+ exports.createVersionPrefixMiddleware = createVersionPrefixMiddleware;
@@ -0,0 +1,11 @@
1
+ export type ClientOptions = {
2
+ clientId: string;
3
+ clientSecret: string;
4
+ audience: string;
5
+ core?: {
6
+ baseUrl: string;
7
+ };
8
+ checkout?: {
9
+ baseUrl: string;
10
+ };
11
+ };
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@dintero/node-sdk",
3
+ "version": "1.0.2",
4
+ "description": "Node.js library for the Dintero API",
5
+ "main": "./dist/dintero.js",
6
+ "typings": "./dist/dintero.d.ts",
7
+ "files": [
8
+ "dist"
9
+ ],
10
+ "license": "MIT",
11
+ "private": false,
12
+ "publishConfig": {
13
+ "access": "public"
14
+ },
15
+ "author": "Dintero <support@dintero.com> (https://dintero.com/)",
16
+ "jest": {
17
+ "preset": "ts-jest",
18
+ "testMatch": [
19
+ "**/test/**/*.test.ts"
20
+ ]
21
+ },
22
+ "scripts": {
23
+ "build": "yarn -s build-ts && yarn -s lint",
24
+ "build-ts": "tsc -p ./tsconfig.build.json",
25
+ "test": "jest",
26
+ "lint": "biome check",
27
+ "convert-spec": "ts-node -T scripts/convert-spec.ts",
28
+ "semantic-release": "semantic-release",
29
+ "prepublishOnly": "yarn run build-ts"
30
+ },
31
+ "devDependencies": {
32
+ "@biomejs/biome": "1.8.3",
33
+ "@types/jest": "29.5.12",
34
+ "@types/js-yaml": "4.0.9",
35
+ "@types/node": "20.14.11",
36
+ "@types/swagger2openapi": "7.0.4",
37
+ "jest": "29.7.0",
38
+ "js-yaml": "4.1.0",
39
+ "msw": "2.4.3",
40
+ "openapi-typescript": "7.4.0",
41
+ "semantic-release": "24.1.1",
42
+ "swagger2openapi": "7.0.8",
43
+ "ts-jest": "29.2.5",
44
+ "ts-node": "10.9.2",
45
+ "typescript": "5.6.2"
46
+ },
47
+ "engines": {
48
+ "node": ">=20.0.0"
49
+ },
50
+ "dependencies": {
51
+ "openapi-fetch": "^0.12.0"
52
+ }
53
+ }