5.5. REST interface (BETA)

5.5.1. Introduction

Note

REST interface is a beta feature. If you have questions about it, please contact .

Note

REST interface does not support payment page bypass.

Paytrail payment REST interface can be used to create a payment with a server-to-server request and thus limits usage less than the form interface. With the REST interface, the payment is created in advance by sending payment data as an XML or JSON message over HTTPS. Service returns the response message in the corresponding format.

We provide a PHP class that implements this interface. The interface is described more closely in the following chapters.

When using the form interface the payment data is sent from a customer's browser to Paytrail service, but when using the REST interface customer's server sends the payment data to Paytrail service in XML or JSON format. The response message is returned in the same format.

When using the REST interface, the data that is sent to the payment service must always be UTF-8 encoded.

Figure 5.3. Payment creation with the REST interface

Payment creation with the REST interface

5.5.2. Interface use

When using the REST service, always include the following headers:

Content-Type
Sent message type. The message can be sent either in XML or JSON format. Corresponding types are application/xml and application/json.
X-Verkkomaksut-Api-Version
Interface version. The current REST interface version is "1".

Each request sent to the interface must be verified with Basic authentication (Authorization header). Basic authentication sends the Merchant ID as a username and the Merchant secret as a password.

5.5.3. Payment creation

Paytrail payment service REST interface allows for creating a payment in advance with a simple HTTP POST request, which sends the payment data as an XML or JSON message. The request returns an order number, payment ID (token) and URL-address for making a payment. In a typical case, a webshop creates a payment with the REST interface at the end of an order process, and redirects the customer to the returned URL.

Service address: https://payment.paytrail.com/api-payment/create

The root name of the sent XML message is payment. The parameters for creating a payment are as follows:

orderNumber
(all characters[64], required) Order number. Order number is a string of characters identifying the customer's purchase.
referenceNumber
(number[22], optional) Reference number to be sent to payment method provider's service. Given value is used only if user selected payment method is configured as interface (i.e. own direct agreement with payment method provider), otherwise the reference number is generated automatically by Paytrail.
description
(all characters[65 000], optional) Any data about the order in text format can be sent to the payment system. The most usual pieces of data are customer name and contact information and order product information. They are shown in the Merchant's Panel in payment details.
currency
(upper case[3], required) Payment currency. Value must be EUR for Finnish banks, otherwise the payment will not be accepted.
locale
(all characters[5], optional) Localisation defines default language for the payment method selection page and presentation format for the sums. Available localisations are "fi_FI" , "sv_SE" and "en_US". The default localisation is “fi_FI”.
urlSet
(required)
success
(all characters[2048], required) User is redirected to this URL after a successful payment to Paytrail.
failure
(all characters[2048], required) User is redirected to this URL after a cancelled or failed payment.
notification
(all characters[2048], required) Paytrail makes a request to this URL when the payment is marked as successful. The address is requested with the same GET parameters as the success address was when the payment was made. Notification request is typically executed within a few minutes from the payment.
orderDetails
(optional) Either orderDetails or payment sum price has to be specified. orderDetails record contains payer details and detailed order rows. We recommend using the orderDetails record whenever it is possible. If the orderDetails record is not supplied, invoice and instalment payment methods are not available and payer and order row details are not available in the Merchant's Panel. Payment method fees can only be used when the orderDetails record is used. Without orderDetails record the order details cannot be shown on the payment method selection page.
includeVat
(0/1, required) VAT included -field shows if the product row prices include value added tax. Value 1 means that VAT is included in the shown price, and 0 that it will be added. Therefore, use 1, if the prices in your webshop include value added tax and 0 if the prices do not include value added tax. If Collector payment method is used, then the value should be 1, or the payment method is hidden from the payment method selection page.
contact
(required)
firstName
(all characters [64], required) Customer's first name.
lastName
(all characters [64], required) Customer's surname.
companyName
(all characters[128], optional) Company name.
email
(all characters[255], required) Customer's email address.
telephone
(all characters[64], optional) Customer's telephone number.
mobile
(all characters[64], optional) Customer's mobile number.
address
(required)
street
(all characters [64], required) Customer's street address.
postalCode
(all characters[16], required) Customer's postal code.
postalOffice
(all characters[64], required) Customer's post office.
country
(capital letters[2], required) Customer's country. The data is sent in ISO-3166-1 format. For example, Finnish is FI and Swedish is SE. The data is used to verify credit history, and is thus required.
products
(required)
product (recurring element [1,500])
title
(all characters[255], required) Product name in free format. The product title is shown in the Merchant's Panel and on Klarna service invoices on a product row. Product details are shown also on the payment method selection page.
code
(all characters[16], optional) Optional product number.
amount
(decimal number[10], required) If an order has several same products, you can enter the number of products here instead of having separate rows for each. Usually this field contains the value 1. If Collector payment method is used, the value should be an integer. If a decimal such as 0.5 is used, Collector payment method is hidden from the payment method selection page.
price
(decimal number[10], required) Price for one product. If the field payment.orderDetails.includeVat = 0, the price excludes VAT. If the value is 1, the price includes VAT. The price can also be negative if you want to add discounts to the service. However, the total amount of the product rows must always be at least 0.65.
vat
(decimal number[10], required) Tax percentage for a product.
discount
(decimal number[10], optional) If you have reduced the product price, you can show the discount percentage as a figure between 0 and 100 in this field. Default is 0.
type
(integer[1], optional) A type can be specified for the product row. 1: normal product row, 2: shipping, 3: handling. 1 can be used for all rows, but shipping and handling costs cannot be differentiated from the other rows. Default is 1.
price
(decimal number[10], optional) Payment total. Send either exact payment data (orderDetails) or the payment total to the service. If you send only the payment total price, (Klarna and Collector) invoice and instalment payment methods are not available and order details cannot be shown in the Merchant's Panel. We recommend using orderDetails record whenever it is possible. The value of price must be >= 0.65.

The service responds to request in the same format (XML or JSON) as it was received. Return record root element is also called payment and it contains the following records:

orderNumber
(all characters[64]) The order number sent on the request is returned as such.
token
(lower and upper case and numbers[64]) Token is 64 characters long, specifying identifier for the payment, which is valid for 14 days or until the payment has been made. Token is needed as such with the payment method selection page embedding.
url
(all characters) Address to which the customer is directed for making the payment. The URL also includes the token, which is used as a payment identifier.

Note

The example XML and JSON messages have been wrapped and indented to make the message more readable. Messages returned by the interface do not contain such formatting.

Example 5.3. Payment creation with the REST interface; XML request

<?xml version="1.0" encoding="UTF-8"?>
<payment>
  <orderNumber>12345678</orderNumber>
  <currency>EUR</currency>
  <locale>fi_FI</locale>
  <urlSet>
    <success>https://www.esimerkkikauppa.fi/sv/success</success>
    <failure>https://www.esimerkkikauppa.fi/sv/failure</failure>
    <pending></pending>
    <notification>https://www.esimerkkikauppa.fi/sv/notify</notification>
  </urlSet>
  <orderDetails>
    <includeVat>1</includeVat>
    <contact>
      <telephone>041234567</telephone>
      <mobile>041234567</mobile>
      <email>tester@esimerkkikauppa.fi</email>
      <firstName>Simon</firstName>
      <lastName>Seller</lastName>
      <companyName></companyName>
      <address>
        <street>Test street 1</street>
        <postalCode>12340</postalCode>
        <postalOffice>Helsinki</postalOffice>
        <country>FI</country>
      </address>
    </contact>
    <products>
      <product>
        <title>Example product</title>
        <code>XX-123</code>
        <amount>1.00</amount>
        <price>99.00</price>
        <vat>23.00</vat>
        <discount>0.00</discount>
        <type>1</type>
      </product>
      <product>
        <title>Example product 2</title>
        <code>XX-456</code>
        <amount>2.50</amount>
        <price>19.90</price>
        <vat>23.00</vat>
        <discount>0.00</discount>
        <type>1</type>
      </product>
    </products>
  </orderDetails>
</payment>
          

Example 5.4. Payment creation with the REST interface; XML response

<?xml version="1.0" encoding="UTF-8"?>
<payment>
  <orderNumber>12345678</orderNumber>
  <token>[SECRET TOKEN STRING GENERATED BY API]</token>
  <url>https://payment.paytrail.com/payment/load/token/[SECRET TOKEN STRING GENERATED BY API]</url>
</payment>
          

Example 5.5. Payment creation with the REST interface; JSON request

{
  "orderNumber": "12345678",
  "currency": "EUR",
  "locale": "fi_FI",
  "urlSet": {
    "success": "https://www.esimerkkikauppa.fi/sv/success",
    "failure": "https://www.esimerkkikauppa.fi/sv/failure",
    "pending": "",
    "notification": "https://www.esimerkkikauppa.fi/sv/success"
  },
  "orderDetails": {
    "includeVat": "1",
    "contact": {
      "telephone": "041234567",
      "mobile": "041234567",
      "email": "tester@esimerkkikauppa.fi",
      "firstName": "Simon",
      "lastName": "Seller",
      "companyName": "",
      "address": {
        "street": "Test street 1",
        "postalCode": "12340",
        "postalOffice": "Helsinki",
        "country": "FI"
      }
    },
    "products": [
      {
        "title": "Example product",
        "code": "XX-123",
        "amount": "1.00",
        "price": "99.00",
        "vat": "23.00",
        "discount": "0.00",
        "type": "1"
      },
      {
        "title": "Example product 2",
        "code": "XX-456",
        "amount": "2.50",
        "price": "19.90",
        "vat": "23.00",
        "discount": "0.00",
        "type": "1"
      }
    ]
  }
}
          

Example 5.6. Payment creation with the REST interface; JSON response

{
  "orderNumber": "12345678",
  "token": "[SECRET TOKEN STRING GENERATED BY API]",
  "url": "https://payment.paytrail.com/payment/load/token/[SECRET TOKEN STRING GENRATED BY API]"
}
          

Example 5.7. Payment creation with the REST interface; XML request, light version

Note

This example describes the interface usage without orderDetails. Please note that the orderDetails record is recommended whenever it is possible. Without the orderDetails record, payment subscriber details and specified product rows cannot be shown in the Merchant's Panel and invoice and instalment payment methods are not supported. In addition, payment method fees are available only when using the orderDetails record.
<?xml version="1.0" encoding="UTF-8"?>
<payment>
  <orderNumber>12345678</orderNumber>
  <currency>EUR</currency>
  <locale>fi_FI</locale>
  <urlSet>
    <success>https://www.esimerkkikauppa.fi/sv/success</success>
    <failure>https://www.esimerkkikauppa.fi/sv/failure</failure>
    <pending></pending>
    <notification>https://www.esimerkkikauppa.fi/sv/notify</notification>
  </urlSet>
  <price>99.00</price>
</payment>
          

5.5.4. Error handling

If the sent request is incorrect or there is an error in interface usage, the interface returns an error message. The error message is in XML or JSON format depending on the request data type (Content-Type header). If the data type is incorrect or it was not read, the error message is returned in XML format. Return message for an incorrect request is returned with HTTP error code 400.

Error message XML root element is called error. Error message returns the following records:

errorCode
(character string) Error code. Error code is an unambiguous character string that describes the error. Possible error codes are listed in table error codes.
errorMessage
(character string) Error description. Error description is a description of the error in chosen localisation. The error description is not to be shown to customers using the service.

Example 5.8. REST service error message in XML format

<?xml version="1.0" encoding="UTF-8"?>
<error>
  <errorCode>invalid-order-number</errorCode>
  <errorMessage>Missing or invalid order number</errorMessage>
</error>
          

Example 5.9. REST service error message in JSON format

{
  errorCode: 'invalid-order-number',
  errorMessage: 'Missing or invalid order number'
}
          

5.5.5. Error codes

Table 5.11. Error codes: Payment creation

Error codeDescription
invalid-content-typeIn HTTP POST request the Content-Type header contains an incorrect type. Allowed types are application/xml and application/json.
invalid-data-xmlError in processing received XML data or XML invalid.
invalid-data-jsonError in processing received JSON data or JSON invalid.
invalid-order-numberOrder number (orderNumber) missing or incorrect.
invalid-reference-numberSent reference number (referenceNumber) incorrect. Reference number must conform to the reference number standard.
invalid-reference-number-usedSent reference number (referenceNumber) incorrect. The reference number has been used for another payment.
invalid-descriptionOrder description (description) incorrect.
invalid-url-setRequired data structure urlSet not specified or incorrect.
invalid-url-successRequired return address for successful payment (success) in data structure urlSet missing or incorrect.
invalid-url-failureRequired return address for failed payment (failure) in data structure urlSet missing or incorrect.
invalid-url-pendingReturn address for pending payment (pending) in data structure urlSet incorrect.
invalid-url-notificationNotify address (notification) in data structure urlSet missing or incorrect.
invalid-currencyCurrency not specified or incorrect. Only "EUR" is supported.
invalid-localeLocalisation incorrect. Allowed options are "fi_FI", "en_US" and "sv_SE".
missing-order-details-and-priceOrder details (orderDetails) or payment sum (price) must be specified. Your request did not contain either of them.
order-details-and-price-definedOnly one of the required records, either order details (orderDetails) or payment sum (price) needs to be specified. Your request includes both records.
invalid-vat-modeIncluding Value Added Tax (includeVat) not specified or incorrect.
invalid-contactOrder details did not contain contact information (contact) or record was incorrect.
invalid-contact-telephoneIncorrect contact person's telephone number (telephone).
invalid-contact-mobileIncorrect contact person's mobile phone number (mobile).
invalid-contact-first-nameIncorrect or missing contact person's first name (firstName).
invalid-contact-last-nameIncorrect or missing contact person's surname (firstName).
invalid-contact-company-nameIncorrect contact person's company name (companyName).
invalid-contact-emailIncorrect or missing contact person's email address (email).
invalid-contact-addressIncorrect or missing contact person's address record (address).
invalid-contact-addressIncorrect or missing contact person's address record street address (street).
invalid-contact-postal-codeIncorrect or missing contact person's address record postal code (postalCode).
invalid-contact-postal-officeIncorrect or missing contact person's address record post office (postalOffice).
invalid-contact-countryIncorrect or missing contact person's address record country (country).
invalid-productsIncorrect or missing product record (products).
invalid-products-amountIncorrect number of product records in products record (products). There must be at least 1 product and at most 500 products.
invalid-product-titleIncorrect or missing product name (title) in product record.
invalid-product-codeIncorrect product code (code) in product record.
invalid-product-amountIncorrect or missing number of products (amount) in product record.
invalid-product-priceIncorrect or missing product price (price) in product record.
invalid-product-vatIncorrect or missing Value Added Tax (vat) in product record.
invalid-product-discountIncorrect discount percentage (discount) in product record.
invalid-product-typeIncorrect product type (type) in product record.
invalid-priceIncorrect payment sum (price).
invalid-total-priceProduct row total too low or too high.

5.5.6. PHP

When the payment service is integrated to an application developed in PHP, the easiest way to implement the payment service is to use our module, which connects to Paytrail payment service JSON interface.

Downloadable files:

Example 5.10. Using the payment service PHP class

<?php

require_once "Paytrail_Module_Rest.php";

// An object is created to model all payment return URLs
$urlset = new Paytrail_Module_Rest_Urlset(
    "https://www.demoshop.com/sv/success", // return URL for successful payment
    "https://www.demoshop.com/sv/failure", // return URL for failed payment
    "https://www.demoshop.com/sv/notify",  // URL for payment confirmation from Paytrail server
    ""  // pending url is not in use
);

// An object is created to model payer's data
$contact = new Paytrail_Module_Rest_Contact(
    "Test",                             // first name
    "Person",                           // surname
    "test.person@democompany.com",      // email address
    "Test street 1",                    // street address
    "12340",                            // postal code
    "Helsinki",                         // post office
    "FI",                               // country (ISO-3166)
    "040123456",                        // telephone number
    "",                                 // mobile phone number
    "Demo Company Ltd"                  // company name
);

// Payment creation
$orderNumber = "1";                     // Use distinguished order number
$payment = new Paytrail_Module_Rest_Payment_E1($orderNumber, $urlset, $contact);

// Adding one or more product rows to the payment
$payment->addProduct(
    "Test product", // product title
    "01234",        // product code
    "1.00",         // product quantity
    "19.90",        // product price (per piece)
    "23.00",        // Tax percentage
    "0.00",         // Discount percentage
    Paytrail_Module_Rest_Product::TYPE_NORMAL // Product type
);

// Changing payment default settings
// Changing payment method selection page language into English here
// The default language is Finnish. See other options from PHP class
$payment->setLocale("en_US");

// Sending payment to Paytrail service and handling possible errors
$module = new Paytrail_Module_Rest(13466, "");
try {
    $result = $module->processPayment($payment);
}
catch (Paytrail_Exception $e) {
    // processing the error
    // Error description available $e->getMessage()
    die("Error in creating payment to Paytrail service");
}

// Using the URL Paytrail returned for the desired payment method
// User is immediately directed to the received address
header("Location: {$result->getUrl()}");
?>
          

Example 5.11. Using the payment service PHP class without contact and product data

<?php

require_once "Paytrail_Module_Rest.php";

// An object is created to model all payment return addresses
$urlset = new Paytrail_Module_Rest_Urlset(
    "https://www.demoshop.com/sv/success", // return address for successful payment
    "https://www.demoshop.com/sv/failure", // return address for failed payment
    "https://www.demoshop.com/sv/notify",  // address for payment confirmation from Paytrail server
    ""  // pending url not in use
);

// Payment creation
$orderNumber = "1";                     // Use distinguished order number
$price = 99.00;                         // Total  (incl. VAT)
$payment = new Paytrail_Module_Rest_Payment_S1($orderNumber, $urlset, $price);

// Changing payment default settings
// Changing payment method selection page language into English here
// The default language is Finnish. See other options from PHP class
$payment->setLocale("en_US");

// Sending payment to Paytrail service and handling possible errors
$module = new Paytrail_Module_Rest(13466, "");
try {
    $result = $module->processPayment($payment);
}
catch (Paytrail_Exception $e) {
    // processing the error
    // Error description available $e->getMessage()
    die("Error in creating payment to Paytrail service");
}

// Using the URL Paytrail returned for the desired payment method
// User is immediately directed to the received address
header("Location: {$result->getUrl()}");
?>
          

Example 5.12. Confirming payment receipt with PHP class

require_once "Paytrail_Module_Rest.php";

$module = new Paytrail_Module_Rest(13466, "");
if ($module->confirmPayment($_GET["ORDER_NUMBER"], $_GET["TIMESTAMP"], $_GET["PAID"], $_GET["METHOD"], $_GET["RETURN_AUTHCODE"])) {
    // Payment receipt is valid
    // If needed, the used payment method can be found from the variable $_GET["METHOD"]
    // and order number for the payment from the variable $_GET["ORDER_NUMBER"]
}
else {
    // Payment receipt was not valid, possible payment fraud attempt
}
          

5.5.7. Perl

Warning

Paytrail is not involved in developing the Perl module and is not responsible for it. Perl module is Perl license (Artistic or GPL) program code.

The latest Perl module is available at http://search.cpan.org/dist/Finance-Bank-SuomenVerkkomaksut/