API Reference

Use the documentation on this site to learn how to implement Reloadly Services. Choose the solution that bests suits your needs from the Featured documentation or select All Docs to find a specific document.

REST APIs

Get Started

The Reloadly APIs are HTTP-base RESTful APIs that use OAuth 2.0 for authorization. API request and response bodies are formatted in jSON.

Important: You cannot run the sample requests in this guide as-is. Replace call-specific parameters such as tokens and IDs with your own values.

For definitions of common REST API terms, see the Glossary.

Authentication and authorization

The Reloadly REST API uses the OAuth 2.0 protocol to authorize calls. OAuth is an open standard that many companies use to provide secure access to protected resources.

When you create a developer account, Reloadly generates a set of OAuth client ID and secret credentials for your app for both the sandbox and live environments. You pass these credentials in the Authorization header in the Authorization header in the get access token request.

In exchange for these credentials, the Reloadly authorization server issues access tokens called bearer tokens that you use for authorization when you make REST API requests. A bearer token enables you to complete actions on behalf of, and with the approval of the resource owner.

The accessToken field in the get access token response contains a bearer token, indicated by the tokenType of Bearer :

                            {
    "accessToken": "<Access-Token>",
    "tokenType": "Bearer",
    "expiresIn": 32398
}
                        


Include this bearer token in API requests in the Authorization header with the Bearer authentication scheme.

Example :

                            
 curl -v -X GET https://portal.sandbox.reloadly.com/transactions?page=3&size=4 \
   -H "Content-Type: application/json" \
   -H "Accept: application/vnd.reloadly.app-v1+json" \
   -H "Authorization: Bearer <Access-Token>"
                            
                        

Access tokens have a finite lifetime. The expiresIn field in the get access token response indicates the lifetime, in seconds, of the access token. For example, an expiry value of 3600 (3600 seconds) indicates that the access token expires in one hour from the time the response was generated.

To detect when an access token expires, write code to either :

  • Keep track of the expiresIn value in the token response. The value is expressed in seconds.

  • Handle the HTTP 401 Unauthorized status code and errorCode of TOKEN_EXPIRED. The API endpoint issues this status code and error code when it detects an expired token.

Before you created another token, re-use the access token until it expires.

API Requests

To construct a REST API request, combine these components :

Component Description

The HTTP method

  • GET. Requests data from a resource.
  • POST. Submits data to a resource to process.
  • PUT. Updates a resource.
  • PATCH. Partially updates a resource.
  • DELETE. Deletes a resource.

The URL to the API service

  • Sandbox. https://api.sandbox.Reloadly.com
  • Live. https://api.Reloadly.com

The URI to the resource

The resource to query, submit data to, update, or delete. For example, v1/invoicing/invoices.

Query parameters

Optional. Controls which data appears in the response. Use to filter, limit the size of, and sort the data in an API response.

HTTP request headers

Includes the Authorization header with the access token.

A JSON request body

Required for most GET, POST, PUT, and PATCH calls.

This sample request retrieves topup transactions :

curl -v -X GET https://portal.sandbox.reloadly.com/reports/transactions?page=1&size=20 \
  -H "Accept: application/vnd.reloadly.app-v1+json" \
  -H "Authorization: Bearer Access-Token"

Query parameters

For most REST GET calls, you can specify one or more optional query parameters on the request URI to filter, limit the size of, and sort the data in an API response. For filter parameters, see the individual GET calls.

To limit, or page, and sort the data that is returned in some API responses, use these, or similar, query parameters:

Note: Not all pagination parameters are available for all APIs.

Parameter Type Description
size integer The number of items to list in the response.
page integer The one-relative start index of the entire list of items that are returned in the response. So, the combination of page=1 and size=20 returns the first 20 items. The combination of page=20 and size=20 returns the next 20 items.
size integer The number of items to return in the response.
totalPages integer Indicates the total number of pages available.
totalElements int Indicates the overall total resources that match the requested query.
numberOfElements integer Number of items on the current page.
sort object Sorting info. "sort":{ "sorted": false, "unsorted": true }

For example, the Invoicing API returns topup transaction details :

curl -v -X GET https://portal.sandbox.reloadly.com/reports/transactions?page=3&size=4 \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer Access-Token"

HTTP request headers

The commonly used HTTP request headers are:

Header Description
Accept

Required for operations with a response body.

Specifies the response format. The syntax is:

Accept: application/format

Where format is vnd.reloadly.app-v1+json. Note the API versioning

application/vnd.reloadly.app-v1+json
Authorization

Required to get an access token or make API calls.

To get an access token, set this header to your clientId and clientSecret credentials.

Note: If you use cURL, specify -u "clientId:clientSecret".

To make REST API calls, include the bearer token in the Authorization header with the Bearer authentication scheme:

Authorization: Bearer Access-Token
Content-Type

Required for operations with a request body.

Specifies the request format. The syntax is:

Content-Type: application/format

Where format is json.

API responses

Reloadly API calls return HTTP status codes. Some API calls also return JSON response bodies that include information about the resource including one or more contextual HATEOAS links. Use these links to request more information about and construct an API flow that is relative to a specific request.

HTTP status codes

Each REST API request returns a success or error HTTP status code.

Success

In the responses, Reloadly returns these HTTP status codes for successful requests:

Status code Description
200 OK The request succeeded.
201 Created A POST method successfully created a resource. If the resource was already created by a previous execution of the same method, for example, the server returns the HTTP 200 OK status code.
202 Accepted The server accepted the request and will execute it later.
204 No Content The server successfully executed the method but returns no response body.

Error

In the responses for failed requests, Reloadly returns HTTP 4XX or 5XX status codes.

For all errors except Identity errors, Reloadly returns an error response body that includes additional error details in this format:

{
  "timeStamp": 1524453335721,
  "status": HTTP_STATUS_CODE,
  "message": "ERROR_DESCRIPTION",
  "path": "END_POINT_CALLED",
  "errorCode": "ERROR_CODE_GIVING_MORE_INSIGHT_AS_TO_WHAT_THE_PROBLEM_IS"
}

In the responses, Reloadly returns these HTTP status codes for failed requests:

HTTP status code Typical error code and error message Cause
400 Bad Request INVALID_REQUEST. Request is not well-formed, syntactically incorrect, or violates schema. See Validation errors. The server could not understand the request. Indicates one of these conditions:
  • The API cannot convert the payload data to the underlying data type.
  • The data is not in the expected data format.
  • A required field is not available.
  • A simple data validation error occurred.
401 Unauthorized AUTHENTICATION_FAILURE. Authentication failed due to invalid authentication credentials. See Authentication errors. The request requires authentication and the caller did not provide valid credentials.
403 Forbidden NOT_AUTHORIZED. Authorization failed due to insufficient permissions. The client is not authorized to access this resource although it might have valid credentials. For example, the client does not have the correct OAuth 2 scope. Additionally, a business-level authorization error might have occurred. For example, the account holder does not have sufficient funds.
404 Not Found RESOURCE_NOT_FOUND. The specified resource does not exist. The server did not find anything that matches the request URI. Either the URI is incorrect or the resource is not available. For example, no data exists in the database at that key.
405 Method Not Allowed METHOD_NOT_SUPPORTED. The server does not implement the requested HTTP method. The service does not support the requested HTTP method. For example, PATCH.
406 Not Acceptable MEDIA_TYPE_NOT_ACCEPTABLE. The server does not implement the media type that would be acceptable to the client. The server cannot use the client-request media type to return the response payload. For example, this error occurs if the client sends an Accept: application/xml request header but the API can generate only an application/json response.
415 Unsupported Media Type UNSUPPORTED_MEDIA_TYPE. The server does not support the request payload’s media type. The API cannot process the media type of the request payload. For example, this error occurs if the client sends a Content-Type: application/xml request header but the API can only accept application/json request payloads.
422 Unprocessable Entity UNPROCCESSABLE_ENTITY. The API cannot complete the requested action, or the request action is semantically incorrect or fails business validation. The API cannot complete the requested action and might require interaction with APIs or processes outside of the current request. No systemic problems limit the API from completing the request. For example, this error occurs for any business validation errors, including errors that are not usually of the 400 type.
429 Unprocessable Entity RATE_LIMIT_REACHED. Too many requests. Blocked due to rate limiting. The rate limit for the user, application, or token exceeds a predefined value. See RFC 6585.
500 Internal Server Error INTERNAL_SERVER_ERROR. An internal server error has occurred. A system or application error occurred. Although the client appears to provide a correct request, something unexpected occurred on the server.
503 Service Unavailable SERVICE_UNAVAILABLE. Service Unavailable. The server cannot handle the request for a service due to temporary maintenance.

Validation errors

For validation errors, Reloadly returns the HTTP 400 Bad Request status code.

To prevent validation errors, ensure that parameters are of the right type and conform to these constraints:

Parameter type Description
Character Names, addresses, phone numbers, and so on have maximum character limits.
Numeric Credit cards, amounts, card verification value (CVV), and so on must use non-negative numeric values and have required formats. For example, a CVV must be three or four numbers while a credit card number must contain only numbers.
Required Must be included in the request. For example, when you provide credit card information, you must include a postal code for most countries.
Monetary Must use the right currency.

For information about parameter types and constraints, see the REST API reference.

Authentication errors

For authentication errors, Reloadly returns the HTTP 401 Unauthorized status code. See authentication and authorization.

Access token-related issues often cause authentication errors.

Ensure that the access token is valid and present and not expired.

Make your first call

To make REST API calls, create a Reloadly Developer Account and use your clientId and clientSecret to get an access token for the the API you want to call :

1. Create a Reloadly Developer Account.
When you create a developer account, Reloadly generates a set of OAuth credentials.
2. Get an access token.
Pass the OAuth credentials in a get access token call.
In response, the Reloadly authorization server issues an access token.
3. Make REST API calls.
Use the access token for authentication when you make REST API calls.

Create a Reloadly Developer Account

See creating a developer account

Get an access token

The get access token for the topups service, the endpoint is /topups/oauth2/token.

To get an access token, you pass your OAuth credentials in a get access token call. To make this call, you can use either cURL on the command line or the Postman app.

In response, the Reloadly authorization server issues an access token.

Re-use the access token until it expires.

cURL example

Tips:

  • If you use Windows, use a Bash shell to make cURL calls.
  • If you use a command-line tool other than cURL, set content-type to application/x-www-form-urlencoded.
  1. Download cURL for your environment.

  2. From the command line, run this command:

    curl -v https://portal.sandbox.reloadly.com/topups/oauth2/token \
       -H "Accept: application/vnd.reloadly.app-v1+json" \
       -u "clientId:clientSecret"
       

    Where:

    /topups/oauth2/token The get topups service access token endpoint.
    clientId Your client ID.
    clientSecret Your client secret.
  3. View the sample response.

Postman example

  1. Download the latest version of Postman for your environment, and open Postman.

  2. Select the POST method.

  3. Enter the https://portal.sandbox.reloadly.com/topups/oauth2/token request URL.

  4. On the Headers add a Accept type and enter this accept header: application/vnd.reloadly.app-v1+json (Use the appropriate version accordingly)

  5. On the Body tab, select raw and from the Text drop down select JSON(application/json) then enter this information:

    clientId <Your-Client-Id>
    clientSecret <Your-Client-Secret>
  6. Click Send.

  7. View the sample response.

Sample response

{
  "accessToken": "Access-Token",
  "tokenType": "Bearer",
  "expires_in": 32398
}

Where:

accessToken Your access token.
expiresIn The number of seconds after which the token expires. Request another token when the current one expires.

Make REST API calls

With a valid access token, you can make REST API calls.

This sample call creates a Reloadly topups service and uses only the required input parameters. The access token in the call is an OAuth bearer token.

Note: Reloadly services API calls are always made by an actor, on behalf of a subject. The actor specifies a bearer token in the Authorization: Bearer request header. A bearer token is an access token that is issued to the actor by an authorization server with the approval of the resource owner. In this case, the actor uses the bearer token to make a topup transaction request on behalf of the subject.

curl -v https://topups.sandbox.reloadly.com/topups \
  -H "Content-Type: application/json" \
  -H "Accept: application/vnd.reloadly.app-v1+json" \
  -H "Authorization: Bearer Access-Token" \
  -d '{
  "recipientPhone": {
    "countryCode": "CO",
    "number": "222222222222"
  },
  "senderPhone": {
    "countryCode": "US",
    "number": "5555555555"
  },
  "operatorId": 182,
  "amount": 182,
  "userId": 25,
  "customIdentifier": "email@example.com"
}'

A successful call returns a JSON-formatted response body with transaction details.

Additional information

Authentication and authorization
HTTP request headers
HATEOAS links
Internet date and time format

Authentication and authorization

The Reloadly REST API uses the OAuth 2.0 protocol to authorize calls. OAuth is an open standard that many companies use to provide secure access to protected resources.

When you create a developer account, Reloadly generates a set of OAuth client ID and secret credentials for your app for both the sandbox and live environments. You pass these credentials in the Authorization header in the Authorization header in the get access token request.

In exchange for these credentials, the Reloadly authorization server issues access tokens called bearer tokens that you use for authorization when you make REST API requests. A bearer token enables you to complete actions on behalf of, and with the approval of the resource owner.

The accessToken field in the get access token response contains a bearer token, indicated by the tokenType of Bearer :

                            {
    "accessToken": "<Access-Token>",
    "tokenType": "Bearer",
    "expiresIn": 32398
}
                        


Include this bearer token in API requests in the Authorization header with the Bearer authentication scheme.

Example :

                            
 curl -v -X GET https://portal.sandbox.reloadly.com/transactions?page=3&size=4 \
   -H "Content-Type: application/json" \
   -H "Accept: application/vnd.reloadly.app-v1+json" \
   -H "Authorization: Bearer <Access-Token>"
                            
                        

Access tokens have a finite lifetime. The expiresIn field in the get access token response indicates the lifetime, in seconds, of the access token. For example, an expiry value of 3600 (3600 seconds) indicates that the access token expires in one hour from the time the response was generated.

To detect when an access token expires, write code to either :

  • Keep track of the expiresIn value in the token response. The value is expressed in seconds.

  • Handle the HTTP 401 Unauthorized status code and errorCode of TOKEN_EXPIRED. The API endpoint issues this status code and error code when it detects an expired token.

Before you created another token, re-use the access token until it expires.

Error

In the responses for failed requests, Reloadly returns HTTP 4XX or 5XX status codes.

For all errors except Identity errors, Reloadly returns an error response body that includes additional error details in this format:

{
  "timeStamp": 1524453335721,
  "status": HTTP_STATUS_CODE,
  "message": "ERROR_DESCRIPTION",
  "path": "END_POINT_CALLED",
  "errorCode": "ERROR_CODE_GIVING_MORE_INSIGHT_AS_TO_WHAT_THE_PROBLEM_IS"
}

In the responses, Reloadly returns these HTTP status codes for failed requests:

HTTP status code Typical error code and error message Cause
400 Bad Request INVALID_REQUEST. Request is not well-formed, syntactically incorrect, or violates schema. See Validation errors. The server could not understand the request. Indicates one of these conditions:
  • The API cannot convert the payload data to the underlying data type.
  • The data is not in the expected data format.
  • A required field is not available.
  • A simple data validation error occurred.
401 Unauthorized AUTHENTICATION_FAILURE. Authentication failed due to invalid authentication credentials. See Authentication errors. The request requires authentication and the caller did not provide valid credentials.
403 Forbidden NOT_AUTHORIZED. Authorization failed due to insufficient permissions. The client is not authorized to access this resource although it might have valid credentials. For example, the client does not have the correct OAuth 2 scope. Additionally, a business-level authorization error might have occurred. For example, the account holder does not have sufficient funds.
404 Not Found RESOURCE_NOT_FOUND. The specified resource does not exist. The server did not find anything that matches the request URI. Either the URI is incorrect or the resource is not available. For example, no data exists in the database at that key.
405 Method Not Allowed METHOD_NOT_SUPPORTED. The server does not implement the requested HTTP method. The service does not support the requested HTTP method. For example, PATCH.
406 Not Acceptable MEDIA_TYPE_NOT_ACCEPTABLE. The server does not implement the media type that would be acceptable to the client. The server cannot use the client-request media type to return the response payload. For example, this error occurs if the client sends an Accept: application/xml request header but the API can generate only an application/json response.
415 Unsupported Media Type UNSUPPORTED_MEDIA_TYPE. The server does not support the request payload’s media type. The API cannot process the media type of the request payload. For example, this error occurs if the client sends a Content-Type: application/xml request header but the API can only accept application/json request payloads.
422 Unprocessable Entity UNPROCCESSABLE_ENTITY. The API cannot complete the requested action, or the request action is semantically incorrect or fails business validation. The API cannot complete the requested action and might require interaction with APIs or processes outside of the current request. No systemic problems limit the API from completing the request. For example, this error occurs for any business validation errors, including errors that are not usually of the 400 type.
429 Unprocessable Entity RATE_LIMIT_REACHED. Too many requests. Blocked due to rate limiting. The rate limit for the user, application, or token exceeds a predefined value. See RFC 6585.
500 Internal Server Error INTERNAL_SERVER_ERROR. An internal server error has occurred. A system or application error occurred. Although the client appears to provide a correct request, something unexpected occurred on the server.
503 Service Unavailable SERVICE_UNAVAILABLE. Service Unavailable. The server cannot handle the request for a service due to temporary maintenance.

Validation errors

For validation errors, Reloadly returns the HTTP 400 Bad Request status code.

To prevent validation errors, ensure that parameters are of the right type and conform to these constraints:

Parameter type Description
Character Names, addresses, phone numbers, and so on have maximum character limits.
Numeric Credit cards, amounts, card verification value (CVV), and so on must use non-negative numeric values and have required formats. For example, a CVV must be three or four numbers while a credit card number must contain only numbers.
Required Must be included in the request. For example, when you provide credit card information, you must include a postal code for most countries.
Monetary Must use the right currency.

For information about parameter types and constraints, see the REST API reference.

Authentication errors

For authentication errors, Reloadly returns the HTTP 401 Unauthorized status code. See authentication and authorization.

Access token-related issues often cause authentication errors.

Ensure that the access token is valid and present and not expired.

TOPUPs Service API

Use the Topups Service API to send airtime around the world in seconds.

Send Topups

Reloadly topup service API allow instant airtime to be sent to mobile phones around the world.


curl -X POST --header "Content-Type: application/json" --header "Accept: application/vnd.reloadly.app-v1+json" --header "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ik0wWXpRalF5UTBGRFJEUkVOVGc0UlVJME56ZEdNVVEzTlRsRVEwVTBOekU1TURJeU16QkJRdyJ9.eyJodHRwczovL3RvcHVwcy1kZXYucmVsb2FkbHkuY29tL2p0aSI6IjZjNGVmYzkzLWNkNTQtNGYwZC1iZDRiLTcwZWY5MDdkNzFhOCIsImh0dHBzOi8vdG9wdXBzLWRldi5yZWxvYWRseS5jb20vdXNlcklkIjoiMUh4SVlxcnBSNUNFbzIzc1ZjWDE4dz09IiwiaHR0cHM6Ly90b3B1cHMtZGV2LnJlbG9hZGx5LmNvbS9waG9uZSI6IklpOW9tS2VkN1R3d2I3bDVoUUpnZ0E9PSIsImh0dHBzOi8vdG9wdXBzLWRldi5yZWxvYWRseS5jb20vY291bnRyeUNvZGUiOiJGMFRBZHJYU1QxYnFFckNOL1BoeHhRPT0iLCJpc3MiOiJodHRwczovL3JlbG9hZGx5LWRldi5hdXRoMC5jb20vIiwic3ViIjoiOGpPSDQwOHloNXpOY1poM1ZGekVzYnJCZTRXT3VzaktAY2xpZW50cyIsImF1ZCI6Imh0dHBzOi8vdG9wdXBzLWRldi5yZWxvYWRseS5jb20iLCJpYXQiOjE1MjQ0NTA2MDgsImV4cCI6MTUyOTYzNDYwOCwiYXpwIjoiOGpPSDQwOHloNXpOY1poM1ZGekVzYnJCZTRXT3VzaksiLCJzY29wZSI6InNlbmQtdG9wdXBzIHJlYWQtdG9wdXBzLWhpc3RvcnkgcmVhZC1vcGVyYXRvcnMgcmVhZC1wcm9tb3Rpb25zIiwiZ3R5IjoiY2xpZW50LWNyZWRlbnRpYWxzIn0.LE1qKxSd2ue02mB7CHgAhvF-2Smt0trt3_pGFZiGlsv4EIKYr_Vg_Nn8S2Olq-y1wPky9SMEG7UwHNzOz82htOrCSfauyjdBXnR93JGoUSKujAvaPUSY8LnHIFhzA3N5hiHjgxoi_oIl3SGaYJ55cfoZj_5RZbc2W37wvN2ZE6DDBEHibPOIzQj-ofXMVafw-qAqGU71y9UTKatmWA8CzwrtrMOc4qMcfv3fEubox3KpbTmCmOc_fUWoJdVCkOMxaHdxKQmz8tizXjGKqmSblnQ1C_aYm21riJR3Db0_Gwp8r_XE0a7o9cE0I9HoIoac10S8-2abeyUeEloTdrBD3Q" -d "{
  \"recipientPhone\": {
    \"countryCode\": \"HT\",
    \"number\": \"50936377111\"
  },
  \"senderPhone\": {
    \"countryCode\": \"US\",
    \"number\": \"5555555555\"
  },
  \"operatorId\": 173,
  \"amount\": 25,
  \"userId\": 4,
  \"customIdentifier\": \"transaction by john@example.com\"
}"
                            
begin
                            # Use example's library to make requests...
                            rescue example::CardError => e
                            # Since it's a decline, example::CardError will be caught
                            body = e.json_body
                            err  = body[:error]

                            puts "Status is: #{e.http_status}"
                            puts "Type is: #{err[:type]}"
                            puts "Charge ID is: #{err[:charge]}"
                            # The following fields are optional
                            puts "Code is: #{err[:code]}" if err[:code]
                            puts "Decline code is: #{err[:decline_code]}" if err[:decline_code]
                            puts "Param is: #{err[:param]}" if err[:param]
                            puts "Message is: #{err[:message]}" if err[:message]
                            rescue example::RateLimitError => e
                            # Too many requests made to the API too quickly
                            rescue example::InvalidRequestError => e
                            # Invalid parameters were supplied to example's API
                            rescue example::AuthenticationError => e
                            # Authentication with example's API failed
                            # (maybe you changed API keys recently)
                            rescue example::APIConnectionError => e
                            # Network communication with example failed
                            rescue example::exampleError => e
                            # Display a very generic error to the user, and maybe send
                            # yourself an email
                            rescue => e
                            # Something else happened, completely unrelated to example
                            end
try:
                            # Use example's library to make requests...
                            pass
                            except example.error.CardError as e:
                            # Since it's a decline, example.error.CardError will be caught
                            body = e.json_body
                            err  = body['error']

                            print "Status is: %s" % e.http_status
                            print "Type is: %s" % err['type']
                            print "Code is: %s" % err['code']
                            # param is '' in this case
                            print "Param is: %s" % err['param']
                            print "Message is: %s" % err['message']
                            except example.error.RateLimitError as e:
                            # Too many requests made to the API too quickly
                            pass
                            except example.error.InvalidRequestError as e:
                            # Invalid parameters were supplied to example's API
                            pass
                            except example.error.AuthenticationError as e:
                            # Authentication with example's API failed
                            # (maybe you changed API keys recently)
                            pass
                            except example.error.APIConnectionError as e:
                            # Network communication with example failed
                            pass
                            except example.error.exampleError as e:
                            # Display a very generic error to the user, and maybe send
                            # yourself an email
                            pass
                            except Exception as e:
                            # Something else happened, completely unrelated to example
                            pass
try {
                            // Use example's library to make requests...
                            } catch(\example\Error\Card $e) {
                            // Since it's a decline, \example\Error\Card will be caught
                            $body = $e->getJsonBody();
                            $err  = $body['error'];

                            print('Status is:' . $e->getHttpStatus() . "\n");
                            print('Type is:' . $err['type'] . "\n");
                            print('Code is:' . $err['code'] . "\n");
                            // param is '' in this case
                            print('Param is:' . $err['param'] . "\n");
                            print('Message is:' . $err['message'] . "\n");
                            } catch (\example\Error\RateLimit $e) {
                            // Too many requests made to the API too quickly
                            } catch (\example\Error\InvalidRequest $e) {
                            // Invalid parameters were supplied to example's API
                            } catch (\example\Error\Authentication $e) {
                            // Authentication with example's API failed
                            // (maybe you changed API keys recently)
                            } catch (\example\Error\ApiConnection $e) {
                            // Network communication with example failed
                            } catch (\example\Error\Base $e) {
                            // Display a very generic error to the user, and maybe send
                            // yourself an email
                            } catch (Exception $e) {
                            // Something else happened, completely unrelated to example
                            }
try {
                            // Use example's library to make requests...
                            } catch (CardException e) {
                            // Since it's a decline, CardException will be caught
                            System.out.println("Status is: " + e.getCode());
                            System.out.println("Message is: " + e.getMessage());
                            } catch (RateLimitException e) {
                            // Too many requests made to the API too quickly
                            } catch (InvalidRequestException e) {
                            // Invalid parameters were supplied to example's API
                            } catch (AuthenticationException e) {
                            // Authentication with example's API failed
                            // (maybe you changed API keys recently)
                            } catch (APIConnectionException e) {
                            // Network communication with example failed
                            } catch (exampleException e) {
                            // Display a very generic error to the user, and maybe send
                            // yourself an email
                            } catch (Exception e) {
                            // Something else happened, completely unrelated to example
                            }
// Note: Node.js API does not throw exceptions, and instead prefers the
                                // asynchronous style of error handling described below.
                                //
                                // An error from the example API or an otheriwse asynchronous error
                                // will be available as the first argument of any example method's callback:
                                // E.g. example.customers.create({...}, function(err, result) {});
                                //
                                // Or in the form of a rejected promise.
                                // E.g. example.customers.create({...}).then(
                                //        function(result) {},
                                //        function(err) {}
                                //      );

                                switch (err.type) {
                                case 'exampleCardError':
                                // A declined card error
                                err.message; // => e.g. "Your card's expiration year is invalid."
                                break;
                                case 'RateLimitError':
                                // Too many requests made to the API too quickly
                                break;
                                case 'exampleInvalidRequestError':
                                // Invalid parameters were supplied to example's API
                                break;
                                case 'exampleAPIError':
                                // An error occurred internally with example's API
                                break;
                                case 'exampleConnectionError':
                                // Some kind of error occurred during the HTTPS communication
                                break;
                                case 'exampleAuthenticationError':
                                // You probably used an incorrect API key
                                break;
                                default:
                                // Handle any other types of unexpected errors
                                break;
                                }
                            
_, err := // Go library call

                            if err != nil {
                            // Try to safely cast a generic error to a example.Error so that we can get at
                            // some additional example-specific information about what went wrong.
                            if exampleErr, ok := err.(*example.Error); ok {
                            // The Code field will contain a basic identifier for the failure.
                            switch exampleErr.Code {
                            case example.IncorrectNum:
                            case example.InvalidNum:
                            case example.InvalidExpM:
                            case example.InvalidExpY:
                            case example.InvalidCvc:
                            case example.ExpiredCard:
                            case example.IncorrectCvc:
                            case example.IncorrectZip:
                            case example.CardDeclined:
                            case example.Missing:
                            case example.ProcessingErr:
                            }

                            // The Err field can be coerced to a more specific error type with a type
                            // assertion. This technique can be used to get more specialized
                            // information for certain errors.
                            if cardErr, ok := exampleErr.Err.(*example.CardError); ok {
                            fmt.Printf("Card was declined with code: %v\n", cardErr.DeclineCode)
                            } else {
                            fmt.Printf("Other example error occurred: %v\n", exampleErr.Error())
                            }
                            } else {
                            fmt.Printf("Other error occurred: %v\n", err.Error())
                            }
                            }