Node JS Example

Example code to demonstrate calling the Shieldpay API using Node JS.

          
            
import crypto from "crypto"; import fs from "fs"; import https from "https"; import fetch from "node-fetch"; const apiKey = "my-api-key"; const url = "https://api.sandbox.partner.shieldpay.com/v1/projects"; const requestId = crypto.randomUUID(); // Must be unique for every request. const timestamp = new Date().toISOString(); // Must be less than 5 minutes old. // Load private key and certificate. const privateKey = fs.readFileSync("/path/to/private.key"); const cert = fs.readFileSync("/path/to/certificate.pem"); // Create the payload for the request. const bodyPayload = JSON.stringify({ name: "my example project", // ... add additional props. }); // Create the string containing the key elements of the request, which we'll use // to generate the digital signature. For request methods without a body, e.g., GET, // you can omit the body from the string. E.g.: // const signatureString = `${url}${apiKey}${requestId}${timestamp}`; const signatureString = `${url}${apiKey}${requestId}${timestamp}${bodyPayload}`; // Generate a digital signature for the request. const signature = crypto .sign("RSA-SHA256", Buffer.from(signatureString), privateKey) .toString("base64"); // Make the API request. If you need to add query params, append them to the URL. E.g., // await fetch(`${url}?page_size=1`, ... const response = await fetch(url, { method: "POST", // Configure certificate and private key to establish mTLS connection. agent: new https.Agent({ cert, key: privateKey, }), // Add headers. headers: { Authorization: apiKey, Timestamp: timestamp, RequestID: requestId, DigitalSignature: signature, }, body: bodyPayload, }); const responseJSON = await response.json();