1

我可以通过传递以下参数通过 POSTMAN 调用获取访问令牌,

发布网址:https ://api.sandbox.paypal.com/v1/oauth2/token

授权 类型:基本认证

用户名:MY_CLIENT_ID

密码:MY_SECRET

标头 内容类型:application/x-www-form-urlencoded

正文 grant_type : client_credentials

请让我知道,如何在 Spring Boot 的 REST TEMPLATE 调用中设置上述详细信息以获取访问令牌

4

1 回答 1

1

可以参考以下代码

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());
    }
于 2019-12-26T12:11:38.610 回答