Apple pay js api example

Подключаем оплату через Apple Pay на сайте

Сейчас, в том числе и у нас на сайте, и в приложениях ivi, есть явная тенденция роста аудитории на мобильных устройствах. Также растет и доля покупок, совершаемых в интернете с мобильных устройств. В отличие от десктопа, помимо традиционных вариантов оплаты, доступны системы мобильных платежей, например Apple Pay, Android Pay, Samsung Pay. Эти системы можно использовать не только для оплаты в терминалах, принимающих банковские карты, но и для оплаты в приложениях и на веб-сайтах.

Внедрение мобильных платежей мы начали с веб-версии ivi и выбрали мобильный сайт и систему Apple Pay.

Apple Pay — система мобильных платежей от Apple, позволяющая мобильным устройствам проводить платежи в магазинах и в интернете. Пользователь привязывает карту к телефону, и далее при оплате требуется только подтверждение платежа отпечатком пальца или цифровым кодом.

В этой статье я расскажу об использовании библиотеки Apple Pay JS.

Библиотека предназначена для использования Apple Pay на сайтах. Apple Pay JS API поддерживается на:

  • iOS начиная от 10 версии в браузере Safari и моделях iPhone, поддерживающих бесконтактные платежи (SE и старше 6);
  • macOS от версии 10.12 в браузере Safari на компьютерах с Touch ID или при подключенном iPhone или Apple Watch для подтверждения платежей.

Для того чтобы принимать платежи через Apple Pay на сайте, вам потребуется:

  • Девелоперский аккаунт Apple;
  • HTTPS на странице, использующей Apple Pay;
  • Выбрать платежный шлюз, с которым вы будете работать. Мы пользуемся услугами Payture.

Далее нужно зарегистрировать Merchant ID, создать сертификаты Merchant Identity Certificate и Payment Processing Certificate и верифицировать домены, на которых будет использоваться Apple Pay. Описание процесса есть в инструкции от Payture.

  • Merchant ID — идентификатор продавца, представляющий его в Apple Pay;
  • Payment Processing Certificate — сертификат, используемый для передачи платежных данных на стороне платежного шлюза. Сервера Apple Pay используют публичный ключ этого сертификата для шифрования платежных данных. Приватный ключ используется для расшифровывания данных при проведении платежа;
  • Merchant Identity Certificate — TLS сертификат, используемый для подтверждения данных продавца и авторизации платежных сессий через сервера Apple. Платежная сессия создается при инициализации процесса оплаты. Сертификат используется только на стороне сайта.

Стоит обратить внимание на то, что при верификации нужно указать полное доменное имя, т.е. маску домена указать не получится.

После всей подготовительной работы можно приступить к интеграции Apple Pay на сайт. Процесс интеграции состоит из 3 основных частей:

  • Создание платежной сессии, показ диалога платежа и обработка событий платежной сессии. Тут используется Apple Pay JS API;
  • Верификация платежной сессии. Требуется для того, чтобы система Apple Pay могла убедиться, что запрос идет от зарегистрированного продавца. Реализуется на бекенде;
  • Проведение платежа через платежный шлюз и завершение платежной сессии.

Создание платежной сессии

Перед показом кнопки оплаты через Apple Pay нужно проверить доступен ли Apple Pay на устройстве. Реализуется это так:

Далее с помощью Apple Pay JS API можно проверить есть ли у пользователя активные карты, привязанные к Apple Pay. Предоставляется 2 метода canMakePayments и canMakePaymentsWithActiveCard . Первый проверяет только факт поддержки Apple Pay, второй помимо этого позволяет узнать есть ли по крайней мере 1 карта, привязанная к Apple Pay.

Читайте также:  Яндекс кто звонил с номера для айфона

У нас, например, эти проверки используются для того, чтобы решить показать кнопку оплаты через Apple Pay над остальными способами оплаты или под ними. В случае если добавленных карт нет, выводится кнопка Set Up Apple Pay, по клику открываются настройки телефона с разделом Wallet. В итоге пользователь уходит с сайта, а процесс оплаты прерывать не стоит, поэтому кнопка располагается под основными типами оплаты и даже не видна без скролла экрана.

Страницы оплаты для настроенного и ненастроенного Apple Pay:

Как только кнопка отображена на странице, можно создать платежную сессию для того чтобы отобразить диалог оплаты. Сессия может быть создана только по явному пользовательскому действию. По клику на кнопку нужно выполнить следующий код:

В примере приведен минимальный набор свойств у объекта ApplePayPaymentRequest. Для отображения более подробной информации о покупке нужно использовать другие свойства этого объекта.

Для обработки событий платежной сессии нужно реализовать как минимум следующие методы:

  • onvalidatemerchant срабатывает при открытии платежной формы Apple Pay. В обработчике этого события требуется верифицировать платежную сессию. Процесс верификации описан далее;
  • onpaymentauthorized срабатывает когда пользователь подтверждает платеж на платежной форме Apple Pay с помощью Touch ID, Face ID или кода. Здесь доступен платежный токен, который нужно передать в платежный шлюз для проведения платежа;

После создания объекта ApplePaySession нужно вызвать метод begin для отображения диалога оплаты:

В результате пользователь увидит следующее:

При показе формы срабатывает событие onvalidatemerchant . Для того чтобы продолжить платеж реализуем следующий этап.

Верификация платежной сессии

В параметре события onvalidatemerchant приходит поле validationURL . На этот адрес с бекенда нужно отправить данные, подписанные сертификатом Merchant Identity Certificate.

Метод performValidation возвращает промис от запроса на валидацию. Обработчик этого запроса находится на нашей стороне, реализация такая: на URL из параметра события onvalidatemerchant отправляется post запрос.

В теле запроса содержится json:

Параметры MERCHANT_IDENTIFIER и DISPLAY_NAME берутся из девелоперского аккаунта (их настроили в самом начале), а HOST — это домен, с которого делается оплата.

Запрос должен быть подписан сертификатом Merchant Identity Certificate. В ответе придет json, его и нужно вернуть. После получения этого ответа, вызываем у платежной сессии метод completeMerchantValidation .

Процесс верификации сессии пройден, теперь пользователю требуется подтвердить платеж пальцем или кодом. После этого срабатывает событие onpaymentauthorized . Переходим к этапу проведения платежа.

Проведение платежа

В параметре события onpaymentauthorized содержится объект с платежным токеном, который нужно передать в платежный шлюз. Вся информация, содержащаяся в токене, описана в документации.

Как только платеж проведен, завершаем оплату на стороне клиента.

в success нужно передать один из 2 статусов window.ApplePaySession.STATUS_SUCCESS или window.ApplePaySession.STATUS_FAILURE .

На этом процесс оплаты через Apple Pay заканчивается. Более подробно про Apple Pay JS можно почитать в официальной документации.

Источник

Apple Pay on the Web
Interactive Demo

Try an Apple Pay test transaction using the button below.
Transactions made on this site do not charge your card.

Overview

Use this page to learn how to enable Apple Pay on the web using Apple Pay JS or the Payment Request API. This demo preconfigures the Apple Pay button below with default values. Explore further by modifying values in the code blocks throughout the page to customize payment sheet experiences. This demo displays a transcript of server responses after each transaction for context. Click or tap the the «Show Transcript» tab to view the transaction transcript.

Читайте также:  Не перелистывается экран айфон

As well as letting you try out the Apple Pay JavaScript APIs, this demo can also serve as a tutorial for your own implementation. It assumes you have already set up your environment to process Apple Pay transactions, and are familiar with Apple Pay best practices. Before starting your integration, we recommend reviewing Getting Started with Apple Pay and the Apple Pay on the Web Human Interface Guidelines. For more information about supporting Apple Pay on your website, see Apple Pay on the Web.

This demo generates source code that you can copy into your own project. Click or tap the the «Show Source» tab to view the source code. The demo updates the source code as you change values in the code blocks through the page. Once you are happy with the configuration, click or tap the «Copy» button inside the «Show Source» tab to copy the source code to your clipboard.

Requirements

This demo uses Apple Pay JS version 3, and to run this demo you must be using:

  • iOS devices running iOS 11 or later
  • Safari 11 on macOS 10.13 or later

Display an Apple Pay button

To display an Apple Pay Button, use the following code to load the button script into your webpage from the content delivery network:

The JavaScript Apple Pay button provides a variety of Apple Pay button types that you can use on your website to initiate a transaction. You can specify the Apple Pay button style, type, and localization using attributes. Use CSS to set other properties, such as the size and corner radius. Using the official Apple Pay button element ensures your site will display the latest style, render correctly across devices, and follow Apple Guidelines. For design guidance, see Human Interface Guidelines > Apple Pay > Buttons and Marks.

Try it: Display Settings

Use the following tools to try the different display settings on the button shown below:

Button Corner Radius

Corner Radius: 3px

Button Padding Y

Button Padding Y: 0px

Button Padding X

Button Padding X: 0px

Button Box Sizing

Create a Payment Request

When your customer clicks or taps the Apple Pay button, you must first construct an ApplePaySession object which includes the ApplePayPaymentRequest dictionary detailing the transaction details the payment sheet will display.

The ApplePayPaymentRequest requires details including: the total payment for the transaction, the currency, and the supported payment networks. You can optionally pass lineItems to show additional charges and discounts, and shippingMethods to allow the customer to choose from different shipping options. If you require address or contact details from your customer, request them by passing values in the requiredShippingContactFields or requiredBillingContactFields .

Try it: ApplePayPaymentRequest

Modify the values in the ApplePayPaymentRequest shown below and click or tap the Apple Pay button to view the payment sheet. Choose Basic Request to see a payment sheet with only the required fields. Choose Detailed Request to show code including optional fields, such as lineItems.

Complete Merchant Validation

Before being able to display the payment sheet to the customer, you must generate a valid payment session by interacting with Apple Pay Servers. For security reasons, your server must do this, not your browser client code, unlike everything else in this demo. To start the merchant validation process, call the begin method on the session object you created above.

Читайте также:  Iphone 12 pro max заряд батареи

Once you do, the browser will invoke your onvalidatemerchant handler, which must fetch a merchant session from your server.

Refer to the instructions in Requesting an Apple Pay Payment Session document to implement your server endpoint responsible for fetching the merchant session object from Apple Pay servers. If successful, Apple Pay servers will return a merchant session object, which your server must then pass back as the response to the browser.

Once you have the merchant session response object in the browser, you must complete your onvalidatemerchant handler by passing that object to the completeMerchantValidation method on the session object. The browser will then display the payment sheet.

The following code shows an example of how to validate merchant:

Respond to Payment Sheet Interactions

After merchant validation is complete, Apple Pay provides the information about your customer’s payment sheet selections so that you can calculate the final transaction cost. The final details of a transaction may depend on user payment method, billing address, shipping address, or shipping method. To handle these adjustments, implement the optional handlers onpaymentmethodselected , onshippingmethodselected , and onshippingcontactselected . When the browser calls one of these handlers, you have 30 seconds to process it and call the corresponding callback function, otherwise the transaction times out. All callbacks accept an object with newTotal (required) and newLineItems (optional) keys. In addition, you may specify newShippingMethods to update shipping methods, and errors to indicate problems with the user’s selected shipping address when calling completeShippingContactSelection . You may also call the callbacks with an empty object or null value if the payment sheet needs no changes.

Event Handlers Callback Function Update Structure Update Properties
onpaymentmethodselected completePaymentMethodSelection ApplePayPaymentMethodUpdate newTotal (required)
newLineItems (optional)
onshippingmethodselected completeShippingMethodSelection ApplePayShippingMethodUpdate newTotal (required)
newLineItems (optional)
onshippingcontactselected completeShippingContactSelection ApplePayShippingContactUpdate newTotal (required)
newLineItems (optional)
newShippingMethods (optional)
errors (optional)

Demo Note: The test transaction always passes in a default success response when it calls completePaymentMethodSelection . The test transaction passes in newLineItems and newTotal when it calls completeShippingMethodSelection . See responses in the transcript.

Request a Shipping Address

If you pass requiredShippingContactFields in the payment request with a postalAddress value, Apple Pay provides redacted address information before the user authenticates the transaction. After the user authenticates, Apple Pay provides the full contact information.

The redacted payment information includes only the data needed to complete required transaction tasks, such as calculating taxes or shipping costs, and may differ based on the user’s geographic region.

The following code shows an example of a redacted payment information:

Try it: completeShippingContactSelection

Choose ‘Success’ with or without updating line items and total below. Choose ‘Failure’ to see completeShippingContactSelection response with custom errors. You may edit the ApplePayShippingContactUpdate response object below to experiment with different responses. Click or tap the Apple Pay button below to see how the payment sheet displays updates or address errors.

Источник

Оцените статью