alt

Important information

The API reference is now available here.
The deprecated API reference is available here.

Unzer

Accept Google Pay with UI components

Use Unzer UI component to add Unzer Google Pay payment to your checkout page.

Overview

Using UI components for Google Pay™ you create a payment type resource that will be used to make the payment. You need to create a Google Pay button for this payment method.

Before you begin

Using Google Pay

Google Pay guidelines

Before you can use Google Pay as a payment method, you must make sure that your website or app comply with the guidelines specified by Google.

Google Pay version compatibility

You can accept payments using Google Pay with the Unzer API. Our implementation uses the major version 2 of the Google Pay API.

Google Pay - Good to know

  • When using an unzer production public key (p-xxx), the Google Pay PRODUCTION environment is used, else the TEST environment is used. For more information about the requirements for the Google Pay PRODUCTION environment that returns chargeable payment methods, see the Integration Checklist.

  • Direct integration (as opposed to Payment Page integration) requires the merchant to have a Google Developer Account (For more information see Setup).

  • When using the integration through our Payment Pages, the merchant will redirect or embed our checkout page and does not need to register for Google Pay individually.

Step 1: Add UI components to your payment page
client side

First, you need to initiate our UI components library and add the payment form to your payment page.

Initiate UI component

Load JS scripts and CSS stylesheet

Include GooglePay script on your website.

Include Unzer’s script and stylesheet on your website.

Always load the script and stylesheet directly from Unzer:

<script src="https://pay.google.com/gp/p/js/pay.js"></script>
<link rel="stylesheet" href="https://static.unzer.com/v1/unzer.css" />
<script type="text/javascript" src="https://static.unzer.com/v1/unzer.js"></script>
icon
Faster load time
To make your website load faster, insert JavaScript scripts at the bottom of your HTML document.
icon
Importing Unzer styles
To minimize the risk of Unzer styles affecting the styles of your webpage, we suggest putting unzer.css on top of other imported CSS files.

Create an Unzer instance

Create an unzer instance with your public key:

// Creating an unzer instance with your public key
var unzerInstance = new unzer('s-pub-xxxxxxxxxx');
icon
Placeholder keys
In the previous example, we used a placeholder API key for example purposes. You should replace it with your public key.

Localization and languages

We support localization with locale option parameters. Check the Localization page for a list of all the supported locales.

The auto option (applied by default) uses the client’s browser language.

Here you can see how to set the language, in our case ‘de-DE’ - to do so, add a comma separated parameter to your unzer instance:

// Creating an unzer instance with your public key
var unzerInstance = new unzer('s-pub-xxxxxxxxxx', {locale: 'de-DE'});

Implement the payment form

To securely collect payment data from your customer, you need to create a payment form with empty DOM elements and unique ID’s within them. That way unzer.js will know where to place its UI components.

<form id="payment-form" class="unzerUI form" novalidate>
  <div id="example-googlepay">
    <!-- The Google Pay button will be inserted here -->
  </div>
  <!-- Example success/error holder -->
  <div id="example-googlepay-error-holder" class="field" style="color: #9f3a38"></div>
  <div id="example-googlepay-success-holder" class="field" style="color: #13ae38"></div>
</form>

Matching IDs

When choosing your ID for a UI component, make sure that the names in your HTML and JavaScript match.

For example:

<div id="example-googlepay"> matches containerId: "example-googlepay".

Create a payment type resource

To create a payment type resource – a Googlepay instance, call the unzerInstance.Googlepay() function.

You should then call the initPaymentDataRequestObject() function by passing a valid object containing all needed information (see the section Initialize PaymentDataRequest object bellow).

This information will be used by the Googlepay instance to construct a valid Google Pay - PaymentDataRequest

Then call the create() function. This will configure your site’s support for the Google Pay API and render the Google Pay button inside the payment form.

// Creating a Google Pay instance
var googlepayInstance = unzerInstance.Googlepay()
var paymentDataRequestObject = googlepayInstance.initPaymentDataRequestObject({...})
googlepayInstance.create(
        {
          containerId: 'example-googlepay',
        },
        paymentDataRequestObject
);

Please make sure to pass valid parameters to the create function.

ParameterTypeDescriptionDefault value
containerId

(required)
StringThe HTML ID of the DOM element, where the UI component will be inserted.-
-

(required)
objectAn object to configure your site’s support for the Google Pay API. Please refer no next section for all available parameters.-

Initialize PaymentDataRequest object

Depending on the needed use case you should provide the needed parameters and callback handlers.

Basic checkout integration

ParameterTypeDescriptionDefault value
gatewayMerchantId

(required)
StringThe ChannelID provided by Unzer to the merchant.-
merchantInfo

(required)
objectMerchant information needed for requesting payment data. (For more details, see Google Pay - MerchantInfo)-
transactionInfo

(required)
objectTransaction details. (For more details, see Google Pay - TransactionInfo)

The countryCode must be set to the one submitted to Merchant upfront in the contract or in a separated email. Currently supported values are CH and DK
-
allowedCardNetworksarrayCard networks merchant supports. (For more details, see Google Pay - CardParameters)['MASTERCARD', 'VISA', 'DISCOVER', 'JCB']
allowCreditCardsbooleanSet to false if you don´t support credit cards. (For more details, see Google Pay - CardParameters)true
allowPrepaidCardsbooleanSet to false if you don´t support prepaid cards.true
CallbackTypeDescription
onPaymentAuthorizedCallback

(required)
functionThis callback is called when the payment is authorized.

Here you need to create the Unzer payment type resource. You can do this by calling googlePayInstance.createResource(paymentData), where paymentData is the response object that’s returned by Google after a payer approves payment. See Examples below.

Basic checkout integration with customized Google Pay button

ParameterTypeDescriptionDefault value
buttonOptionsobjectPay button options (For more details, see Google Pay - ButtonOptions).-

You can e.g provide the buttonColor property to set color of the button.

icon
Button type
The buttonType property is set to pay and can not be changed.

Express checkout

ParameterTypeDescriptionDefault value
emailRequiredbooleanSet to true if you request an email address.-
billingAddressRequiredbooleanSet to true if you require a billing address.false
billingAddressParametersobjectThe expected fields returned if billingAddressRequired is set to true. (For more details, see Google Pay - BillingAddressParameters)-

Express checkout with dynamic price update

ParameterTypeDescriptionDefault value
shippingAddressRequiredbooleanSet to true if you require a shipping address.false
shippingAddressParametersobjectSet shipping restrictions. (For more details, see Google Pay - ShippingAddressParameters)-
shippingOptionRequiredbooleanSet to true if you require shipping options.false
shippingOptionParametersobjectSet shipping options for the payment sheet and a default shipping option. (For more details, see Google Pay - ShippingOptionParameters)-
CallbackTypeDescription
onPaymentDataChangedCallbackfunctionThis callback is called when the shipping data changes .

Here you need to implement the logic to get the new shipping options. You can do this by implementing your own functions like fetchNewShippingOptions. See Examples below.

Examples

var paymentDataRequestObject = googlepayInstance.initPaymentDataRequestObject({
  gatewayMerchantId: "yourUnzerChannelId",
  merchantInfo: {
    merchantId: "yourGooglePayMerchantId",
    merchantName: 'yourMerchantName'
  },
  transactionInfo: {
    countryCode: 'CH',
    currencyCode: 'EUR',
    totalPrice: '19.99'
  },
  buttonColor: 'white',
  // ... other parameters
  onPaymentAuthorizedCallback: (paymentData) => {
    return googlepayInstance.createResource(paymentData)
            .then(result => {
              let typeId = result.id;
              // Submit the ID to your server-side integration
              document.getElementById('example-googlepay-success-holder').innerHTML = "created type ID: " + typeId;
              // Return object { status: 'success' }
              return { status: 'success' }
            })
            .catch(function (error) {
              let errorMessage = error.customerMessage || error.message || 'Error';
              document.getElementById('example-googlepay-error-holder').innerHTML = errorMessage;

              // return object { status: 'error', message: '--' }
              return {
                status: 'error',
                message: errorMessage || 'Unexpected error'
              }
            })
  },
  // ... other parameters
})

// Call create function and pass paymentDataRequestObject parameter 
googlepayInstance.create(
        {
          containerId: 'example-googlepay',
        },
        paymentDataRequestObject
);
var paymentDataRequestObject = googlepayInstance.initPaymentDataRequestObject({
  gatewayMerchantId: "yourUnzerChannelId",
  merchantInfo: {
    merchantId: "yourGooglePayMerchantId",
    merchantName: 'yourMerchantName'
  },
  transactionInfo: {
    countryCode: 'CH',
    currencyCode: 'EUR',
    totalPrice: '19.99'
  },
  emailRequired: true,
  billingAddressRequired: true,
  billingAddressParameters: {
    format: 'FULL'
  },
  // ... other parameters
  onPaymentAuthorizedCallback: (paymentData) => {
    return googlepayInstance.createResource(paymentData)
            .then(result => {
              let typeId = result.id;
              // Submit the ID to your server-side integration
              document.getElementById('example-googlepay-success-holder').innerHTML = "created type ID: " + typeId;
              // Return object { status: 'success' }
              return { status: 'success' }
            })
            .catch(function (error) {
              let errorMessage = error.customerMessage || error.message || 'Error';
              document.getElementById('example-googlepay-error-holder').innerHTML = errorMessage;

              // return object { status: 'error' }
              return {
                status: 'error',
                message: errorMessage || 'Unexpected error'
              }
            })
  },
  // ... other parameters
})

// Call create function and pass paymentDataRequestObject parameter 
googlepayInstance.create(
        {
          containerId: 'example-googlepay',
        },
        paymentDataRequestObject
);
const SAMPLE_DEFAULT_SHIPPING_OPTIONS = {
  defaultSelectedOptionId: 'shipping-001',
  shippingOptions: [
    {
      'id': 'shipping-001',
      'label': 'Free: Standard shipping',
      'description': 'Free Shipping delivered in 5 business days.'
    },
    {
      'id': 'shipping-002',
      'label': '$1.99: Standard shipping',
      'description': 'Standard shipping delivered in 3 business days.'
    },
    {
      'id': 'shipping-003',
      'label': '$10: Express shipping',
      'description': 'Express shipping delivered in 1 business day.'
    },
  ]
}

var paymentDataRequestObject = googlepayInstance.initPaymentDataRequestObject({
  gatewayMerchantId: "yourUnzerChannelId",
  merchantInfo: {
    merchantId: "yourGooglePayMerchantId",
    merchantName: 'yourMerchantName'
  },
  transactionInfo: {
    countryCode: 'CH',
    currencyCode: 'EUR',
    totalPrice: '19.99'
  },
  allowedCardNetworks: ['MASTERCARD'],
  buttonColor: 'white',
  shippingAddressRequired: true,
  shippingAddressParameters: {
    allowedCountryCodes: ['CH', 'DK', 'DE', 'US', 'HK', 'GB'],
    phoneNumberRequired: false
  },
  shippingOptionRequired: true,
  shippingOptionParameters: SAMPLE_DEFAULT_SHIPPING_OPTIONS,
  emailRequired: true,
  billingAddressRequired: true,
  
  // ... other parameters
  
  onPaymentDataChangedCallback: (intermediatePaymentData) => {
    // Sample logic to update the payment data by building new shipping options and new total calculation.
    let shippingAddress = intermediatePaymentData.shippingAddress;
    let shippingOptionData = intermediatePaymentData.shippingOptionData;
    let paymentDataRequestUpdate = {};

    if (intermediatePaymentData.callbackTrigger === "INITIALIZE" || intermediatePaymentData.callbackTrigger === "SHIPPING_ADDRESS") {
      if (shippingAddress.administrativeArea === "NJ") {
        paymentDataRequestUpdate.error = {
          reason: 'SHIPPING_ADDRESS_UNSERVICEABLE',
          message: 'Cannot ship to the selected address',
          intent: 'SHIPPING_ADDRESS'
        };
      } else {
        paymentDataRequestUpdate.newShippingOptionParameters = {
          defaultSelectedOptionId: 'shipping-001',
          shippingOptions: [
            {
              'id': 'shipping-001',
              'label': 'Free: Standard shipping',
              'description': 'Free Shipping delivered in 5 business days.'
            },
            // other values 
          ]
        };
        let selectedShippingOptionId = paymentDataRequestUpdate.newShippingOptionParameters.defaultSelectedOptionId;
        paymentDataRequestUpdate.newTransactionInfo = calculateNewTransactionInfo(selectedShippingOptionId);
      }
    } else if (intermediatePaymentData.callbackTrigger == "SHIPPING_OPTION") {
      paymentDataRequestUpdate.newTransactionInfo = calculateNewTransactionInfo(shippingOptionData.id);
    }

    return paymentDataRequestUpdate;
  }
})

// Call create function and pass paymentDataRequestObject parameter 
googlepayInstance.create(
        {
          containerId: 'example-googlepay',
        },
        paymentDataRequestObject
);


// -----------------------------------------------------------------
// Sample shipping helper functions, to be implemented be the merchant
// -----------------------------------------------------------------
function calculateNewTransactionInfo(shippingOptionId) {
  let newTransactionInfo = getGoogleTransactionInfo();

  let shippingCost = getShippingCosts()[shippingOptionId];
  newTransactionInfo.displayItems.push({
    type: "LINE_ITEM",
    label: "Shipping cost",
    price: shippingCost,
    status: "FINAL"
  });

  let totalPrice = 0.00;
  newTransactionInfo.displayItems.forEach(displayItem => totalPrice += parseFloat(displayItem.price));
  newTransactionInfo.totalPrice = totalPrice.toString();
  newTransactionInfo.totalPriceLabel = paymentDataRequestObject.transactionInfo.totalPriceLabel;

  return newTransactionInfo;
}

const SAMPLE_UNSERVICEABLE_ADDRESS_ERROR = {
  reason: 'SHIPPING_ADDRESS_UNSERVICEABLE',
  message: 'Cannot ship to the selected address',
  intent: 'SHIPPING_ADDRESS'
}

const SAMPLE_TRANSACTION_INFO = {
  countryCode: 'CH',
  currencyCode: "EUR",
  totalPriceStatus: "FINAL",
  totalPrice: "12.00",
}

const SHIPPING_COSTS = {
  'shipping-001': '0.00',
  'shipping-002': '1.99',
  'shipping-003': '10.00'
}

function getUnserviceableAddressError() {
  return JSON.parse(JSON.stringify(SAMPLE_UNSERVICEABLE_ADDRESS_ERROR));
}

function getNewShippingOptions() {
  return JSON.parse(JSON.stringify(SAMPLE_DEFAULT_SHIPPING_OPTIONS));
}

function getGoogleTransactionInfo() {
  return JSON.parse(JSON.stringify(SAMPLE_TRANSACTION_INFO));
}

function getShippingCosts() {
  return JSON.parse(JSON.stringify(SHIPPING_COSTS));
}

Step 2: Make a payment
server side

To make a payment, you need a customer, a basket (optional), and a paymentType resource.

Create the customer resource

This step is only applicable if you didn’t create a customer resource on the client side.

B2C customer creation

For B2C transactions, create a customer as described in the example request. To learn more about the customer resource, see the API reference.

POST https://api.unzer.com/v1/customers
{
  "salutation": "mr",
  "firstname": "Rainer",
  "lastname": "Zufall",  
  "birthDate": "1980-06-22",
  "email": "rainer.zufall@domain.de",
  "language": "de",
  "phone": "+49 152 987654321",
  "billingAddress": {
    "name": "Rainer Zufall",
    "street": "Unzerstraße 18",
    "zip": "22767",
    "city": "Hamburg",
    "country": "DE"
  },
  "shippingAddress": {
    "name": "Rainer Zufall",
    "street": "Unzerstraße 18",
    "zip": "22767",
    "city": "Hamburg",
    "country": "DE"
  }
}
$address = (new Address())
    ->setName('Rainer Zufall')
    ->setStreet('Unzerstraße 18')
    ->setZip('22767')
    ->setCity('Hamburg')
    ->setCountry('DE');

$customer = (new Customer())
    ->setFirstname('Rainer')
    ->setLastname('Zufall')
    ->setSalutation(Salutations::MR)
    ->setCompany('Unzer GmbH')
    ->setBirthDate('1972-12-24')
    ->setEmail('rainer.zufall@domain.de')
    ->setLanguage("de")
    ->setPhone('+49 152 987654321')
    ->setBillingAddress($address)
    ->setShippingAddress($address);

$unzer = new Unzer('s-priv-xxxxxxxxxx');
$unzer->createCustomer($customer);
Unzer unzer = new Unzer("s-priv-xxxxxxxxxx");

Address address = new Address()
        .setName('Rainer Zufall')
        .setStreet('Unzerstraße 18')
        .setZip('22767')
        .setCity('Hamburg')
        setCountry('DE');
        
Customer customer = new Customer("John", "Doe")
        .setSalutation(Salutations::MR)
        .setCompany('Unzer GmbH')
        .setBirthDate('1972-12-24')
        .setEmail('rainer.zufall@domain.de')
        .setLanguage("de")
        .setPhone('+49 152 987654321')
        .setBillingAddress(address)
        .setShippingAddress(address);

unzer.createCustomer(customer);

The response looks similar to the following example:

{
    "id": "s-cst-b7e502fcbb10"
}

For a full description of customer resource, refer to the relevant server-side-integration documentation page: Manage customer (direct API calls).

icon
Both B2C and B2B customer types are supported.

Create a basket resource (Optional)

The basket resource stores information about the purchased products, used vouchers, and the shipment costs.

For a full description of baskets resource, refer to the relevant server-side-integration documentation page: Manage baskets (v2).

POST https://api.unzer.com/v2/baskets
{
    "totalValueGross": "105.95",
    "currencyCode": "EUR",
    "basketItems": [
        {
            "type": "goods",
            "basketItemReferenceId": "SKU-1783746",
            "title": "Jacket Fleece size M",
            "quantity": 1,
            "amountPerUnitGross": 100,
            "vat": "19"
        },
        {
            "type": "shipment",
            "basketItemReferenceId": "express-shipping",
            "title": "Shipment fee",
            "quantity": 1,                        
            "amountPerUnitGross": 5.95,
            "vat": "19"
        }
    ]
}
<?php
$unzer = new Unzer('s-priv-xxxxxxxxxx');

$basketItem1 = (new BasketItem())
    ->setBasketItemReferenceId('Item-d030efbd4963')
    ->setQuantity(10)
    ->setUnit('m')
    ->setAmountPerUnitGross(20.00)
    ->setAmountDiscountPerUnitGross(1.00)
    ->setVat(19.0)
    ->setTitle('SDM 6 CABLE')
    ->setSubTitle('This is brand new Mid 2019 version')
    ->setImageUrl('https://a.storyblok.com/f/91629/x/1ba8deb8cc/unzer_primarylogo__white_rgb.svg')
    ->setType(BasketItemTypes::GOODS);

$basketItem2 = (new UnzerSDK\Resources\EmbeddedResources\BasketItem())
    ->setTitle('Shipment fee')
    ->setBasketItemReferenceId('express-shipping')
    ->setQuantity(1)
    ->setAmountPerUnitGross(5.95)
    ->setVat(19.0)
    ->setType(UnzerSDK\Constants\BasketItemTypes::SHIPMENT);

$basket = (new Basket())
    ->setTotalValueGross(195.95)
    ->setCurrencyCode('EUR')
    ->setOrderId('Order-12345')
    ->setNote('Test Basket')
    ->addBasketItem($basketItem1)
    ->addBasketItem($basketItem2);

$unzer->createBasket($basket);
BasketItem basketItem1 = new BasketItem()
        .setBasketItemReferenceId("Item-d030efbd4963")
        .setQuantity(BigDecimal.valueOf(10))
        .setUnit("m")
        .setAmountPerUnitGross(BigDecimal.valueOf(20.00))
        .setAmountDiscountPerUnitGross(BigDecimal.valueOf(1.00))
        .setVat(BigDecimal.valueOf(19.0))
        .setTitle("SDM 6 CABLE")
        .setSubTitle("This is brand new Mid 2019 version")
        .setImageUrl(new URL("https://a.storyblok.com/f/91629/x/1ba8deb8cc/unzer_primarylogo__white_rgb.svg"))
        .setType(BasketItem.Type.GOODS);

BasketItem basketItem2 = (new BasketItem())
    .setBasketItemReferenceId("express-shipping")
    .setQuantity(1)
    .setAmountPerUnitGross(BigDecimal.valueOf(5.95))
    .setVat(BigDecimal.valueOf(19.0))
    .setTitle("Shipment fee")
    .setType(BasketItem.Type.GOODS);

Basket basket  = new Basket()
    .setTotalValueGross(BigDecimal.valueOf(195.95))
    .setCurrencyCode(Currency.getInstance("EUR"))
    .setOrderId("Order-12345")
    .setNote("Test Basket")
    .addBasketItem(basketItem1)
    .addBasketItem(basketItem2);

Unzer unzer = new Unzer("s-priv-xxxxxxxxxx");
unzer.createBasket(basket);

The response looks similar to the following example:

{
    "id": "s-bsk-7e772dd4266b"
}

For a full description of basket resource, refer to the relevant server-side-integration documentation page: Direct API integration.

Option 1: Charge the card directly

Make a charge transaction with the googlepay resource that you created in the front end. With a successful charge transaction, money is transferred from the customer to you (merchant) and a payment resource is created.

POST https://api.unzer.com/v1/payments/charges
   
Body:
{
  "amount" : "105.95",
  "currency": "EUR",
  "returnUrl": "https://www.my-shop-url.de/returnhandler",
  "resources" : {
    "typeId" : "s-gop-p6gwgiuvjigm",
    "basketId": "s-bsk-7e772dd4266b",
    "customerId": "s-cst-b7e502fcbb10"
  }
}
<?php

$unzer     = new UnzerSDK\Unzer('s-priv-xxxxxxxxxx');

$charge = new Charge(105.95, 'EUR', 'https://www.my-shop-url.de/returnhandler');
$typeId = 's-gop-3qujdbdjas5w';

$unzer->performCharge($charge, $typeId);
Unzer unzer = new Unzer("s-priv-xxxxxxxxxx");

Charge charge = (Charge) new Charge()
        .setAmount(BigDecimal.valueOf(105.95))
        .setCurrency(Currency.getInstance("EUR"))
        .setTypeId("s-gop-zex7c9iibpek")
        .setReturnUrl(unsafeUrl("https://www.my-shop-url.de/returnhandler");

unzer.charge(charge);

The response looks similar to the following example:

{
    "id": "s-chg-1",
    "isSuccess": false,
    "isPending": true,
    "isError": false,
    "redirectUrl": "https://stg-payment.unzer.com/v1/redirect/crd/s-sGYdGywWpxzW",
    "message": {
        "code": "COR.000.100.112",
        "merchant": "Request successfully processed in 'Merchant in Connector Test Mode'",
        "customer": "Your payments have been successfully processed in sandbox mode."
    },
    "amount": "105.9500",
    "currency": "EUR",
    "returnUrl": "https://www.my-shop-url.de/returnhandler",
    "date": "2021-05-10 00:51:03",
    "resources": {
        "paymentId": "s-pay-131937",
        "traceId": "70ddf3152a798c554d9751a6d77812ae",
        "typeId": "s-gop-p6gwgiuvjigm",
        "basketId": "s-bsk-7e772dd4266b",
        "customerId": "s-cst-b7e502fcbb10"
        
    },
    "paymentReference": "",
    "processing": {
        "uniqueId": "31HA07BC8157BD2BC04D483EFA914465",
        "shortId": "4845.3426.1987",
        "traceId": "70ddf3152a798c554d9751a6d77812ae"
    }
}

For a full description of the charge transaction, refer to the relevant server-side integration documentation page: Charge a payment (direct API calls), Charge a payment (PHP SDK), Charge a payment (Java SDK).

Option 2: Authorize and then charge the card

To authorize an amount, make an authorize transaction with the googlepay resource that you created in the frontend. With a successful authorize transaction, money is reserved on the customer account and a Payment resource is created.

POST https://api.heidelpay.com/v1/payments/authorize


 Body:
{
  "amount" : "105.95",
  "currency": "EUR",
  "returnUrl": "https://www.my-shop-url.de/returnhandler",
  "resources" : {
    "typeId" : "s-gop-p6gwgiuvjigm",
    "basketId": "s-bsk-7e772dd4266b",
    "customerId": "s-cst-b7e502fcbb10"
  }
}
<?php

$unzer     = new UnzerSDK\Unzer('s-priv-xxxxxxxxxx');

$authorization = (new Authorization(105.95, 'EUR', 'https://www.my-shop-url.de/returnhandler'));
$typeId = 's-gop-3qujdbdjas5w';

$unzer->performAuthorization($authorization, $typeId);
Unzer unzer = new Unzer("s-priv-xxxxxxxxxx");
    
Authorization authorization = (new Authorization())
        .setAmount(BigDecimal.valueOf(105.95))
        .setCurrency(Currency.getInstance("EUR"))
        .setTypeId("s-gop-zex7c9iibpek")
        .setReturnUrl(unsafeUrl("https://www.my-shop-url.de/returnhandler");

unzer.authorize(authorization);

The response looks similar to the following example:

{
    "id": "s-aut-1",
    "isSuccess": true,
    "isPending": false,
    "isError": false,
    "card3ds": false,
    "redirectUrl": "",
    "message": {
        "code": "COR.000.100.112",
        "merchant": "Request successfully processed in 'Merchant in Connector Test Mode'",
        "customer": "Your payments have been successfully processed in sandbox mode."
    },
    "amount": "105.9500",
    "currency": "EUR",
    "returnUrl": "https://www.my-shop-url.de/returnhandler",
    "date": "2021-06-04 11:19:10",
    "resources": {
        "customerId": "s-cst-b7e502fcbb10",
        "paymentId": "s-pay-8435",
        "basketId": "s-bsk-7e772dd4266b",
        "traceId": "8ee5c53960f8b39839b70799fe224d84",
        "typeId": "s-gop-p6gwgiuvjigm"
    },
    "paymentReference": "",
    "processing": {
        "uniqueId": "31HA07BC8198C2F9107E0E3536444655",
        "shortId": "4867.3194.9885",
        "traceId": "8ee5c43960f8b39839b70799fe224d84"
    }
}

For a full description of the Authorize transaction, see the relevant server-side-integration documentation page: Authorize a payment (direct API calls), Authorize a payment (PHP SDK), Authorize a payment (Java SDK).

Charge the authorization

Because the customer already accepted the payment with the authorize transaction, you can now charge the payment to transfer the money.

POST https://api.heidelpay.com/v1/payments/s-pay-8435/charges/
   
Body:
{
    "amount": "105.95",
}
$unzer = new Unzer('s-priv-xxxxxxxxx');
$charge = $unzer->performChargeOnPayment('s-pay-1', new Charge());
Unzer unzer = new Unzer("s-priv-xxxxxxxxxx");
Charge charge = unzer.chargeAuthorization("s-pay-1");

The response looks similar to the following example:

{
    "id": "s-chg-1",
    "isSuccess": true,
    "isPending": false,
    "isError": false,
    "card3ds": false,
    "redirectUrl": "",
    "message": {
        "code": "COR.000.100.112",
        "merchant": "Request successfully processed in 'Merchant in Connector Test Mode'",
        "customer": "Your payments have been successfully processed in sandbox mode."
    },
    "amount": "105.9500",
    "currency": "EUR",
    "date": "2021-06-04 11:19:10",
    "resources": {
        "customerId": "s-cst-b7e502fcbb10",
        "paymentId": "s-pay-8435",
        "basketId": "s-bsk-7e772dd4266b",
        "traceId": "8ee5c53960f8b39839b70799fe224d84",
        "typeId": "s-gop-p6gwgiuvjigm"
    },
    "paymentReference": "",
    "processing": {
        "uniqueId": "31HA07BC8198C2F9107E0E3536444655",
        "shortId": "4867.3194.9885",
        "traceId": "8ee5c43960f8b39839b70799fe224d84"
    }
}

Step 3: Check status of the payment
server side

Once the customer is redirected to the returnUrl, you can fetch the payment details from the API, by using the resources.paymentId from the charge response above to handle the payment according to its status. If the status of the payment is completed, the payment process has been finished successfully and can be considered as paid. Check all possible payment states here.

GET https://api.unzer.com/v1/payments/{payment_ID}

{
    "id": "s-pay-8435",
    "state": {
        "id": 1,
        "name": "completed"
    },
    "amount": {
        "total": "105.9500",
        "charged": "105.9500",
        "canceled": "0.0000",
        "remaining": "0.0000"
    },
    "currency": "EUR",
    "orderId": "",
    "invoiceId": "",
    "resources": {
        "customerId": "s-cst-b7e502fcbb10",
        "paymentId": "s-pay-8435",
        "basketId": "s-bsk-7e772dd4266b",
        "metadataId": "",
        "payPageId": "",
        "traceId": "70ddf3152a798c554d9751a6d77812ae",
        "typeId": "s-gop-p6gwgiuvjigm"
    },
    "transactions": [
        {
            "date": "2021-05-10 00:51:03",
            "type": "charge",
            "status": "success",
            "url": "https://api.unzer.com/v1/payments/s-pay-131937/charges/s-chg-1",
            "amount": "105.9500"
        }
    ]
}

Step 4: Display the payment result
client side

Use the information from the Check status of the payment step to display the payment result to your customer.
This can be the success or error page of your shop. If something went wrong, you can use the client message from the API response and show it to the customer.

Manage payment
server side

For more details on managing Google Pay payments, see Manage Google Pay payments.

Notifications

We recommend subscribing to the payment event to receive notifications about any changes to the payment resource. As soon as the event is triggered you should fetch the payment and update the order status in your shop according to its status.

  {
    "event":"payment.pending",
    "publicKey":"s-pub-xxxxxxxxxx",
    "retrieveUrl":"https://api.unzer.com/v1/payments/s-pay-774",
    "paymentId":"s-pay-774"
  }

For more details on implementing webhooks to receive notifications, see Notifications page.

Error handling

All requests to the API can result in an error that should be handled. Refer to the Error handling guide to learn more about Unzer API (and other) errors and handling them.

Test & go live

You should always test your integration before going live. First perform test transactions using test data. Next, check against Integration checklist and Go-live checklist to make sure the integration is complete and you’re ready to go live.

See also