Apple pay payment token

Возможна ли анонимная оплата в Apple Pay?

Конечно, нельзя называть Apple Pay анонимным в принципе, хотя бы потому что к ней привязана наша банковская карта. Однако, в момент оплаты что о нас узнаёт продавец? Какие наши персональные данные получает продавец от Apple Pay? Можно ли избежать передачи данных и, тем самым, сделать оплату анонимной в глазах продавца?

Когда мы полагаем, что оплачиваем через Apple Pay, то можем заблуждаться. В зависимости от того что мы приобретаем, используется один из двух механизмов Apple. При покупке любой материальной услуги действительно применяется Apple Pay. Однако, когда мы приобретаем цифровой контент в экосистеме Apple, применяется In-App Purchase. Заказываете Uber через Apple Pay? Верно, это Apple Pay. Оформляете подписку в Apple Music? Это уже In-App Purchase.

Ниже мы рассказываем, какие данные утекают продавцу при оплате внутри приложений. Мы не стали разбирать ситуацию, когда товар оплачивается через POS-терминал, так как она требует отдельного внимания.

Визуально оба механизма очень похожи, но “под капотом” все иначе.

In-App Purchase

Как уже было сказано выше, данный механизм оплаты используется только для цифрового контента. Электронные книги в Amazon Kindle, дополнительное пространство в Dropbox, скины в PUBG — это всё примеры цифрового контента.

При анализе In-App Purchase выяснилось, что мы анонимны перед продавцом. Некоторая информация о нас все же передается продавцу, но в обезличенном виде. Если мы купим неприличную книгу в LitRes, то разработчики приложения не узнают, что именно мы её приобрели. При условии, что мы не поделились с приложением личной информацией иным путем.

Какие данные передаются продавцу

Ниже представлена таблица, где мы видим какие данные In-App Purchase передает продавцу.

In-App Purchase

Как предотвратить передачу?

Дата первой установки приложения

Список всех сделанных покупок

Биллинговая ошибка на стороне клиента (не хватает денег, карта неактивна)

Дата первой установки приложения

Можно определить, когда мы первый раз скачали приложение, даже если удалим сейчас, но скачаем заново через пол года.

Список всех сделанных покупок

По сути, только дата покупки и что за продукт был приобретен.

Биллинговая ошибка на стороне клиента

Если мы оформим автовозобновляемую подписку, а потом на карте закончатся деньги или карта будет неактивной, то разработчик узнает об этом.

Технические подробности

Приложение предлагает пользователю какой-то контент.

Пользователь инициирует процесс покупки.

Приложение показывает ему окно для совершения транзакции.

После подтверждения приложение какое-то время думает.

В это время в приложении происходит целая череда событий. Большая часть из них скрыта внутри самой операционной системы, а именно системной библиотеки StoreKit. В результате покупки разработчик получит специальную строку receipt .

receipt нужен для того, чтобы приложение смогло проверить, действительно ли пользователь совершил эту покупку. Обычно приложение передает эту строку на свой бекенд, а тот — в Apple, чтобы проверить покупку. Apple в ответ на запрос пришлет JSON. Он то нам и нужен:

Читайте также:  Айфон боковая кнопка звука

Чтобы определить дату первой установки, в JSON необходимо найти поле original_purchase_date. Это просто дата, когда приложение было скачано тем самым iTunes аккаунтом, через который совершается покупка.

Поле in_app даст информацию о почти всех покупках, совершенных с этого iTunes аккаунта. Почти, потому что в нем не хранится информация о всех consumable покупках, только о текущей (как в примере выше). Consumable покупки — это покупки, которые можно совершать любое число раз, например, наборы монеток или кристаллов, за которые в приложении можно купить что-то. Все остальные покупки будут всегда храниться в этом поле. Причем, что интересно, если мы сделаем возврат покупки через Apple, то это действие также отобразится в этом массиве. То есть, когда мы в следующий раз придем покупать или восстанавливать покупку, разработчик может узнать не только как часто мы покупаем, но и как часто отменяем покупку.

О нехватке баланса на карте можно будет узнать только в случае продления автовозобновляемой подписки. Эту информацию можно получить через App Store Server Notifications. Это система нотификаций от App Store, на которую подписывается бекенд и может обрабатывать разного рода сообщения. В конкретном случае нас интересует событие DID_FAIL_TO_RENEW

Apple Pay

Просто напомню, что Apple Pay предназначен для материальных товаров и услуг. Примерами могут быть: доставка еды в UberEATS, аренда дома в Airbnb, авиабилеты в Skyscanner.

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

Какие данные передаются продавцу

Ниже представлена таблица, где мы видим какие данные Apple Pay передает продавцу.

До подтверждения оплаты

В момент, когда у нас выскакивает шторка с просьбой подтвердить оплату, продавец уже получает о нас информацию.

Поле

Значение

Как предотвратить передачу?

Примерный адрес доставки пользователя

Страна, область, город, почтовый индекс

Исказить или убрать в iOS. Настройки iOS → Wallet и Apple Pay → Параметры оплаты по умолчанию

Примерный платежный адрес пользователя (если не запрошен адрес доставки)

Страна, область, город, почтовый индекс

Исказить или убрать в iOS. Приложение Wallet → Карта → Настройки → Адрес плательщика [1]

Информация о банке эмитенте карты (при наличии договоренности между разработчиком и банком)

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

Как только мы подтверждаем оплату с помощью Face ID, Touch ID или пароля, продавец получает новую порцию данных.

Поле

Значение

Как предотвратить передачу?

Название карты с последними символами реальной карты

Точный адрес доставки пользователя

Страна, область, город, почтовый индекс, улица, дом, квартира

До подтверждения оплаты исказить текст в самой шторке

Точный платежный адрес пользователя

Страна, область, город, почтовый индекс, улица, дом, квартира

Исказить или убрать в iOS. Приложение Wallet → Карта → Настройки → Адрес плательщика [1]

Исказить или убрать в iOS. Находится там же, где и адрес доставки или платежный адрес.

1. Либо до подтверждения оплаты исказить текст в самой шторке

2. Либо исказить/убрать в iOS. Настройки → Wallet и Apple Pay → Параметры оплаты по умолчанию [2]

От банка-эквайера

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

Поле

Значение

Как предотвратить передачу?

Читайте также:  Характеристики apple earpods 2019

Источник

Apple pay payment token

Developer

Apple Pay Programming Guide

Authorizing Payments

The payment authorization process is a cooperative effort between the payment authorization view controller and its delegate. A payment authorization view controller does two things: It lets the user select the billing and shipping information that is needed by a payment request, and it lets the user authorize the payment to be made. The delegate methods are called when the user interacts with the view controller so that your app can update the information shown—for example, to update the shipping price when a shipping address is selected. The delegate is also called after the user authorizes the payment request.

As you implement the delegate methods, remember that they can be called multiple times and that the order in which they are called depends on the order of the user’s actions.

All of the delegate methods called during the authorization process are passed a completion block as one of their arguments. The payment authorization view controller waits for its delegate to finish responding to one method (by calling the completion block) before it calls any other delegate methods. The paymentAuthorizationViewControllerDidFinish: method is the only exception: It doesn’t take a completion block, and it can be called at any time.

The completion blocks take an argument that lets you specify the current status of the transaction based on the information that’s available. If there are no problems with the transaction, you pass the value PKPaymentAuthorizationStatusSuccess ; otherwise, you pass a value that identifies the problem.

To create an instance of the PKPaymentAuthorizationViewController class, pass the payment request to the view controller’s initializer. Set a delegate for the view controller, and then present it.

The PKPaymentAuthorizationController class performs the same role as the PKPaymentAuthorizationViewController class, but it does not depend on the UIKit framework. This means that the authorization controller can be used in places where a view controller cannot (for example, in watchOS apps or in Intents extensions).

To use the PKPaymentAuthorizationController class, assign an object that adopts the PKPaymentAuthorizationControllerDelegate protocol as a delegate, and call the presentWithCompletion: method to present a payment sheet. When you are done, call the dismissWithCompletion: method to dismiss the payment sheet. Otherwise, the APIs are identical.

  1. PKPaymentAuthorizationViewController * viewController = [[ PKPaymentAuthorizationViewController alloc ] initWithPaymentRequest: request ];
  2. if ( ! viewController ) < /* . Handle error . */ >
  3. viewController . delegate = self ;
  4. [ self presentViewController: viewController animated: YES completion: nil ];

As the user interacts with the view controller, the view controller calls its delegate methods.

In Xcode 7.0 or later, you can test the payment authorization view controller in the simulator. It provides simulated cards for all the supported payment networks and returns dummy payment data in plain text. On a device, this data is encrypted with your merchant identifier and must be decrypted either on your server or by your payment processor.

Use the Apple Pay Sandbox environment to test your app on a device with test cards.

Although these techniques provide fast and convenient ways to test your code, you still need to thoroughly test Apple Pay on actual, physical devices with production cards.

Your Delegate Updates Shipping Methods and Costs

When the user provides shipping information, the authorization view controller calls your delegate’s paymentAuthorizationViewController:didSelectShippingContact:completion: and paymentAuthorizationViewController:didSelectShippingMethod:completion: methods. Use these methods to update the payment request based on the new information.

  1. — ( void ) paymentAuthorizationViewController: ( PKPaymentAuthorizationViewController * ) controller
  2. didSelectShippingContact: ( CNContact * ) contact
  3. completion: ( void ( ^ )( PKPaymentAuthorizationStatus , NSArray * , NSArray * )) completion
  4. <
  5. self . selectedContact = contact ;
  6. [ self updateShippingCost ];
  7. NSArray * shippingMethods = [ self shippingMethodsForContact: contact ];
  8. completion ( PKPaymentAuthorizationStatusSuccess , shippingMethods , self . summaryItems );
  9. >
  10. — ( void ) paymentAuthorizationViewController: ( PKPaymentAuthorizationViewController * ) controller
  11. didSelectShippingMethod: ( PKShippingMethod * ) shippingMethod
  12. completion: ( void ( ^ )( PKPaymentAuthorizationStatus , NSArray * )) completion
  13. <
  14. self . selectedShippingMethod = shippingMethod ;
  15. [ self updateShippingCost ];
  16. completion ( PKPaymentAuthorizationStatusSuccess , self . summaryItems );
  17. >
Читайте также:  Код пароль iphone где его вводить

To maintain privacy, the shipping information provided in paymentAuthorizationViewController:didSelectShippingContact:completion: is anonymized. The returned contact contains enough information to calculate shipping costs, without revealing sensitive information about the user. You do not get the user’s full shipping information until after the user approves the payment. Additionally, the data available in the contact changes from country to country, and can change from release to release. Be sure to test your app appropriately.

A Payment Token Is Created When a Payment Is Authorized

When the user authorizes a payment request, the framework creates a payment token by coordinating with Apple’s server and the Secure Element. You send this payment token to your server in the paymentAuthorizationViewController:didAuthorizePayment:completion: delegate method, along with any other information you need to process the purchase—for example, the shipping address and a shopping cart identifier. The process happens as follows:

The framework sends the payment request to the Secure Element. Only the Secure Element has access to the tokenized device-specific payment card numbers.

The Secure Element puts together payment data for the specified card and merchant, encrypts it so that only Apple can read it, and sends it to the framework. The framework then sends the payment data to Apple’s server.

Apple’s server reencrypts the payment data using your Payment Processing certificate. The token can only be read by you and the people with whom you have shared your Payment Processing certificate. The server then signs the payment token, and returns it to the device.

The framework passes the token to your delegate by calling its paymentAuthorizationViewController:didAuthorizePayment:completion: method. Your delegate sends the token to your server.

The actions on your server vary depending on whether you process your own payments or work with a payment platform. In both cases, your server handles the order and sends a status back to the device, which your delegate passes to its completion handler, as described in Processing Payments .

  1. — ( void ) paymentAuthorizationViewController: ( PKPaymentAuthorizationViewController * ) controller
  2. didAuthorizePayment: ( PKPayment * ) payment
  3. completion: ( void ( ^ )( PKPaymentAuthorizationStatus )) completion
  4. <
  5. NSError * error ;
  6. ABMultiValueRef addressMultiValue = ABRecordCopyValue ( payment . billingAddress , kABPersonAddressProperty );
  7. NSDictionary * addressDictionary = ( __bridge_transfer NSDictionary * ) ABMultiValueCopyValueAtIndex ( addressMultiValue , 0 );
  8. NSData * json = [ NSJSONSerialization dataWithJSONObject: addressDictionary options: NSJSONWritingPrettyPrinted error: & error ];
  9. // . Send payment token, shipping and billing address, and order information to your server .
  10. PKPaymentAuthorizationStatus status ; // From your server
  11. completion ( status );
  12. >

Your Delegate Dismisses the Payment Authorization View Controller

After the framework displays the transaction’s status, the authorization view controller calls your delegate’s paymentAuthorizationViewControllerDidFinish: method. In your implementation, dismiss the authorization view controller and then display your own app-specific order-confirmation page.

Источник

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