Tag Archives: REST

New REST API Feature: Setting a Receiver for Payments

By and

Until recently, if you have been using the PayPal REST APIs to process payments, you will have seen that the money transacted is always paid to the app owner, known as the payee or receiver. The ability to change the receiver of funds in a transaction by setting a different payee has been a highly requested feature by our developer community.

With that said, we’re happy to share that you can now set the payment receiver when making direct payments in the REST APIs. When setting your payment transaction details, before starting the payment, simply add a payee object and include the email address of the account that should receive the payment. A sample payment JSON object that includes a payee email may look something like this:

{
    'intent':'sale',
    'redirect_urls':{
        'return_url':'http://localhost:3000/process',
        'cancel_url':'http://localhost:3000/cancel'
    },
    'payer':{
        'payment_method':'paypal'
    },
    'transactions':[{
        'amount':{
            'total':'10',
            'currency':'USD'
        },
        'payee':{
            'email': 'payee@test.com'
        },
        'description':'My amazing product'
    }]
}

You can see the full payee object definition in our API documentation.

Currently this functionality is available globally, where PayPal is available, for standard PayPal and credit card payments through the REST APIs only, but we’re working hard to get it enabled for all feature endpoints. Please note that direct credit card payments and their related features are restricted in some countries.

Happy coding!

Webhooks for REST APIs launched

By

(By Joe Nash & Alberto López)


PayPal’s latest addition to the roster of products taking advantage of PayPal REST API technology gives developers easier access to notifications of payment activities, such as payment status updates. PayPal webhooks are now available, and not only do they enable similar functionality to that of the IPN available in the Classic APIs, but they provide additional functionality to ease development and create innovative new products.

What is a webhook?

When we discuss webhooks, we refer to three key actors:

  • Webhooks: A webhook takes the form of a POST request to a URL that you set via your PayPal account. When a payment is made, or the status of a payment changes, the POST request is triggered, sending an event. This allows you to see and work with payment updates in real time. Webhooks can be created, updated, listed and deleted all through your PayPal account.
  • Events: An event contains the details about the payment update, including: the time of payment authorization or the amount of a payment or refund. Past events are searchable, and can also be resent in a webhook. There are multiple event types.
  • Event types: Event types can be selected to only cause the triggering of webhooks for specific payment updates and information, allowing you to choose to receive POST requests about the information that is important to you and your product.

Through these three actors, developers can manage operations that happen during the transaction lifecycle. Developers can list all of the event types subscribed to by a given webhook, perform more focused searches such as searching for webhooks by event type, and the API itself can be used to retrieve webhook events.

What operations are available using webhooks?

Webhooks provide some interesting functions for developers:

What are the differences between Webhooks and IPN?

At first glance, the differences between Webhooks and IPN used in the Classic API are subtle. What makes webhooks desirable over IPN is their sheer customisability versus IPN:

  • Whilst IPN did allow for the configuration of different IPN listener’s for different transactions, the IPN listener had to be predefined in the PayPal account. Further, it could only be modified through the PayPal account, and by default all refunds notify to this listener. With Webhooks you will be able to create different webhooks via the API for managing different event types (an authorization created, or voided or refunded), and modify each of them using an API REST call.
  • Webhooks enable the retrieval via API of any webhook event that was unable to be collected in the initial triggering of the webhook. In contrast, IPN events were only accessible via the PayPal account.
  • Webhooks have the important property of real time event notification, whilst with IPN, some delays could be experienced.

It is clear that webhooks give distinct advantages versus IPN; they are more flexible, versatile and can be used in real time. Let’s see how they work.

How do Webhooks work?

To use the webhook API in the Sandbox, first do the following:

  1. Go to the My REST apps page.
  2. Create an application, if you haven’t done so already.
  3. Add a webhook URL (the maximum number of webhooks is 10).
  4. Subscribe to the event types of interest. As we said before, you can also choose to manage webhooks, events, and event types through the Webhooks API.

Getting the bearer token:

Request

curl https://api.sandbox.paypal.com/v1/oauth2/token
\ -H "Accept: application/json" 
\ -H "Accept-Language: en_US" 
\ -u "<Client-Id>:<Secret>" 
\ -d "grant_type=client_credentials”

Response

{ "scope": "https://api.paypal.com/v1/payments/.*
https://api.paypal.com/v1/vault/credit-card/
https://api.paypal.com/v1/vault/credit-card/.*",
"access_token": "EEwJ6tF9x5WCIZDYzyZGaz6Khbw7raYRIBVTTTWxVvgmsG",
"token_type": "Bearer",
"app_id": "APP-6XR95014BA15863X",
"expires_in": 28800
}

Creating the webhook via API

Request

curl -v POST https://api.sandbox.paypal.com/v1/notifications/webhooks \
-H 'Content-Type:application/json' \
-H 'Authorization: 
        Bearer EEwJ6tF9x5WCIZDYzyZGaz6Khbw7raYRIBVTTTWxVvgmsG' \
-d '{
   "url": "http://www.yeowza.com/paypal_webhook",
   "event_types": [
       {
           "name": "PAYMENT.SALE.REFUNDED"
       },
       {
           "name": "PAYMENT.CAPTURE.REFUNDED"
       }
   ]
}'

Response

{
"id":"0E842532SB505363J",
"url":"https://www.mysite.com/paypal_webhook",
"event_types":[
    {
        "name":"PAYMENT.SALE.REFUNDED",
        "description":"A sale payment was refunded"
    },
    {
        "name":"PAYMENT.CAPTURE.REFUNDED",
        "description":"A capture payment was refunded"}
    ],
"links":[
    {
     "href": "https://api.sandbox.paypal.com/v1/notifications/
             webhooks/0E842532SB505363J",
     "rel":"SELF",
     "method":"GET"
    },
    {
     "href": "https://api.sandbox.paypal.com/v1/notifications/
             webhooks/0E842532SB505363J",
     "rel":"UPDATE",
     "method":"PATCH"
    },
    {
     "href": "https://api.sandbox.paypal.com/v1/notifications/
             webhooks/0E842532SB505363J",
     "rel":"DELETE",
     "method":"DELETE"
     }
]
}

After making a payment, you’ll receive in your webhook (https://www.mysite.com/paypal_webhook) an event type with the information of the event type:

{
 "id": "WH-0AF57170N8121644E-6VF27453LH2982421",
 "create_time": “2014-09-25T21:41:28Z",
 "resource_type": "authorization",
 "trigger_event": "PAYMENT.AUTHORIZATION.CREATED",
 "summary": "A payment authorization was created",
 "resource": {
   "id": "0MW879906U0874649",
   "create_time": "2014-09-25T21:39:15Z",
   "update_time": "2014-09-25T21:39:17Z",
   "state": "authorized",
   "amount": {
     "total": “10.00",
     "currency": "USD",
     "details": {
       "subtotal": “10.00"
     }
   },
   "parent_payment": "PAY-0AB48420EF007493KKQVUMBY",
   "valid_until": "2014-07-24T21:39:15Z",
   "links": [
     {
       "href": "https://api.sandbox.paypal.com/v1/payments/
               authorization/0MW879906U0874649",
       "rel": "self",
       "method": "GET"
     },
     {
       "href": "https://api.sandbox.paypal.com/v1/payments/
               authorization/0MW879906U0874649/capture",
       "rel": "capture",
       "method": "POST"
     },
     {
       "href": "https://api.sandbox.paypal.com/v1/payments/
               authorization/0MW879906U0874649/void",
       "rel": "void",
       "method": "POST"
     },
     {
       "href": "https://api.sandbox.paypal.com/v1/payments/
               payment/PAY-0AB48420EF007493KKQVUMBY",
       "rel": "parent_payment",
       "method": "GET"
     }
   ]
 },
 "links": [
   {
     "href": "https://api.sandbox.paypal.com/v1/notfications/
             webhooks-events/WH-0AF57170N8121644E-6VF27453LH2982421",
     "rel": "self",
     "method": "GET"
   },
   {
     "href": "https://api.sandbox.paypal.com/v1/notfications/
             webhooks-events/WH-0AF57170N8121644E-6VF27453LH2982421/
             resend",
     "rel": "resend",
     "method": "POST"
   }
 ]}

In our webhook event, we get all of the information, coupled with useful links, given by the event type. From here, we can perform some operations on the data, update our databases, or launch a process after ensuring the process is done.

Subscriptions are Now Available in the PayPal REST APIs

By and

As of today, I am happy to announce that subscription models (what we call billing plans and agreements) have launched as our newest piece of functionality in the PayPal REST APIs.

This long awaited feature will allow you to not just process one time payments, but instead set up and modify entire recurring payment cycles, including the ability to incorporate trial periods for greater product control.

How it Works

While there is a lot of new functionality to play with in this API release, let’s start by taking a look at how to get to the point of starting to bill a customer on a monthly basis, and also include a trial period for the product for people to try before they buy.

In its simplest form, how we make a subscription model work is a two step process:

  1. Create a Billing Plan: Basically all you’re doing here is creating the billing template that you can use to subscribe users to a particular billing plan.
    Tip: You can have multiple billing plans set up at the same time.
  2. Create a User Billing Agreement: Once you have the billing plan template in place, you can then use that template in the payment process to set up a recurring payment cycle for a user, such as monthly.

That’s pretty much the gist of it, create a billing plan, then assign a user to a particular plan (called a billing agreement) when you push them through to pay. Let’s dive a little bit deeper into these features, and see how each piece works.

Creating a Billing Plan

Let’s say we run a “Fruit of the Month” club, and we sell monthly subscriptions to ship a new assortment of unique fruits to people monthly. For new customers, we also offer a trial period where you can have the first month free, to take a look at the quality of the product. The request to the billing plan API would look something like this:

    curl -v POST https://api.sandbox.paypal.com/v1/payments/billing-plans \
-H 'Content-Type:application/json' \
-H 'Authorization: Bearer {accessToken}' \
-d '{
    "name": "Fruit of the Month",
    "description": "10 Pound Box of Fruit",
    "type": "fixed",
    "payment_definitions": [
        {
            "name": "Standard Package",
            "type": "REGULAR",
            "frequency": "MONTH",
            "frequency_interval": "2",
            "amount": {
                "value": "50",
                "currency": "USD"
            },
            "cycles": "12",
            "charge_models": [
                {
                    "type": "SHIPPING",
                    "amount": {
                        "value": "8",
                        "currency": "USD"
                    }
                },
                {
                    "type": "TAX",
                    "amount": {
                        "value": "4",
                        "currency": "USD"
                    }
                }
            ]
        },
        {
            "name":"First Month Free Trial",
            "type":"TRIAL",
            "frequency":"MONTH",
            "frequency_interval":"1",
            "amount": { 
            "value" : "50",
            "currency" : "USD"
        },
        "cycles":"1",
        "charge_models": [
            {
                "type":"SHIPPING",
                "amount": { 
                    "value" :"8",
                    "currency" : "USD"
                }
            },
            {
                "type":"TAX",
                "amount": {
                    "value" :"4",
                    "currency" : "USD"
                }
            }
        ]
    }],
    "merchant_preferences": {
        "setup_fee": {
            "value": "1",
            "currency": "USD"
        },
        "return_url": "http://www.fruitofthemonth.com/complete",
        "cancel_url": "http://www.fruitofthemonth.com/cancel",
        "autobill_amount": "YES",
        "initial_amount_fail_action": "CONTINUE",
        "max_fail_attempts": "0"
    }
}'

Once you create the billing plan, you’ll get a JSON response back, which will include an ID referencing back to the billing plan. This is what we’re going to use when we push a user through to the payment step to reference what billing plan we want them signed up to, called a billing agreement.

Subscribing a User to a Billing Agreement

Next, let’s say a customer has come to our site and wants to subscribe to the “Fruit of the Month” club. She picks the plan that she wants to be a part of (let’s say a 10 pound box of fruit) and is subscribed using a billing agreement (essentially just subscribing a user to a billing plan) that we just set up by pushing her to PayPal to use her account.

curl -v POST https://api.sandbox.paypal.com/v1/payments/billing-agreements
-H 'Content-Type:application/json' \
-H 'Authorization: Bearer {accessToken}' \
-d '{
    "name": "Main Subscription",
    "description": "Fruit of the Month Subscription",
    "start_date": "2015-02-19T00:37:04Z",
    "plan": {
        "id": "P-0NJ10521L3680291SOAQIVTQ"
    },
    "payer": {
        "payment_method": "paypal"
    },
    "shipping_address": {
        "line1": "My Business",
        "line2": "1665 Biscayne rd",
        "city": "Miami",
        "state": "FL",
        "postal_code": "33141",
        "country_code": "US"
    }
}'

As you can see from the sample, we are sending a user through a standard PayPal payment method, passing in the new “plan” object within the request payload. That will reference the ID that we gained back when creating the billing plan above. We will get back a redirect URL to forward the user to in order to sign in to their PayPal account.

That’s pretty much it for our simple example. Between a billing plan and the user billing agreement, you can create any number of subscription scenarios for your customers.

Going Further

We’ve obviously just began to touch on all of the functionality that’s available to us with the new billing plan / billing agreement APIs. We can go further with mechanisms to suspend and revoke billing agreements, update parts of billing plans, and a number of other scenarios.

As you build out your subscription system, you can dive into more detail about the capabilities on the REST API docs.

Open sourcing genio

By

The PayPal Developer team strives to build SDKs and Tools that make it easy for developers and integrators to work with PayPal APIs. Our SDKs are designed with a shared core component that handles cross cutting concerns and different API specific components that contain model classes and utility wrappers.

When we sat down to write the API specific components, lazy developers that we are, we looked out for code generation tools that we could bootstrap on. We found a few open source code generators such as java2wsdl but none that had support for custom templates or could generate classes in multiple languages. So we sat down to write genio (pronounced ‘genie-oh’), our very own code generator that we are happy to now open source.

genio is a pluggable code generation system that can parse various API specification files into a generic model. The parsed model is pumped through a set of templates to generate full fledged classes with class documentation from the API specification file and custom logic for plugging into our core SDKs. The SDKs that you see on GitHub have all been generated using the tool. genio has helped us upgrade our SDKs and other tools within minutes of a new release. The upgrade is often triggered by a git commit hook on the API repo. When we released the new REST APIs back in February, we wrote a new WADL parser that produced genio compliant model objects and with a few minor tweaks to our templates, we were ready with the first version of our REST SDKs. Subsequently we switched to using the Google discovery format and it was a trivial task for us to start generating the SDKs using the new specification format. In all, the current release has parsers for WSDL, WADL and the Google discovery format. We will follow up this release with API documentation generation features and support for JSON schema version 4.

genio-blocks

How genio can be useful to you

What has been useful to us is potentially useful to other developers as well. When we saw other groups in eBay Inc. show interest in genio, we plugged new templates to the genio parser to build API references, testing tools, API explorers and so on. And now, we are open sourcing it, hoping that the developer community can benefit as well and also contribute with enhancements.

Any project that implements or consumes APIs can use genio to generate service stubs, client stubs, testing tools etc. genio is being released as two ruby gems:

  • genio-parser that parses service specification files into a generic model and
  • genio that provides a set of templates and uses genio-parser to generate code.

The client templates shipped with genio in this release generate client stubs that can be plugged directly into our core SDKs. If you have a preferred service framework, you can write new templates that are specific to your framework. You can contribute new templates to genio or add support for new specification formats in genio-parser. We will be thrilled to accept those that target widely used open frameworks / API specification formats.

Look at the genio samples repository for example code generated using genio. Do look out for our next blog post that will tell you how genio can be extended to suit your needs.

Auth / Capture Payment Support Now Available in the New RESTful APIs

By and

Today I am very happy to announce the launch of auth / capture support in our new RESTful APIs! With this new support mechanism, you will be able to hold a portion of funds from a user account (auth) for a period of time before processing the payment and transferring the funds (capture).

An applicable use case for something like this would be if you have a business that loans out products. When the user receives the product the charge can put on the customer’s credit card, and only when they return it do you process the funds. Using this mechanism, you can ensure that the funds will be available when processing them. Of course, there are many other use cases for a system like this.

How long can you capture the funds for?

One of the first questions that you might have about this new API feature is, “How Long will I be able to hold money on a user’s account for?”. The short answer to that one is that an authorization will be guaranteed to be available for 3 days (guarantee that the funds will be locked on the funding source), but you will be able to attempt authorizations for a period of 29 days.

How do you use it with the new APIs?

To get things started, if you’ve never worked with the new RESTful APIs, I would suggest starting with a little bit of background on how they work (it’ll make this a lot easier). Here are some links for that:

Now that we have that covered, let’s get into a few specific differences in processing a payment versus making an authorization call. First off, when you are authorizing a payment you will be making a request to the same API endpoint as you would if you are making a payment:

https://api.sandbox.paypal.com/v1/payments/payment

The only other difference in payment versus auth is in the POST payload that you send through with the request. When you are making a payment, you would set the “intent” key in the POST body to “sale”, to indicate a payment. If you are processing an authorization payment, then you would instead set “intent” to “authorize”, like so:

"intent":"authorize"

After you make that request, you will receive a JSON response back from PayPal indicating the success or failure. There are a few key things about the response structure that are important to note for processing the payment and verifying its success: * id: This is the unique payment identifier that you can use to later look up information or process the payment. * state: On success, this will be set to approved, stating that the funds are locked. * links (under the transactions key): This will be a series of HATEOAS links to provide you with logical next steps in the auth/capture process. With that said, let’s take a quick look at those HATEOAS links that are returned to us:

"links":[
  {
    "href":"https://api.sandbox.paypal.com/v1/payments/authorization/9T287484DP554682S",
    "rel":"self",
    "method":"GET"
  },
  {
    "href":"https://api.sandbox.paypal.com/v1/payments/authorization/9T287484DP554682S/capture",
    "rel":"capture",
    "method":"POST"
  },
  {
    "href":"https://api.sandbox.paypal.com/v1/payments/authorization/9T287484DP554682S/void",
    "rel":"void",
    "method":"POST"
  },
  {
    "href":"https://api.sandbox.paypal.com/v1/payments/payment/PAY-0R831151JU007784NKGSU2SA",
    "rel":"parent_payment",
    "method":"GET"
  }
]

These links provide the next actions that you can take with the REST APIs, with information on how to make the request. Based on their “rel” tag, they include: * self: Look up information on the auth request * capture: This is the request to capture the payments (part 2 in the 2 step auth/capture process) * void: Void the payment * parent payment: Look up the payment resource itself With those links, you’ll have everything you’ll need to do to build proper auth/capture support. If you don’t want to work with the HATEOAS link structure, then you can set up the capture / payment lookup yourself using the same API endpoints and data that are available in those links. More information on all of that is available in the

official documentation for auth/capture support.

More Features Coming Soon! As we endeavor to create better RESTful APIs for our commerce developers, having feature parity between the

REST and classic APIs is a very important future step for us. With that in mind, you will see continuous releases that add in the support that our developers are asking for.