Introduction
Apple Pay is a mobile payment service provided by Apple. When a user registers their credit/debit card with Apple Pay, it generates a token for that device, a Device Account Number (DAN). All the purchases then are carried out using this token; when card information is shared across the wire, it is not the actual card number. This ensures that the actual card information is safe. In addition, Apple also supports phone safety by using touch ID or using a phone’s passcode. This article describes the steps to integrate Apple Pay with the Xamarin iOS.
Description
In this example, we will build the app in Xamarin forms and platform-specific code for ApplePay in Xamarin iOS. First, create a Xamarin forms application named “ApplePaySample,” as shown in Figure 1. It creates a Xamarin forms project named “ApplePaySample” and platform-specific projects named “ApplePaySample.iOS.”
Figure 1: Creating a Xamarin forms application
Now, add a PCL library Project to the solution, named “ApplePaySampleLib” (see Figure 2). Add a class file and create an interface named “IApplePayAuthorizer.” Add a method signature named “AuthorizePayment.”
Figure 2: Adding a PCL library Project
1. namespace ApplePaySampleLib 2. { 3. public interface IApplePayAuthorizer 4. { 5. bool AuthorizePayment() 6. } 7. }
iOS level implementation will be invoked from Xamarin forms using dependency injection.
Changes in the Xamarin Forms Project
Now, add the reference of the ‘ApplePaySampleLib‘ project to the Xamarin Forms and iOS project. For this example, we are using FreshMVVM. Add the FreshMVVM NuGet package, as shown in Figure 3:
Figure 3: Adding the FreshMVVM NuGet package
Open ‘App.Xaml.cs‘ and register the “IApplePayAuthorizer” interface.
1. FreshIOC.Container.Register(DependencyService. Get<IApplePayAuthorizer>()); 2. var mainNavigationContainer = new FreshNavigationContainer(FreshPageModelResolver. ResolvePageModel< "ApplePaySamplePage"); 3. MainPage = mainNavigationContainer;
Line 1 registers the interface with the container for dependency injection. Line 2 resolves the page model for the landing page, and Line 3 assigns it to the main page.
Add a new ‘Forms ContentPage Xaml’ named “ApplePaySamplePage.xaml” and add the following code to a add the Apple Pay button:
1. <Button Command="{Binding ApplePayCommand}" Image="ApplePayBTN_32pt__black_logo_@2x.png"/>
Add a new class file named “AppPaySamplePageModel” and inherit it from ‘FreshBasePageModel.’ The page model code is as follows:
1. public class ApplePaySamplePageModel : FreshBasePageModel 2. { 3. IApplePayAuthorizer _applePayAuthorizer; 4. public ApplePaySamplePageModel (IApplePayAuthorizer applePayAuthorizer) 5. { 6. _applePayAuthorizer = applePayAuthorizer; 7. } 8. public ICommand ApplePayCommand { get; set; } 9. public override void Init( initData) 10. { 11. base.Init(initData); 12. ApplePayCommand = new Command(async () => await OnApplePayClick()); 13. } 14. private async Task<bool> OnApplePayClick() 15. { 16. return _applePayAuthorizer.AuthorizePayment(); ; 17. } 18. }
Line 4 is an example of dependency injection in a constructor; here, ‘applePayAuthorizer’ is injected as a parameter to the constructor. Line 8 declares the command object and Lines 14-17 invoke the AuthorizerPayment method, which is defined at the iOS level.
Platform Level Changes
In the ‘ApplePaySample.iOS’ project, add a class file that will be the dependency service and ‘AuthorizePayment’ method.
1. [assembly: Xamarin.Forms.Dependency(typeof(ApplePayAuthorizer))] 2. namespace ApplePaySample.iOS 3. { 4. public class ApplePayAuthorizer: PKPaymentAuthorizationViewControllerDelegate, IApplePayAuthorizer 5. { 6. void HandleAction() 7. { 8. } 9. public ApplePayAuthorizer() 10. { 11. } 12. public bool AuthorizePayment() 13. { 14. NSString[] paymentNetworks = new NSString[] { PKPaymentNetwork.Visa, PKPaymentNetwork.MasterCard, PKPaymentNetwork.Amex }; 15. var merchantID = "merchant.com.Companyxxx.Appxxx"; // Enter merchant ID registered in apple.developer.com 16. PKPaymentRequest paymentRequest = new PKPaymentRequest(); 17. paymentRequest.MerchantIdentifier = merchantID; 18. paymentRequest.SupportedNetworks = paymentNetworks; 19. paymentRequest.MerchantCapabilities = PKMerchantCapability.ThreeDS; 20. paymentRequest.CountryCode = "US"; 21. paymentRequest.CurrencyCode = "USD"; 22. paymentRequest.PaymentSummaryItems = new PKPaymentSummaryItem[]{ new PKPaymentSummaryItem(){ Label = "Sample Purchase Item" , Amount = new NSDecimalNumber("100") } }; 23. PKPaymentAuthorizationViewController controller = new PKPaymentAuthorizationViewController(paymentRequest); 24. controller.Delegate = (PassKit.IPKPaymentAuthorization ViewControllerDelegate)Self; 25. var rootController = UIApplication.SharedApplication. KeyWindow.RootViewController; 26. rootController.PresentViewController(controller, true, null); 27. return false; 28. } 29. public override void DidAuthorizePayment(PKPaymentAuthorization ViewController controller, PKPayment payment, Action<PKPaymentAuthorizationStatus> completion) 30. { 31. completion(PKPaymentAuthorizationStatus.Success); 32. } 33. public override void PaymentAuthorizationViewControllerDidFinish (PKPaymentAuthorizationViewController controller) 34. { 35. controller.DismissViewController(true, null); 36. } 37. public override void WillAuthorizePayment(PKPaymentAuthorization ViewController controller) 38. { 39. throw new NotImplementedException(); 40. } 41. } 42. }
Line 1 is the decorator for the dependency service. Line 4 defines the class that inherits from PKPaymentAuthorizationViewControllerDelegate and IAppAuthorize.
PKPaymentAuthorizationViewControllerDelegate has two important methods, “DidAuthorizePayment” and “PaymentAuthorizationViewControllerDidFinsh.” Lines 29-32 are executed when payment authorization is completed. Lines 33-36 define the method that closes the Apple Pay window.
Lines 12-28 define the ‘AuthorizePayment‘ method. Lines 16-21 define the ‘PaymentRequest’ that contains information of the merchant ID, supported payment networks, merchant capabilities, country code, and currency code.
Line 22 defines the item summary and the amount. Line 23 creates an object of the view controller ‘PKPaymentAuthorizationViewController‘ which displays the Apple payment window. Line 25 gets the root controller of the current application and Line 26 opens the ‘PKPaymentAuthorizationViewController‘ in the current window. Now the user can select a card from the registered set of cards and complete the payment.
In Lines 30-32, specify the code that will store the token received from the payment processor in the app database.
Summary
In this article, we covered the basic code required to integrate Apple Pay with Xamarin forms using PassKit APIs. Apple Pay is supported by many banks and payment processors and the details are available at the Apple Web site. Apple also provides test cards to validate the success and the error scenarios.