Paypal API with angular | 400 (Bad Request)

2019-08-29 22:46发布

I'm working with paypal API and flowing with this document make your firest call.

I got a Status Code 400 (Bad Request) with an error message:

Object {error: "invalid_request", error_description: "grant_type is a required parameter"}

'Authorization': "Basic RU9KMlMtWjZPb05fbGVfS1MxZDc1d3NaNnkwU0ZkVnNZOTE4M0l2eEZ5WnA6RUNsdXNNRVVrOGU5aWhJN1pkVkxGNWNaNnkwU0ZkVnNZOTE4M0l2eEZ5WnA=",

In this case I used the Client-Id and Secret which provided by the example and encoded them in base 64.

$http({
            url: 'https://api.sandbox.paypal.com/v1/oauth2/token',
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded', 
                      'Authorization': "Basic RU9KMlMtWjZPb05fbGVfS1MxZDc1d3NaNnkwU0ZkVnNZOTE4M0l2eEZ5WnA6RUNsdXNNRVVrOGU5aWhJN1pkVkxGNWNaNnkwU0ZkVnNZOTE4M0l2eEZ5WnA=",
                      'Accept-Language': 'en_US'
                      },
            data: { grant_type: 'client_credentials' }
    }).success(function (data, status, headers, config) {
                console.log(data)
    }).error(function (data, status, headers, config) {
                console.log(data)
    });

2条回答
孤傲高冷的网名
2楼-- · 2019-08-29 23:35

The root cause is your data is encoded as JSON instead of application/x-www-form-urlencoded, so what you need to do is URL-encode data like:

$http({
    method: 'POST',
    url: url,
    data: $.param({grant_type: 'client_credentials'}),
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
查看更多
做个烂人
3楼-- · 2019-08-29 23:37

You'll need to include the 'withCredentials' option. Make sure that you put a colon in between your client-id and your secret key. You shouldn't need to encode those values at all, just use the ones Paypal gives you. I also think the data field should not be an object, as Paypal seems to be expecting a string.

If you are not using windows, I believe you'll need to set the content type to JSON, but the documentation is a bit vague there. Maybe try both? I think this request config should work:

url: 'https://api.sandbox.paypal.com/v1/oauth2/token',
method: 'POST',
withCredentials: true,
headers: {'Content-Type': 'application/json', 
          'Authorization': 'Basic {Client-Id}:{Secret}',
          'Accept-Language': 'en_US'
         },
data: 'grant_type=client_credentials'

Lastly, you may need to configure your $httpProvider. I've never had to, but I'm unsure of your environment and Angular version:

$httpProvider.defaults.useXDomain = true;
查看更多
登录 后发表回答