Get Access Token in Ionic

Asked

Viewed 225 times

0

Through the command prompt I get an access token.

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

In the project I use this token and get a json.

Service.ts

getPayment() {
let token = 'A21AAGsiyUhk3ntiu7MMtkvc_aTKaXyWHdfKRrMV0qqNyPQ1ZzxXrT2oxGGdz8wLVcgZzmwgQ8r1mdMLprw0vsB374AI8D2AA';
const httpOptions = {
  headers: new HttpHeaders().set("Authorization", [`Bearer ${token}`]).set("Content-Type", "application/json")
}
return this.http.get("https://api.sandbox.paypal.com/v1/payments/payment/PAY-1826783671569693VLQ2IYVQ", httpOptions)
  .pipe(
    catchError(this.handleError)
  );
}

Component.

  this.authService.getPayment().subscribe((response) => {
   console.log('abcde', JSON.stringify(response))
 });

However, I need to generate this Token automatically, but I don’t know how to send my Client_id and Secret by parameter. Any help?

  • You have to make a get request for this URL by passing these parameters.

  • I edited my question, maybe I can understand a little better. Thanks

2 answers

0


In case anyone ever needs it, here’s the solution I got:

var request = require('request');

request.post({
    uri: "https://api.sandbox.paypal.com/v1/oauth2/token",
    headers: {
        "Accept": "application/json",
        "Accept-Language": "en_US",
        "content-type": "application/json"
    },
    auth: {
        'user': 'SEU CLIENT ID',
        'pass': 'SEU CLIENT SECRET',
        // 'sendImmediately': false
    },
    form: {
        "grant_type": "client_credentials"
    }
}, function(error, response, body) {
    console.log(body);
});

if require is not accepted:

npm i @types/node
and add:

"types": [
    "node"
],
"typeRoots": [
    "node_modules/@types"
]

in the archive tsconfig.json
and also: declare var require: any; in its component

-2

pegarToken(){
 const auth = btoa(`${this.clientId}:${this.clientSecret}`);//substitui pelo seu id e secret
 return `Bearer ${auth}`;
}


getPayment() {
let token = this.pegarToken();
const httpOptions = {
  headers: new HttpHeaders().set("Authorization", token).set("Content-Type", "application/json")
}
return this.http.get("https://api.sandbox.paypal.com/v1/payments/payment/PAY-1826783671569693VLQ2IYVQ", httpOptions)
  .pipe(
    catchError(this.handleError)
  );
}
  • Thank you for answering, but where do I call "https://api.sandbox.paypal.com/v1/oauth2/token" ? I’m not sure, can you give me an explanation? Thx

  • at the time you subscribe to your component it will make this http request. Every time you subscribe to the function return observable it will make the request.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.