Code Samples

Documentation for the Payson Checkout 2.0 libraries hosted at GitHub.

PHP: https://github.com/PaysonAktiebolag/PaysonCheckout2-PHP

.NET: https://github.com/PaysonAktiebolag/PaysonCheckout2-.NET

Both libraries include complete examples to quickly get you started.

Initiate API

$merchantId = '4';
$apiKey = '2acab30d-fe50-426f-90d7-8c60a7eb31d4';
$environment = true;
$paysonApi = new PaysonEmbedded\PaysonApi($merchantId, $apiKey, $environment);
ParameterTypeDescription
$merchantIdstringR
$apiKeystringR
$environmentbooleanDefault falseO
var paysonMerchantId = "4";
var paysonApiKey = "2acab30d-fe50-426f-90d7-8c60a7eb31d4";
var inTestMode = true;
var apiCaller = new ApiCaller(paysonMerchantId, paysonApiKey, inTestMode);
ParameterTypeDescription
var paysonMerchantIdstringR
var paysonApiKeystringR
var inTestModeboolDefault falseO

Validate account

$accountStatus = $paysonApi->Validate();
var accountStatus = apiCaller.Validate();

Create merchant

$checkoutUri = 'https://www.mystore.com/checkout.php';
$confirmationUri = 'https://www.mystore.com/confirmation.php';
$notificationUri = 'https://www.mystore.com/notification.php';
$termsUri = 'https://www.mystore.com/terms.php';
$paysonMerchant = new PaysonEmbedded\Merchant($checkoutUri, $confirmationUri, $notificationUri, $termsUri);
ParameterTypeDescription
$checkoutUristringURI to the checkout pageR
$confirmationUristringURI to the confirmation pageR
$notificationUristringURI to the notifictaion pageR
$termsUristringURI to the terms pageR
$partnerIdstringOnly used by partners. Default nullO
$integrationInfostringDefault ‘PaysonCheckout2.0|x.x.x|NONE’O
$referencestringDefault nullO
$validationUristringURI to an optional validation page used to verify an order before it can be paid. Can for example be used to make sure all products are still in stock before payment is done. This URI must return HTTP 200 OK for the payment to succeed. Make sure the URI is publicly accessible. Default nullO
var merchant = new Merchant()
{
    CheckoutUri = new System.Uri("https://www.mystore.com/checkout"),
    NotificationUri = new System.Uri("https://www.mystore.com/notification"),
    ConfirmationUri = new System.Uri("https://www.mystore.com/confirmation"),
    TermsUri = new System.Uri("https://www.mystore.com/terms")
};
ParameterTypeDescription
CheckoutUriSystem.UriURI to the checkout pageR
ConfirmationUriSystem.UriURI to the confirmation pageR
NotificationUriSystem.UriURI to the notifictaion pageR
TermsUriSystem.UriURI to the terms pageR
PartnerIdstringOnly used by partners. Default nullO
ReferencestringDefault nullO
ValidationUriSystem.UriURI to an optional validation page used to verify an order before it can be paid. Can for example be used to make sure all products are still in stock before payment is done. This URI must return HTTP 200 OK for the payment to succeed. Make sure the URI is publicly accessible. Default nullO

Create order

$currencyCode = 'SEK';
$payData = new PaysonEmbedded\PayData($currencyCode);
ParameterTypeDescription
$currencyCodestring‘SEK’ or ‘EUR’R
var order = new Order()
{
    Currency = Currency.SEK
};
ParameterTypeDescription
CurrencyPaysonIntegrationCO2.Models.Enums.CurrencySEK or EURR

Create order item

$name = 'Product Name';
$unitPrice = 499.00;
$quantity = 1.00;
$taxRate = 0.25;
$reference = 'MDO0001';
$itemType = 'Physical';
$orderItem = new PaysonEmbedded\OrderItem($name, $unitPrice, $quantity, $taxRate, $reference, $itemType);

// Add order item to order
$payData->AddOrderItem($orderItem);
ParameterTypeDescription
$namestringProduct nameR
$unitPricefloatR
$quantityfloatR
$taxRatefloatR
$referencestringR
$itemTypestring‘Physical’, ‘Fee’, ‘Discount’ or ‘Service’. Default ‘Physical’O
$discountRatefloatO
$eanString (8-18)O
$uristringURI for product pageO
$imageUristringURI for product imageO
var orderItem = new Item()
{
    DiscountRate = 0.0m,
    Name = "Product Name",
    Quantity = 1,
    Reference = "MDO0001",
    TaxRate = (decimal)0.25,
    Type = ItemType.Physical,
    UnitPrice = 499
};

// Add order item to order
order.Items.Add(orderItem);
ParameterTypeDescription
NamestringProduct nameR
UnitPricedecimalR
QuantitydecimalR
TaxRatedecimalR
ReferencestringR
TypePaysonIntegrationCO2.Models.Enums.ItemTypePhysical, Fee, Discount or ServiceO
DiscountRatedecimalO
EanstringO
UriSystem.UriURI for product pageO
ImageUriSystem.UriURI for product imageO

Create GUI

$locale = 'sv';
$colorScheme = 'gray';
$verification = 'none';
$requestPhone = false;
$countries = array('SE', 'DK', 'FI');
$phoneOptional = false;
$gui = new PaysonEmbedded\Gui($locale, $colorScheme, $verification, $requestPhone, $countries, $phoneOptional);
ParameterTypeDescription
$localestring‘sv’, ‘fi’, ‘da’, ‘no’ or ‘en’. Default ‘sv’O
$colorSchemestring‘Gray’, ‘Blue’, ‘White’, ‘GrayTextLogos’, ‘BlueTextLogos’, ‘WhiteTextLogos’, ‘GrayNoFooter’, ‘BlueNoFooter’ or ‘WhiteNoFooter’. Default ‘Gray’O
$verificationstring‘none’ or ‘bankid’. Default ‘none’O
$requestPhonebooleanO
$countriesarrayArray of selectable countries, null will display all countries. Default nullO
$phoneOptionalbooleanO
var gui = new Gui()
{
    RequestPhone = false,
    ColorScheme = ColorScheme.Gray,
    Locale = "sv",
    PhoneOptional = false
};
ParameterTypeDescription
Localestring“sv”, “fi”, “da”, “no” or “en”R
ColorSchemePaysonIntegrationCO2.Models.Enums.ColorSchemeGray, Blue, White, GrayTextLogos, BlueTextLogos, WhiteTextLogos, GrayNoFooter, BlueNoFooter or WhiteNoFooterO
RequestPhoneboolO
PhoneOptionalboolO

Create customer

$firstName = 'Tess T';
$lastName = 'Persson';
$email = 'test@payson.se';
$phone = '1111111';
$identityNumber = '4605092222';
$city = 'Stan';
$countryCode = 'SE';
$postalCode = '99999';
$street = 'Storgatan 66';
$type = 'person';
$customer = new PaysonEmbedded\Customer($firstName, $lastName, $email, $phone, $identityNumber, $city, $countryCode, $postalCode, $street, $type);
ParameterTypeDescription
$firstNamestringO
$lastNamestringO
$emailstringO
$phonestringO
$identityNumberstringO
$citystringO
$countryCodestringO
$postalCodestringO
$streetstringO
$typestring ‘person’ or ‘business’. Default ‘person’O
var customer = new Customer()
{
    FirstName = "Tess T",
    LastName = "Persson",
    Email = "test@payson.se",
    Phone = "1111111",
    IdentityNumber = "4605092222",
    City = "Stan",
    CountryCode = "SE",
    PostalCode = "99999",
    Street = "Storgatan 66",
    Type = CustomerType.Person
};
ParameterTypeDescription
FirstNamestringO
LastNamestringO
EmailstringO
PhonestringO
IdentityNumberstringO
CitystringO
CountryCodestringO
PostalCodestringO
StreetstringO
TypePaysonIntegrationCO2.Models.Enums.CustomerType Person or BusinessO

Create checkout

$checkout = new PaysonEmbedded\Checkout($paysonMerchant, $payData, $gui, $customer);
$paysonCheckout = $paysonApi->CreateGetCheckout($checkout);
ParameterTypeDescription
$paysonMerchantPaysonEmbedded\MerchantR
$payDataPaysonEmbedded\PayDataR
$guiPaysonEmbedded\GuiO
$customerPaysonEmbedded\CustomerO
$descriptionstringO
$expirationTimestringO
var checkout = new Checkout()
{
    Merchant = merchant,
    Order = order,
    Customer = customer,
    Gui = gui
};
var location = apiCaller.NewCheckout(checkout);
var paysonCheckout = apiCaller.GetCheckout(location);
ParameterTypeDescription
MerchantPaysonIntegrationCO2.Models.MerchantR
OrderPaysonIntegrationCO2.Models.OrderR
GuiPaysonIntegrationCO2.Models.GuiR
CustomerPaysonIntegrationCO2.Models.CustomerR
ExpirationTimeSystem.DateTimeO

Get existing checkout

$existingCheckoutId = 'a273a0b8-402c-428f-99a0-a93f00df6bf6';

$paysonCheckout = $paysonApi->GetCheckout($existingCheckoutId);
ParameterTypeDescription
$existingCheckoutIdString, existing checkout ID, e.g ‘a273a0b8-402c-428f-99a0-a93f00df6bf6’R
var existingCheckoutId = new System.Guid("a273a0b8-402c-428f-99a0-a93f00df6bf6");

var paysonCheckout = apiCaller.GetCheckout(existingCheckoutId);
ParameterTypeDescription
var existingCheckoutIdGuidR

Ship/capture checkout

If ($paysonCheckout->status == 'readyToShip') {
    $paysonApi->ShipCheckout($paysonCheckout);
}
if (paysonCheckout.Status == CheckoutStatus.ReadyToShip)
{
    paysonCheckout.Status = CheckoutStatus.Shipped;

    apiCaller.SaveCheckout(paysonCheckout);
}

Cancel checkout

If ($paysonCheckout->status == 'readyToShip') {
    $paysonApi->CancelCheckout($paysonCheckout);
}
if (paysonCheckout.Status == CheckoutStatus.ReadyToShip)
{
    paysonCheckout.Status = CheckoutStatus.Canceled;

    apiCaller.SaveCheckout(paysonCheckout);
}

Update checkout

if ($paysonCheckout->status == 'shipped' || $paysonCheckout->status == 'paidToAccount') {
    foreach ($paysonCheckout->payData->items as $item) {
        // Credit 100%
        $item->creditedAmount = ($item->unitPrice * $item->quantity);

        // Credit 50%
        $item->creditedAmount = (($item->unitPrice * $item->quantity) / 2);

        // Credit specific order item
        if ($item->itemId == '33e67029-c07f-4327-ab2f-a95e00bb764b') {
            $item->creditedAmount = ($item->unitPrice * $item->quantity);
        }
    }

    $paysonCheckout = $paysonApi->UpdateCheckout($paysonCheckout);
}
if (paysonCheckout.Status == CheckoutStatus.Shipped || paysonCheckout.Status == CheckoutStatus.PaidToAccount)
{
    var checkoutItems = paysonCheckout.Order.Items.ToList();
    foreach (var checkoutItem in checkoutItems)
    {
        // Credit 100%
        checkoutItem.CreditedAmount = (checkoutItem.UnitPrice * checkoutItem.Quantity);

        // Credit specific order item
        if (checkoutItem.ItemId == new System.Guid("33e67029-c07f-4327-ab2f-a95e00bb764b"))
        {
            checkoutItem.CreditedAmount = (checkoutItem.UnitPrice * checkoutItem.Quantity);
        }
    }

     apiCaller.SaveCheckout(paysonCheckout);
}

Display checkout

echo $paysonCheckout->snippet;
ViewBag.Snippet = paysonCheckout.Snippet;

@Html.Raw(ViewBag.Snippet)

Minimal example

require_once 'lib/paysonapi.php';

$paysonApi = new PaysonEmbedded\PaysonApi('4', '2acab30d-fe50-426f-90d7-8c60a7eb31d4', true);

$paysonMerchant = new PaysonEmbedded\Merchant('https://www.mystore.com/checkout.php', 'https://www.mystore.com/confirmation.php', 'https://www.mystore.com/notification.php', 'https://www.mystore.com/terms.php');

$payData = new PaysonEmbedded\PayData('SEK');
$payData->AddOrderItem(new PaysonEmbedded\OrderItem('Product Name', 499.00, 1, 0.25, 'MDO0001'));

$checkout = new PaysonEmbedded\Checkout($paysonMerchant, $payData);

$paysonCheckout = $paysonApi->CreateGetCheckout($checkout);

echo $paysonCheckout->snippet;
// Controller
using System.Web.Mvc;
using PaysonIntegrationCO2;
using PaysonIntegrationCO2.Models;
using PaysonIntegrationCO2.Models.Enums;

namespace PaysonCheckout.Controllers
{
    public class CheckoutController : Controller
    {
        public ActionResult Index()
        {
            var apiCaller = new ApiCaller("4", "2acab30d-fe50-426f-90d7-8c60a7eb31d4", true);

            var merchant = new Merchant()
            {
                CheckoutUri = new System.Uri("https://www.mystore.com/checkout"),
                NotificationUri = new System.Uri("https://www.mystore.com/notification"),
                ConfirmationUri = new System.Uri("https://www.mystore.com/confirmation"),
                TermsUri = new System.Uri("https://www.mystore.com/terms")
            };

            var order = new Order()
            {
                Currency = Currency.SEK
            };

            var orderItem = new Item()
            {
                Name = "Product Name",
                Quantity = 1,
                Reference = "MDO0001",
                TaxRate = (decimal)0.25,
                UnitPrice = 499
            };
            order.Items.Add(orderItem);

            var customer = new Customer();

            var gui = new Gui()
            {
                Locale = "sv"
            };

            var checkout = new Checkout()
            {
                Merchant = merchant,
                Order = order,
                Customer = customer,
                Gui = gui
            };
 
            var location = apiCaller.NewCheckout(checkout);

            var paysonCheckout = apiCaller.GetCheckout(location);

            ViewBag.Snippet = paysonCheckout.Snippet;
            
            return View();
        }
    }
}
// View
<html>
    <body>
        @Html.Raw(ViewBag.Snippet)
    </body>
</html>

Full example

// Reference the library
require_once 'lib/paysonapi.php';

// Initiate API
$merchantId = '4';
$apiKey = '2acab30d-fe50-426f-90d7-8c60a7eb31d4';
$environment = true;
$paysonApi = new PaysonEmbedded\PaysonApi($merchantId, $apiKey, $environment);

// Create merchant
$checkoutUri = 'https://www.mystore.com/checkout.php';
$confirmationUri = 'https://www.mystore.com/confirmation.php';
$notificationUri = 'https://www.mystore.com/notification.php';
$termsUri = 'https://www.mystore.com/terms.php';
$partnerId = null;
$integrationInfo = 'PaysonCheckout2.0|1.0|NONE';
$orderReference = 'order123';
$validationUri = 'https://www.mystore.com/validation.php';
$paysonMerchant = new PaysonEmbedded\Merchant($checkoutUri, $confirmationUri, $notificationUri, $termsUri, $partnerId, $integrationInfo);
$paysonMerchant->reference = $orderReference;
$paysonMerchant->validationUri = $validationUri;

// Create order
$currencyCode = 'SEK';
$payData = new PaysonEmbedded\PayData($currencyCode);

// Create order item
$name = 'Product Name';
$unitPrice = 499.00;
$quantity = 1;
$taxRate = 0.25;
$reference = 'MDO0001';
$itemType = 'Physical';
$discountRate = 0.00;
$ean = 1234567891234;
$uri = 'https://www.mystore.com/productpage.php';
$imageUri = 'https://www.mystore.com/images/productimage.jpg';
$orderItem = new PaysonEmbedded\OrderItem($name, $unitPrice, $quantity, $taxRate, $reference, $itemType, $discountRate, $ean, $uri, $imageUri);

// Add order item to order
$payData->AddOrderItem($orderItem);

// Create GUI
$locale = 'sv';
$colorScheme = 'Gray';
$verification = 'none';
$requestPhone = false;
$countries = array('SE', 'DK', 'FI');
$phoneOptional = false;
$gui = new PaysonEmbedded\Gui($locale, $colorScheme, $verification, $requestPhone, $countries, $phoneOptional);

// Create customer
$firstName = 'Tess T';
$lastName = 'Persson';
$email = 'test@payson.se';
$phone = '1111111';
$identityNumber = '4605092222';
$city = 'Stan';
$countryCode = 'SE';
$postalCode = '99999';
$street = 'Storgatan 66';
$type = 'person';
$customer = new PaysonEmbedded\Customer($firstName, $lastName, $email, $phone, $identityNumber, $city, $countryCode, $postalCode, $street, $type);

// Create checkout
$description = 'Order from www.mystore.com';
$expirationTime = '2019-10-22T18:33:27';
$checkout = new PaysonEmbedded\Checkout($paysonMerchant, $payData, $gui, $customer, $description, $expirationTime);

// Get checkout
$paysonCheckout = $paysonApi->CreateGetCheckout($checkout);

// Display checkout
echo $paysonCheckout->snippet;
// Controller
using System.Web.Mvc;
using PaysonIntegrationCO2;
using PaysonIntegrationCO2.Models;
using PaysonIntegrationCO2.Models.Enums;

namespace PaysonCheckout.Controllers
{
    public class CheckoutController : Controller
    {
        public ActionResult Index()
        {

            var paysonMerchantId = "4";
            var paysonApiKey = "2acab30d-fe50-426f-90d7-8c60a7eb31d4";
            var inTestMode = true;
            var apiCaller = new ApiCaller(paysonMerchantId, paysonApiKey, inTestMode);

            var merchant = new Merchant()
            {
                CheckoutUri = new System.Uri("https://www.mystore.com/checkout"),
                NotificationUri = new System.Uri("https://www.mystore.com/notification"),
                ConfirmationUri = new System.Uri("https://www.mystore.com/confirmation"),
                TermsUri = new System.Uri("https://www.mystore.com/terms"),
                PartnerId = "",
                Reference = "order123",
                ValidationUri = new System.Uri("https://www.mystore.com/validation")
            };

            var order = new Order()
            {
                Currency = Currency.SEK
            };

            var orderItem = new Item()
            {
                DiscountRate = (decimal)0.00,
                Name = "Product Name",
                Quantity = 1,
                Reference = "MDO0001",
                TaxRate = (decimal)0.25,
                Type = ItemType.Physical,
                UnitPrice = 499,
                Ean = "1234567891234",
                ImageUri = new System.Uri("https://www.mystore.com/images/productimage.jpg"),
                Uri = new System.Uri("https://www.mystore.com/productpage.php")
            };
            order.Items.Add(orderItem);

            var customer = new Customer()
            {
                FirstName = "Tess T",
                LastName = "Persson",
                Email = "test@payson.se",
                Phone = "1111111",
                IdentityNumber = "4605092222",
                City = "Stan",
                CountryCode = "SE",
                PostalCode = "99999",
                Street = "Storgatan 66",
                Type = CustomerType.Person
            };

            var gui = new Gui()
            {
                RequestPhone = false,
                ColorScheme = ColorScheme.Gray,
                Locale = "sv",
                PhoneOptional = false
            };

            var checkout = new Checkout()
            {
                Merchant = merchant,
                Order = order,
                Customer = customer,
                Gui = gui,
                ExpirationTime = new System.DateTime(2020,08,28,17,44,18)
            };
 
            var location = apiCaller.NewCheckout(checkout);

            var paysonCheckout = apiCaller.GetCheckout(location);

            ViewBag.Snippet = paysonCheckout.Snippet;

            return View();
        }
    }
}
// View
<html>
    <body>
        @Html.Raw(ViewBag.Snippet)
    </body>
</html>

JavaScript Functions

// Reloads the iframe object (for example after updating of an order amount)
function sendUpdate() {
    var iframe = document.getElementById('paysonIframe');
    iframe.contentWindow.postMessage('updatePage', '*');
}

// Lock iframe object from user interaction until checkout is updated
function sendLockDown() {
    var iframe = document.getElementById('paysonIframe');
    iframe.contentWindow.postMessage('lock', '*');
}

// Release an locked iframe object
function sendRelease() {
    var iframe = document.getElementById('paysonIframe');
    iframe.contentWindow.postMessage('release', '*');
}

JavaScript Events

// Sent when customer adress has been set or changed
document.addEventListener("PaysonEmbeddedAddressChanged",function(evt) {
    var address = evt.detail;
        
    //adress.City
    //adress.CountryCode
    //adress.FirstName
    //adress.LastName
    //adress.PostalCode
    //adress.Street
    //adress.Email
        
    // Do something
});

// Sent when purchase is complete
document.addEventListener("PaysonEmbeddedCheckoutResult",function(evt) {
    var result= evt.result;
        
    if(result == 'ReadyToShip') {
         // Do something
    }

    if(result == 'Canceled') {
         // Do something
    }

    if(result == 'Denied') {
         // Do something
    }

    if(result == 'Expired') {
         // Do something
    }
});

Notifications

After a checkout resource has had its status changed to a status where the merchant may need to act, a notification will be sent. The notification is a simple POST call to the notificationUri specified by the merchant object with the id of the checkout as a querystring parameter.

For example: https://www.mystore.com/notification?checkout=a273a0b8-402c-428f-99a0-a93f00df6bf6

Make sure the notificationUri is publicly accessible for notifications to work.

The POST to notificationUri expect a 200 OK in response and will keep trying for up to 24 hours if the response is anything else.

Notification is sent on statusDescription
readyToShipThe payment is complete and the order should be shipped.
shippedThe order has been shipped.
paidToAccountMoney has been paid out to the merchant´s account.
expiredThe customer did not complete the payment in time (default 3 hours) or status readyToShip was set for more than 59 days.
canceledThe payment was canceled.
deniedThe payment of the order has been denied.

Statuses

 

StatusDescription
createdSet by Payson after the checkout has been created.
readyToPaySet by Payson after all necessary customer information has been added.
readyToShipSet by Payson after the customer has completed a payment or when an invoice can be sent.
shippedSet by the merchant to signal that the order has been shipped.
paidToAccountSet by Payson when money has been paid out to the merchant´s account.
expiredSet by Payson when expirationTime is reached for a checkout with status created (default 3 hours),
or when the status readyToShip has been set for more than 59 days.
canceledSet by either the merchant or the customer.
The customer is able to cancel the order before its status is set to readyToShip.
The merchant is able to cancel the order before its status is set to shipped.
deniedPayson will set the status to denied if the purchase is denied for any reason.