Search code examples
node.jspaypalbase64

Error Fetching PayPal REST API Credential


I am trying to set up a PayPal payment gateway in my React web app that makes use of a firebase function backend for token fetching and order creation. However, for the past few days I have been absolutely road blocked by the retrieving the access token. Here is the function that I am using to fetch the token

const generateAccessToken = async (PAYPAL_CLIENT_ID,PAYPAL_CLIENT_SECRET) => {
  try {
    if (!PAYPAL_CLIENT_ID || !PAYPAL_CLIENT_SECRET) {
      throw new Error("MISSING_API_CREDENTIALS");
    }
    const base = "https://api-m.sandbox.paypal.com";
    const auth = Buffer.from(
      PAYPAL_CLIENT_ID + ":" + PAYPAL_CLIENT_SECRET,
    ).toString("base64");
    const response = await fetch(`${base}/v1/oauth2/token`, {
      method: "POST",
      body: "grant_type=client_credentials",
      headers: {
        Authorization: `Basic ${auth}`,
      },
    });

    const data = await response.json();
    return data.access_token;
  } catch (error) {
    console.error("Failed to generate Access Token:", error);
  }
};

Once I run this, I get the message

message: 'Authentication failed due to invalid authentication credentials or a missing Authorization header.'

However, I have repeatedly verified that the credentials are correct for my Sandbox account. Thank you in advance for any help.


Solution

  • Using the credentials from the logged auth, I tried the following in a browser console using btoa instead of Buffer and it works as expected.

    generateAccessToken = async (PAYPAL_CLIENT_ID,PAYPAL_CLIENT_SECRET) => {
      try {
        if (!PAYPAL_CLIENT_ID || !PAYPAL_CLIENT_SECRET) {
          throw new Error("MISSING_API_CREDENTIALS");
        }
        const base = "https://api-m.sandbox.paypal.com";
        const auth = btoa(
          PAYPAL_CLIENT_ID + ":" + PAYPAL_CLIENT_SECRET,
        );
        const response = await fetch(`${base}/v1/oauth2/token`, {
          method: "POST",
          body: "grant_type=client_credentials",
          headers: {
            Authorization: `Basic ${auth}`,
          },
        });
    
        const data = await response.json();
        return data.access_token;
      } catch (error) {
        console.error("Failed to generate Access Token:", error);
      }
    };
    
    generateAccessToken('Ad1TLtgzVXT63b98Sf0sdwSTTF7o11uFw_jLplNEQNYdzVlyGC6-liUaPy2D85Aie2WKxr-BrzNCBmFn','EFvbe7j6LL90bc0TpJlmEcyDY6eETquP4WskPPzeJ1tDdQh5jaWXBZF_6MEbbQ1SDH64m_JJ6AIrs8Z_').then((token) => console.log(token))
    

    ^ this prints a token to the console. Don't know what would be resulting in errors in your case as code and credentials are essentially the same thing.