With the launch of the new PayPal REST APIs there comes a new way of authenticating your application to begin receiving payments, issuing refunds, storing credit card information and a slew of other features.

In this post, I’m going to introduce you to working with the OAuth 2 bearer tokens that the REST APIs use as their auth mechanism. At the end of the post, you should have a good understanding on how the system works and how to use it to build out calls to the new APIs.

A little background on our use of OAuth 2

Before we get into the code, there are a few things that you should know about the PayPal implementation of OAuth 2 that you may or may not be familiar with.

You may already be used to working with a flow where the user will have to grant your application permission to use their information or do something on their behalf using a regular access token. Instead of this flow, PayPal uses bearer tokens that do not have a user step to sign in and authorize the application in this familiar construct. Instead, the bearer token is obtained by passing your client id and secret keys using basic auth to PayPal servers. Once the bearer token is obtained, it will be supplied as an authorization header when making GET / POST requests to work with the APIs.

You can find more information on our implementation here.

Defining your keys and URIs

The first step that you’re going to need to do is to define your application keys and the URIs that we’re going to be working with.

First off, go to the REST API Credentials page directly (or from developer.paypal.com go to the “Applications” tab, then click on “REST API credentials” from the left hand menu). On this page you will be able to see your sandbox and live credentials. Simply copy the values that you want to use into the code sample above. The URI endpoints for sandbox and live are already defined.

Fetching the bearer token

Now that we have our URIs and keys defined, we can start creating a class wrapper with a few methods to fetch the OAuth 2 bearer token. Within this class, we will have several main pieces that we will begin working with:

  • Properties: We define two private properties for the call to store the access token / bearer token and the token type (which will be Bearer).
  • Constructor method: Our constructor will make the requests to PayPal servers (via the cURL method) to obtain the bearer token and store it in the properties above.
  • cURL method: This will not only be the method that makes the HTTP requests to obtain the bearer token, but will also handle any HTTP requests to invoke PayPal APIs using the bearer token.

If we break down these code sample pieces into their individual methods, we can see the flow of how they work.

Constructor
When a new instance of the paypal class in instantiated, the constructor will be invoked. In the code, it goes through several steps:

  1. We set up the POST parameter, grant type, with a value of client_credentials to instruct the OAuth 2 request to PayPal that we are making a request for client credentials.
  2. We then set up the URI that we will make this HTTP POST request to, which will be https://api.sandbox.paypal.com/v1/oauth2/token on the sandbox.
  3. Next we issue an HTTP POST request through the cURL method to return our bearer token. An object containing these details will be returned to us.
  4. We then parse apart that object to store the bearer token and token type in our private properties.

cURL
The cURL method is going to allow us to generate requests for our bearer tokens, but also permit authenticated HTTP GET and POST requests to the APIs once we have that token. The method has a few parameters that can be supplied:

  • url: the URL that we will make a request to.
  • method: The HTTP request method to be used, either GET or POST in our cases.
  • postvals: The POST body to be supplied with a POST request.
  • auth: A boolean value for whether we are making a request to get the bearer token. If true, the basic auth headers with our key / secret will be used instead of the bearer token authorization header.

We first initialize the cURL request with curl_init. Next we need to set the headers of the request. If we are making a request to get the bearer token ($auth == true), then we set up a basic auth header, passing in our client id and secret as the username and password values. If we are making a request to the APIs using the bearer token ($auth == false), then we set a content type header and an Authorization header, supplying the token type and the bearer token.

We then set up the cURL options that we want to use, which are fairly standard. We set up options to send a header, enable verbose output, return the response from the server, and set a 10 second timeout on the request (because the bearer token fetch may take ~ 5 seconds on sandbox to respond. If an HTTP POST request is being made, we also set options for the HTTP request type and supply the POST body to the request.

Lastly, we make the cURL request, then split the response into the header and body and return both pieces.

Making a call with the bearer token

At this point we have everything we need to start making requests to the APIs using the cURL method. Let’s take a look at what one of these requests will look like if we want to process a credit card payment from someone.

In this simple wrapper, the user will supply a JSON string for the payment POST request that they want to make, based on the API specification for the request. We simply need to create a POST body object, set the URI (which will be https://api.sandbox.paypal.com/v1/payments/payment on the sandbox), then return the response from the cURL request. What we should be left with is an object containing the success response, or an appropriate error if something went wrong.

That’s really all you need to do to work with the new REST APIs using bearer tokens. There are also SDKs available if you want to bypass this deep integration, which are detailed (with samples) in this post.

Tell me what might be helpful for you

In my next post on the subject I will post out a new PHP API wrapper that extends everything we went through here, and includes methods for working with all functionality of the new APIs, and includes proper error handling. Of course, I really do want to hear from everyone to let me know if there are any samples or walkthroughs in particular that you might find helpful. Would you like to see some video screencast, other tutorials, other languages? Please let me know and I’ll do what I can to put together that for you.

About Jonathan LeBlanc

Jonathan LeBlanc is an Emmy award winning software engineer, author of the O’Reilly books “Identity and Data Security for Web Development” and "Programming Social Applications", and the Head of Global Developer Advocacy for PayPal. Specializing in identity, auth and security, hardware to web interconnectivity, and data mining techniques, as well as open source initiatives around social engagement, Jonathan works on the development of emerging initiatives towards building a more user-centric web.

Tagged with:
 

9 Responses to Authenticating with OAuth 2 in the new RESTful APIs

  1. David R. Schaller says:

    Great article. I hope to see all disparate PayPal API’s move to using REST. Is it currently possible to use the REST APIs for facilitating payment requests between two parties – ‘Adaptive Payments’? Our members would like to collect funds on our website from their users.
    -David

  2. jcleblanc says:

    Hi David,

    I agree, I’m looking forward to seeing more functionality being added to the REST APIs. I enjoy the idea of including functionality as it’s needed instead of binding to a single set of APIs.

    Right now payments through the REST APIs are restricted to payments to the code implementer (for instance, making payments through a website), but the multi-user approach that adaptive payments makes available has not been included as of yet.

    Stay tuned though, we’ll keep rolling out new features into the REST APIs, and that is a popular model.

    – Jon

  3. Igor says:

    Thank you for interesting notes.
    I would like to ask when users could expect other currencies (like EUR) on RESTfull APIes?

  4. Guest says:

    I don’t have any specific dates yet for the releases outside the US, but I can tell you that the team is actively working on providing alternate currencies. We on the outreach teams are waiting on the alternate currencies as well.

  5. jcleblanc says:

    I don’t have any specific dates yet for the releases outside the US, but I can tell you that the team is actively working on providing alternate currencies. We on the outreach teams are waiting on the alternate currencies as well.

  6. Andrew Angell says:

    So is it correct that I end up with a new access token for pretty much every call I make? Or at least each script I run..??

    This article helped me to get this built into my own set of class libraries for PayPal (thanks for that!) and I’m to the point where I followed your procedure to generate access token in the constructor of the class.

    Then in my actual scripts I create an object of this class and I simply output the value to make sure it’s working as expected, and it is, but each time I refresh that page I get a new access token.

    Should I be caching the access token and re-using it or is that correct to generate one for basically every instance? If I were to re-use the access token, though, I guess I’d have to pull the generation of it out of the constructor and into its own method that I could only call when a previous token is expired..??

    Just trying to get my around how the tokens and everything works. I’ve always had issues understanding oauth for some reason. Any info on that would be greatly appreciated!

  7. jcleblanc says:

    Hi Andrew,

    I’m sorry that I missed this message from you, but wanted to respond in any event in case you were still wondering or if there was anyone else out there with the same questions.

    When working with OAuth 2 / OpenID Connect, or any of those auth specs, the proper way to work with an access token is not to re-generate a new token each time you refresh the page. Instead, you should store the access token and make requests using that token until it expires.

    I hope that helps,

    Jon

  8. Mike says:

    This article has been very helpful. The only thing I was wondering if you ever wrote the next article that you talk about at the end of this one?

  9. Agostino Cinelli says:

    Maybe a bit offtopic, but… are the REST API compatible with .NET and Azure? The authenticate method is throwing an axception on
    get_OperatingSystemFriendlyName().
    Any hints?