Apple pay button demo

Подключаем оплату через 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 iphone 16gb

Страницы оплаты для настроенного и ненастроенного 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 button demo

The system provides several Apple Pay button types and styles you can use in your app or website. In contrast to the Apple Pay buttons, you use the Apple Pay mark to communicate the availability of Apple Pay as a payment option.

Don’t create your own Apple Pay button design or attempt to mimic the system-provided button designs.

Button Types

Apple provides several types of buttons so that you can choose the button type that fits best with the terminology and flow of your purchase or payment experience.

Use the Apple-provided APIs to create Apple Pay buttons. When you use the system-provided APIs, you get:

  • A button that is guaranteed to use an Apple-approved caption, font, color, and style
  • Assurance that the button’s contents maintain ideal proportions as you change its size
  • Automatic translation of the button’s caption into the language that’s set for the device
  • Support for configuring the button’s corner radius to match the style of your UI
  • A system-provided alternative text label that lets VoiceOver describe the button
Payment button type Example usage
An area in an app or website where people can make a purchase, such as a product detail page or shopping cart page.
An app or website that lets people pay bills or invoices, such as those for a utility — like cable or electricity — or a service — like plumbing or car repair.
An app or website offering a shopping cart or purchase experience that includes other payment buttons that start with the text Check out.
An app or website offering a shopping cart or purchase experience that includes other payment buttons that start with the text Continue with.
An app or website that helps people book flights, trips, or other experiences.
An app or website for an approved nonprofit that lets people make donations.
An app or website that lets people purchase a subscription, such as a gym membership or a meal-kit delivery service.
An app or website that uses the term reload to help people add money to a card, account, or payment system associated with a service, such as transit or a prepaid phone plan.
An app or website that uses the term add money to help people add money to a card, account, or payment system associated with a service, such as transit or a prepaid phone plan.
An app or website that uses the term top up to help people add money to a card, account, or payment system associated with a service, such as transit or a prepaid phone plan.
An app or website that lets people place orders for items like meals or flowers.
An app or website that lets people rent items like cars or scooters.
An app or website that uses the term support to help people give money to projects, causes, organizations, and other entities.
An app or website that uses the term contribute to help people give money to projects, causes, organizations, and other entities.
An app or website that lets people tip for goods or services.
An app or website that has stylistic reasons to use a button that can have a smaller minimum width or that doesn’t specify a call to action. If you choose a payment button type that isn’t supported on the version of the operating system your app or website is running in, the system may replace it with this button.

When a device supports Apple Pay, but it hasn’t been set up yet, you can use the Set up Apple Pay button to show that Apple Pay is accepted and to give people an explicit opportunity to set it up.

You can display the Set up Apple Pay button on pages such as a Settings page, a user profile screen, or an interstitial page. Tapping the button in any of these locations should initiate the process of adding a card.

Button Styles

Beginning in iOS 14 and macOS 11, you can use the automatic style to let the current system appearance determine the appearance of the Apple Pay buttons in your app (for developer guidance, see PKPaymentButtonStyle.automatic). If you want to control the button appearance yourself, you can use one of the following options. For web developer guidance, see ApplePayButtonStyle.

Black

Use on white or light-color backgrounds that provide sufficient contrast. Don’t use on black or dark backgrounds.

Источник

Apple pay button demo

Apple Pay is a secure, easy way to make payments for physical goods and services — as well as donations and subscriptions — in apps running on iPhone, iPad, Mac, and Apple Watch, and on websites. People authorize payments and provide shipping and contact information, using credentials that are securely stored on the device.

TIP It’s important to understand the difference between Apple Pay and In-App Purchase. Use Apple Pay in your app to sell physical goods like groceries, clothing, and appliances; for services such as club memberships, hotel reservations, and tickets for events; and for donations. Use In-App Purchase in your app to sell virtual goods, such as premium content for your app, and subscriptions for digital content.

Apple Pay in Apps

Apps that accept Apple Pay display an Apple Pay mark wherever available payment options are shown and an Apple Pay button that people tap to bring up a payment sheet. During checkout, the payment sheet can show the credit or debit card linked to Apple Pay, purchase amount (including tax and fees), shipping options, and contact information. People make any necessary adjustments and then authorize payment and complete the purchase.

For developer guidance, see PassKit > Apple Pay.

Apple Pay on the Web

Websites that accept Apple Pay incorporate it into the purchasing flow. An Apple Pay mark should be shown wherever available payment options are shown and an Apple Pay button can be clicked to bring up a payment sheet. During checkout, the payment sheet can show the credit or debit card linked to Apple Pay, purchase amount (including tax and fees), shipping options, and contact information. People make any necessary adjustments, authorize payment, and complete the purchase using securely stored credentials on iPhone, iPad, and Macs that include Touch ID or a Magic Keyboard with Touch ID (for a complete list of supported Macs, see Apple Pay is compatible with these devices). On other Macs, people confirm the purchase with their nearby iPhone or Apple Watch that has Apple Pay enabled.

All websites that offer Apple Pay must include a privacy statement and adhere to the Apple Pay on the Web Acceptable Use Guidelines. For developer guidance, see Apple Pay on the Web. For a hands-on demo of Apple Pay on the web, see Apple Pay on the Web Demo.

Источник

Apple pay button demo

Apple Pay Example Project

This is a basic application that we used to test the Apple Pay production environment.

After studying documentations and seeing some github projects, we discovered that it was not so easy, so we choose to share this repository and thus help other developers.

We use CIELO as payment provider, a brazilian payment company.

Creat a Merchant ID in your Apple Developer area

Go to the Identifier and creat your Merchant ID. Afther this, you will have an Identifier name like: com.domainname.appname .

The Apple Pay Payment Processing Certificate

You need to send your Merchant ID to your payment provider and then you will receive from then a .CSR or a .certSigningRequest file.

If you receive a .PEM file, rename the extension to .CSR and upload the certificate in the Payment Processing Certificate area.

Click twice at the certificate file to install then in your Keychain locally.

The Apple Pay Merchant Certificate

DON’T USE THE APPLE DOCS to create this certificate. In ther documentation, they create a basic certificate without a private key. WE NEED a private key for the production environment.

The correct way is creating the certificate by the Keys section of your Keychain Access.

Name the certificate as merchant_id.cer . Click twice to install the certificate to your Keychain and then export this certificate as a .p12 file, like: merchant_id.p12 . If it asks you to pick a passphrase, you can just leave it blank since we’ll be removing it in a second anyway.

Now we’ll convert from a .p12 file into a .pem file. Run this command in your terminal:

You only’ll need the .PEM certificate in your server.

The Merchant Domain

To test locally, you need a HTTPS host, so the best way is using the ngrok app. Install ngrok app and run in a new terminal tab:

In another terminal tab, install and run this project:

And access the generated ngrok HTTPS url.

We use Node v8.9.1 to run this example.

A special thanks to Tom Dale that help us a lot with their Apple Pay Merchant Session Server.

Источник

Читайте также:  Клавиатурный тренажер для iphone
Оцените статью