Home > Software design >  Paypal Subscription cancel - Translate CURL command
Paypal Subscription cancel - Translate CURL command

Time:12-30

I want to add the option for users to cancel a Paypal Subscription for my Web App.

https://developer.paypal.com/docs/api/subscriptions/v1/#subscriptions_cancel

https://developer.paypal.com/reference/get-an-access-token/

https://developer.paypal.com/api/rest/authentication/

I understand that first I need to call a endpoint with my project ID and secret. Do I need to do this on the server so the secret is not exposed?

Then use the authentication data received and make another call for the subscription ending.

CURL code:

 curl -v https://api-m.sandbox.paypal.com/v1/oauth2/token \ -H "Accept: 
 application/json" \ -H "Accept-Language: en_US" \ -u "client_id:secret" \ -d 
 "grant_type=client_credentials"

The Postman documentation: "

  1. Download Postman for your environment. In Postman, select the POST method.
  2. In Postman, select the POST method.
  3. Enter the https://api-m.sandbox.paypal.com/v1/oauth2/token request URL.
  4. On the Authorization tab, select the Basic Auth type. Type your client ID in the Username box, and type your secret in the Password box.
  5. On the Body tab, select x-www-form-urlencoded. Type grant_type in the key box, and type client_credentials in the value box.
  6. Click Send

"

Can someone please translate the CURL code into a fetch API request? Can someone please explain the steps that I have to take to cancel a PayPal subscription?

https://www.paypal.com/merchantapps/appcenter/acceptpayments/subscriptions

CodePudding user response:

I was able to perform a successful authentication on Postman Desktop for Mac following the instructions provided by PayPal and listed above.

Then I looked in Postman for Code Snippet in JavaScript fetch and found out what I was looking for.

I was a little confused by the requirement of base 64 encoding required(btoa()) and automatically done by Postman and added in the code snippet.

The comment from @Peter Thoeny was also helpful.

This is the code that I used for authentication and cancel authorization:

var myHeaders = new Headers();
myHeaders.append("Authorization", "Basic "   btoa("ClientID:Secret") );
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");

var urlencoded = new URLSearchParams();
urlencoded.append("grant_type", "client_credentials");

var requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: urlencoded
};

fetch("https://api-m.sandbox.paypal.com/v1/oauth2/token", requestOptions)
  .then( (response) => response.json())
  .then(result => {
    console.log(result);

    var myHeaders = new Headers();
    myHeaders.append("Authorization", "Bearer "   result.access_token );
    myHeaders.append("Content-Type", "application/json");

    fetch("https://api-m.sandbox.paypal.com/v1/billing/subscriptions/"   _this.lastSubscriptionData.resourceId   "/cancel", {
      method: 'POST',
      headers : myHeaders
    })
    .then( (response) => response.text())
    .then( (result) => {
      console.log(result);
    })
    .catch( (error) => console.log('error', error));

  })
  .catch(error => console.log('error', error));

CodePudding user response:

Using 'axios` version

const axios = require('axios')
const config = require('./config.json');
const getAccessToken = async () => {
    try {
        const resp = await axios.post(
            'https://api-m.sandbox.paypal.com/v1/oauth2/token',
            '',
            {
                params: {
                    'grant_type': 'client_credentials'
                },
                auth: {
                    username: config.CLIENT_ID,
                    password: config.CLIENT_SECRET
                }
            }
        );
        // console.log(resp.data);
        return Promise.resolve(resp.data.access_token);
    } catch (err) {
        // Handle Error Here
        console.error(err);
        return Promise.reject(err);
    }
};

getAccessToken()
    .then((token) => {
        console.log(token);
    })

config.json

{
    "CLIENT_ID" : "***** your Client ID *******",
    "CLIENT_SECRET" : "***** your client secret ********"
}

And curl version

CLIENT_ID='***** your Client ID *******'
CLIENT_SECRET='***** your client secret ********'
CLIENT_ID_SECRET=$(echo -n $CLIENT_ID:$CLIENT_SECRET | base64 -w 0)

ACCESS_TOKEN=$(curl -v https://api-m.sandbox.paypal.com/v1/oauth2/token \
-H "Accept: application/json" \
-H "Accept-Language: en_US" \
-H 'Authorization: Basic '$CLIENT_ID_SECRET \
-d "grant_type=client_credentials" | jq -r '.access_token')
echo $ACCESS_TOKEN
  • Related