[ad_1]

How to use the PayPal subscription API with Node.js to manage recurring payments to serverless cloud features.

Posted in: PaypalJavascript

Our Google Add-on Store uses PayPal subscriptions with digital products to process recurring payments, and invoices are sent to customers through Document Studio.

There are two steps.

  1. The customer makes the payment and completes the order on our website.
  2. PayPal sends one BILLING.SUBSCRIPTION.ACTIVATED webhook to a serverless function.
  3. The feature (running on Firebase, Google Cloud) verifies the subscription and checks if the status is active.
  4. Invokes the Apps Script API to complete the command.

The cloud feature previously used PayPal’s official SDK for Node.js, but has recently become obsolete and no longer supports the new PayPal subscription API endpoints. Migrating the PayPal Node SDK to your own solution is relatively straightforward and involves two steps:

1. Get the PayPal access token

const { default: axios } = require("axios");

const getPayPalAccessToken = async () => {
  const client_id = "PayPal Client ID goes here";
  const client_secret = "PayPal Client Secret goes here";
  const options = {
    url: "https://api-m.paypal.com/v1/oauth2/token",
    method: "POST",
    headers: {
      Accept: "application/json",
      "Accept-Language": "en_US",
      "Content-Type": "application/x-www-form-urlencoded",
    },
    auth: {
      username: client_id,
      password: client_secret,
    },
    params: {
      grant_type: "client_credentials",
    },
  };
  const { status, data } = await axios(options);
  return data.access_token;
};

If you plan to test your integration with your PayPal trial account instead of the production version, replace it api-m.paypal.com in requests with api-m.sandbox.paypal.com and use the secret credentials of the sandbox client.

2. Verify your PayPal subscription

A successful request returns the HTTP 200 OK status code and a JSON response body.

const { default: axios } = require("axios");

const verifyPayPalSubscription = async (subscription_id) => {
  const token = await getPayPalAccessToken();
  const options = {
    method: "GET",
    url: `https://api-m.paypal.com/v1/billing/subscriptions/${subscription_id}`,
    headers: {
      Authorization: `Bearer ${token}`,
      Accept: "application/json",
    },
  };
  const { status, data = {} } = await axios(options);
  if (status === 200) {
    const { subscriber: { email_address } = {}, status } = data;
    return status === "ACTIVE";
  }
  return false;
};

Once the PayPal subscription is detected, an HTTP request is made to the Google Apps Script API that sends the invoice and license to the customer. Learn more.

Leave a Reply

Your email address will not be published. Required fields are marked *