1

I can get access token with POSTMAN call by passing below parameters,

POST URL : https://api.sandbox.paypal.com/v1/oauth2/token

Authorization Type : Basic Auth

Username : MY_CLIENT_ID

Password : MY_SECRET

Headers Content-Type : application/x-www-form-urlencoded

Body grant_type : client_credentials

Please let me know, how can I set above details in REST TEMPLATE call in spring boot to get access token

Chirag Shah
  • 353
  • 1
  • 13
  • 1
    You need to set authorization as part of header only. Username and Password are Base64 encoded when you send the request; you need to do the same in Java before requesting for access token. – Akash Jan 23 '19 at 05:22
  • Assuming you know how to make restTemplate call in Spring boot. If not, please go through the tutorial https://spring.io/guides/gs/consuming-rest/ first – Akash Jan 23 '19 at 05:28

1 Answers1

2

you can refer to the following code

public void run(String... args) throws Exception {
        StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
        RestTemplate restTemplate = new RestTemplateBuilder()
                .setConnectTimeout(Duration.ofSeconds(60))
                .additionalMessageConverters(stringHttpMessageConverter)
                .build();

        String uri = "https://api.paypal.com/v1/oauth2/token?grant_type=client_credentials";
        String username = "yourAppClientId";
        String password = "yourAppPwd";

        HttpHeaders basicAuth = new HttpHeaders() {{
            String auth = username + ":" + password;
            byte[] encodedAuth = Base64.encodeBase64(
                    auth.getBytes(StandardCharsets.US_ASCII));
            String authHeader = "Basic " + new String(encodedAuth);
            set("Authorization", authHeader);
        }};

        ResponseEntity<String> response = restTemplate.exchange
                (uri, HttpMethod.POST, new HttpEntity<>(basicAuth), String.class);
        System.out.println(response.getBody());
    }
Leven.Chen
  • 21
  • 3