Socket
Book a DemoInstallSign in
Socket

@diagonal-finance/sdk-be

Package Overview
Dependencies
Maintainers
2
Versions
15
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install
Package was removed
Sorry, it seems this package was removed from the registry

@diagonal-finance/sdk-be

Diagonal finance Backend SDK

2.2.0
unpublished
latest
Source
npmnpm
Version published
Weekly downloads
0
Maintainers
2
Weekly downloads
 
Created
Source

Diagonal Backend SDK

SDK for easier interaction with the Diagonal backend (webhooks).

Github license GitHub Workflow test Coveralls Linter eslint Code style prettier

👥 Contributing   |   🤝 Code of conduct   |   🔎 Issues

Diagonal SDK backend is a collection of classes which enables developers easier interaction with the Diagonal backend.

Jest tests & common test coverage for all packages (npm test)
ESLint & Prettier to keep the code neat and well organized (npm run format & npm run lint)
♝ Automatic deployment of documentation generated with typedocs

📦 Package

PackageVersionDownloadsSize
@diagonal-finance/sdk-be (docs) NPM version Downloads npm bundle size (scoped)

🛠 Installation

ESMModule:

yarn add @diagonal-finance/sdk-be

📜 Usage

ESModule:

Webhook:

import {
  IWebhookEvent,
  WebhookEvent,
  DiagonalError,
} from '@diagonal-finance/sdk-be'

import express from 'express'

const app = express()
const endpointSecret = '78...b1'

// Parse body into JSON
app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => {
  let payload = req.body
  let signatureHeader = req.headers['diagonal-signature'] as string

  let event: IWebhookEvent

  try {
    event = WebhookEvent.construct(payload, signatureHeader, endpointSecret)
  } catch (e) {
    if (e instanceof DiagonalError.InvalidPayloadError) {
      // handle invalid payload error
    } else if (e instanceof DiagonalError.InvalidEndpointSecretError) {
      // handle invalid endpoint secret error
    } else if (e instanceof DiagonalError.InvalidSignatureHeaderError) {
      // handle invalid signature header
    } else if (e instanceof DiagonalError.InvalidSignatureError) {
      // handle invalid signature error
    } else {
      // handle another type of error
    }
    return res.sendStatus(400)
  }

  // Handle the event
  switch (event.type) {
    case WebhookEvent.Type.SubscriptionAcknowledged:
      console.log(
        `Account ${event.customerAddress} subscription was acknowledged!`,
      )
      // Then define and call a method to handle the acknowledged event
      // handleAcknowledged(data);
      break
    case WebhookEvent.Type.SubscriptionFinalized:
      console.log(
        `Account ${event.customerAddress} subscription was finalized!`,
      )
      // Then define and call a method to handle the successful attachment of a PaymentMethod.
      // handleFinalized(event);
      break
    case WebhookEvent.Type.SubscriptionReorged:
      console.log(`Account ${event.customerAddress} subscription was re-orged!`)
      // Then define and call a method to handle the successful attachment of a PaymentMethod.
      // handleReorg(event);
      break
    case WebhookEvent.Type.SubscriptionCanceled:
      console.log(`Account ${event.customerAddress} has canceled the subscription!`)
      // Then define and call a method to handle the successful attachment of a PaymentMethod.
      // handleUnsubscribe(event);
      break
    default:
      // Unexpected event type
      console.log(`Unhandled event type ${event.type}.`)
  }

  // Return a 200 response to acknowledge receipt of the event
  res.sendStatus(200)
})


...

app.listen(3000, () => console.log('Running on port 3000'));

Checkout session

import {
    Diagonal,
    Config,
    ICreateCheckoutSessionInput,
} from "@diagonal-finance/sdk-be";

const express = require("express");
const app = express();

const apiKey = "abc...";
const diagonal = new Diagonal(apiKey);
const YOUR_DOMAIN = "http://example.com";

app.post("/create-checkout-session", async (req, res) => {
    const checkoutSessionInput: ICreateCheckoutSessionInput = {
        customerId: "de49e7f2-bc33-4f4f-a3ae-c1207b02819c", // Immutable ID of your customer.
        packageId: "ff4e1d23-54ab-4385-9ea9-02c58ec5e32a",
        allowedChains: [Config.ChainId.Mumbai], // Optional. Can be used to limit to specific chains on runtime.
        cancelUrl: new URL(`${YOUR_DOMAIN}/cancel`),
        successUrl: new URL(`${YOUR_DOMAIN}/success`),
        optimisticRedirect: true, // Optional. Used to redirect to the success url if TX has been confirmed (no waiting for long confirmation).
    };

    const checkoutSession = await diagonal.checkout.sessions.create(
        checkoutSessionInput
    );

    console.info(`Checkout session created, UUID: ${checkoutSession.id}`);

    res.redirect(303, checkoutSession.url);
});

Portal Session

import {
    Diagonal,
    Config,
    ICreatePortalSessionInput,
} from "@diagonal-finance/sdk-be";

const express = require("express");
const app = express();

const apiKey = "abc...";
const diagonal = new Diagonal(apiKey);
const YOUR_DOMAIN = "http://example.com";

app.post("/create-portal-session", async (req, res) => {
    const portalSessionInput: ICreatePortalSessionInput = {
        customerId: "de49e7f2-bc33-4f4f-a3ae-c1207b02819c", // Immutable ID of your customer. Should not be email nor phone number.
        configuration: {
            availableChains: [Config.ChainId.Polygon],
            availablePackages: ["de49e7f2-bc33-4f4f-a3ae-c1207b02819c"],
        },
        returnUrl: new URL(`${YOUR_DOMAIN}/return`),
    };

    const portalSession = await diagonal.portal.sessions.create(
        portalSessionInput
    );

    console.info(`Portal session created, UUID: ${portalSession.id}`);

    res.redirect(303, portalSession.url);
});

🛠 Development

Clone this repository and install the dependencies:

git clone https://github.com/diagonal-finance/sdk-be.git
cd sdk-be && npm i

📜 Usage

npm run lint # Syntax check with ESLint (yarn lint:fix to fix errors).
npm run prettier # Syntax check with Prettier (yarn prettier:fix to fix errors).
npm test # Run tests (with common coverage).
npm run build # Create a JS build.
npm run publish # Publish a package on npm.

FAQs

Package last updated on 20 Jul 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

About

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.

  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc

U.S. Patent No. 12,346,443 & 12,314,394. Other pending.