alt

Important information

Please be advised that there will be a scheduled downtime across our API network on November 05 and November 07, 2024. For more information, visit our platform status portal.:
- Scheduled maintenance on November 5, 2024
- Scheduled maintenance on November 7, 2024

Unzer

Accept Google Pay with UI components (V2)

Beta

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

Overview

Using UI components for Google Pay™ you create a googlepay payment type resource that will be used to make the payment. Basic steps for integrating using UI v2 components are the same for all payment methods, and you can read about them here.

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.

Before you begin

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

First, you need to initiate our UI components v2 library and add the needed payment type component to your payment page.

Initiate UI Components

Load the Unzer JS script

Include the Unzer JS script on your website. This will load all the Unzer custom UI components, prefixed with unzer- e.g <unzer-paylater-invoice>.

Make sure to always include the script directly from the Unzer domain https://static.unzer.com

<script
        type="module"
        src="https://static-v2.unzer.com/v2/ui-components/index.js"
></script>
icon info
Faster load time

To make your website load faster, import the unzer script at the bottom of your HTML document.

Make sure to import the script as type=“module”

icon info
Content security policy
To learn which URLs must be added to the allowlist for Unzer UI components in your content security policy, please refer to Content security policy section.

It is a good practice to put your website in loading state until the Unzer script is loaded, and the UI components are ready to use.

    // Make sure initially your application is in loading state
    // until all Unzer components are loaded
    Promise.all([
        customElements.whenDefined("unzer-payment"),
        // Probably add any other Unzer components used here. For example:
        // customElements.whenDefined("unzer-paylater-invoice"),
    ]).then(() => {
        // Hide the loading state and proceed with next steps
    }).catch((error) => {
        // Handle any error that might occur during the 
        // loading process and initialization
    });

UI setup and configuration

To securely collect payment data from your customer, you need to add the <unzer-payment> component, inside which you insert the needed payment type components.

icon
We recommend putting your submit button inside the <unzer-checkout> element. This will provide automatic handling for enabling/disabling the submit button depending on the current status, and showing/hiding of brand icons.
<unzer-payment
        id="unzer-payment"
        publicKey="s-pub-xyz"
        locale="de-DE">
    <!-- ... Here you will need to add the Unzer payment type tag, so the form UI elements will be inserted -->
    <!--    e.g <unzer-paylater-invoice></unzer-paylater-invoice> -->
</unzer-payment>
<unzer-checkout id='unzer-checkout'>
    <button type="submit" id="yourPaymentButtonId">Pay</button>
</unzer-checkout>

Following parameters need to be passed.

ParameterTypeDescriptionDefault value
publicKey (required)StringThe merchant public key.-
localeStringThe used locale. For more information on supported locales, see Localization.Browser user defined locale.
initDataobjectA key/value object in JSON-format containing data to initialize the payment type. For more information, Check payment methods and their features.Empty object {}

Optional: Customize UI components

Our UI Components v2 are provided with a default theme that contains base styles. You can easily customize these styles by overriding the following CSS variables.

Variable nameDescriptionAffected components
--unzer-fontReplaces all fonts with the given font. Users can define any font-face and provide the name of the custom font-face.typography
--unzer-text-colorThe font color use for typography.typography, icons
--unzer-brand-colorThe main color of the application.button, checkbox, radio, loader
--unzer-background-colorThe page background.
--unzer-link-colorThe color of links.link
--unzer-corner-radiusWhether controls will have rounded corners or not. Values can be either 0 or 1.button, tags, chips
--unzer-shadowsWhether shadows are enabled or not. Values can be either 0 or 1.button, card
<head>
    <style>
        :root {
            --unzer-font: SFMono;
            --unzer-brand-color: #ee1818;
            --unzer-text-color: #f19316;
            --unzer-background-color: #6a9472;
            --unzer-link-color: #1330ef;
            --unzer-corner-radius: 0;
            --unzer-shadows: 1;
        }
    </style>
</head>

Implement the payment form

First you need to insert the Unzer Google Pay element <unzer-google-pay> inside the <unzer-payment>.

<unzer-payment
        id="unzer-payment"
        publicKey="s-pub-xyz"
        locale="de-DE">
        <unzer-google-pay></unzer-google-pay>
</unzer-payment>
<unzer-checkout id='unzer-checkout'></unzer-checkout>

In case you want also to create/update your customer information, then you will need to use our Unzer UI customer elements.

Option 1: Implement with customer elements

If you don’t have information about the customer (and the corresponding customerID) or want to update information of an already existing customer, you can do so using Unzer UI customer elements.

Customer elementDescription
<unzer-shipping-address>Adds the customer shipping address information (email, salutation, firstname, lastname, country, street, post code, city, mobile number)
<unzer-billing-address>Adds the customer billing address information (firstname, lastname, country, street, post code, city).

The Unzer UI customer elements can be inserted either inside or outside the <unzer-payment> element. On submit, all data from the added Unzer UI customer elements will be gathered and submitted together with the payment form, in order to create the customer and payment type resources.

In case you wish to initialize the customer elements with the data of an already created customer, you will need to call the setCustomerData() function of the <unzer-payment> element, and pass a customer object in JSON format.

customer object

ParameterTypeDescriptionDefault value
idStringThe ID of the customer you wish to update.
If not passed, then a new customer will be created.
salutationStringThe salutation for the customer. Allowed values are:
"mr", "mrs", "diverse"
"mr"
firstnameStringThe first name of the customer.""
lastnameStringThe last name of the customer.""
birthDateStringThe birth date of the customer.""
emailStringThe E-mail of the customer.""
mobileNumbermobileNumber ObjectThe mobile number{}
shippingAddressaddress objectThe shipping address for the customer in JSON format.{}
billingAddressaddress objectThe billing address for the customer in JSON format.{}

address object

ParameterTypeDescriptionDefault value
nameStringThe firstname + lastname of the customer""
streetStringThe street and house number""
zipStringThe zip-code""
cityStringThe city""
stateStringThe state""
countryStringThe country ISO country code ISO 3166 ALPHA-2"DE"
shippingType

only in shippingAddress
StringThe shippingType. Allowed values are:
"equals-billing", "different-address", "branch-pickup", "post-office-pickup", "pack-station"
"DE"

mobileNumber object

ParameterTypeDescriptionDefault value
prefixStringThe country prefix of the mobile number""
phoneStringThe mobile number""



The following code example shows the options described above:

    <unzer-payment
            id="unzer-payment"
            publicKey="s-pub-xyz"
            locale="de-DE">
            <unzer-google-pay></unzer-google-pay>
    </unzer-payment>
    
    <p>Shipping Information</p>
    <unzer-personal-info></unzer-personal-info>
    <unzer-shipping-address></unzer-shipping-address>
    
    <p>Billing Information</p>
    <unzer-billing-address></unzer-billing-address>

    <unzer-checkout id='unzer-checkout'></unzer-checkout>
    const unzerPaymentElement = document.getElementById('unzer-payment');
    unzerPaymentElement.setCustomerData({
        "id": "s-cst-xyz",
        "lastname": "Universum",
        "firstname": "Peter",
        "salutation": "mr",
        "birthDate": "20.12.1987",
        "mobileNumber": {
            "prefix": "49",
            "phone": "1234"
        },
        "shippingAddress": {
            "name": "Peter Universum",
            "street": "Hugo-Junkers-Str. 5",
            "zip": "60386",
            "city": "Frankfurt am Main",
            "country": "DE",
            "shippingType": "equals-billing"
        },
        "billingAddress": {
           "state": "Peter Universum",
           "street": "Hugo-Junkers-Str. 5",
            "zip": "60386",
            "city": "Frankfurt am Main",
            "country": "DE"
        }
    })

Option 2: Create the customer on the server side

You can also use the customer data provided by your shop system to create the customer resource on the server side. This way you can omit rendering the customer form in the front end and just create the resource and use the ID in your transaction request.

In that case you just need to render the payment type form and create a simple HTML button on the client side.

Initialize PaymentDataRequest object

To Initialize Google Payment, you need to call the setGooglePayData() function by passing a valid object containing all required information.

<unzer-payment
        id="unzer-payment"
        publicKey="s-pub-xyz"
        locale="de-DE"
        >
        <unzer-google-pay></unzer-google-pay>
</unzer-payment>
    Promise.all([
        customElements.whenDefined("unzer-payment"),
    ]).then(() => {
        const paymentDataRequestObject = {googlePayData: paymentDataRequestObject}
        const unzerPaymentElement = document.getElementById('unzer-payment');
        unzerPaymentElement.setGooglePayData(paymentDataRequestObject);
    }).catch((error) => {
        // Handle any error that might occur during the 
        // loading process and initialization
    });

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

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
Default is 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. 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.

Create Payment Type and Customer Resources

To create a payment type, call the submit() function on onPaymentAuthorizedCallback.

Examples

const unzerPaymentElement = document.getElementById('unzer-payment');

unzerPaymentElement.setGooglePayData({
  gatewayMerchantId: "yourUnzerChannelId",
  merchantInfo: {
    merchantId: "yourGooglePayMerchantId",
    merchantName: 'yourMerchantName'
  },
  transactionInfo: {
    countryCode: 'CH',
    currencyCode: 'EUR',
    totalPrice: '19.99'
  },
  buttonOptions: {
    buttonColor: 'black',
  },
  // ... other parameters
  onPaymentAuthorizedCallback: async () => {
    return await unzerPaymentElement?.submit().then(result => result.submitResponse);
  }
});
var paymentDataRequestObject = unzerPaymentElement.setGooglePayData({
  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) => {

  },
  // ... other parameters
});
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 = unzerPaymentElement.setGooglePayData({
  gatewayMerchantId: "yourUnzerChannelId",
  merchantInfo: {
    merchantId: "yourGooglePayMerchantId",
    merchantName: 'yourMerchantName'
  },
  transactionInfo: {
    countryCode: 'CH',
    currencyCode: 'EUR',
    totalPrice: '19.99'
  },
  allowedCardNetworks: ['MASTERCARD'],
  buttonOptions: {
    buttonColor: 'black',
  },
  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;
  }
})

// -----------------------------------------------------------------
// 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",
    "shippingType": "equals-billing"
  }
}
$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"
        }
    ]
}
$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"
  }
}
$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://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.unzer.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"
  }
}
$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.unzer.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