Adding Apple Pay to your store

Dylan Mckee profile picture Written by: Dylan Mckee - Published on: 21 Jan 2016
The Moltin iOS SDK allows you to easily add Apple Pay to your mobile eCommerce store, so you can sell to customers seamlessly using a fully native payment method that they’re extremely familiar with.

In this post, we’ll be taking you through the process of adding Apple Pay to you Moltin store in Swift. If you haven’t created a store yet, you can check out our previous tutorial on creating a Moltin store in Swift.

Requirements

Setting up dependencies

Firstly, ensure that you have a Moltin store set up with a product in (so that you can buy something in the tutorial app), and linked to a Stripe payment gateway.

Next, head over to the Apple Developer Portal, click on the Merchant IDs section, and add a merchant ID for your app (it needs to be something unique) and click Register - once you’ve registered successfully, it should look something like this…

Now, head to theStripewebsite and sign in to your dashboard. Click Your Account and navigate to the Apple Pay tab, click Create New Certificate and follow their instructions to upload the file they provide you with to the Apple Developer Portal. Once you’ve done that, your Stripe dashboard should look like this:

The next step is to create a new blank Xcode project. Navigate to the Targets section, find your current target, select the Capabilities tab, and switch on Apple Pay, then tick the checkbox next to the merchant ID you registered before - like so…

Now, let’s get started on creating the app!

Setting up your project

The first thing to do is set up your Xcode project using CocoaPods to install the dependencies needed. Open a new Terminal window in the same directory as your Xcode project and run the pod init command. Now, open the Podfile in a text editor and add the following lines:

  use_frameworks!
pod 'Moltin'
pod 'Stripe'
pod 'Stripe/ApplePay'

Your Podfile should end up looking like this…

Now, head back to your terminal window and run pod install, then open the .xcworkspace file that gets created.

Once you’ve done this, go to File > New > File, then select ‘Header File’, call it BridgingHeader. Then, go to your target’s Build Settings, search for Objective-C Bridging Header, and then type BridgingHeader.h. Your setup should now look like the one shown in the screenshot below…

Next, head to BridgingHeader.h and add the lines:

  #import <Moltin/Moltin.h>
#import <Stripe/Stripe.h>
#import <Stripe/Stripe+ApplePay.h>

Your bridging header file should end up looking like the one below…

Now, you’re ready to start using our iOS SDK in your Swift code for Apple Pay!

Next, get your store’s Client ID (you’ll need a Moltin account and store) - you’ll need to include these in the app in the next step of this tutorial. Also, ensure that you create some mock products in your store so that you can see them in your iOS app.

Setting up the SDK

Head to the ViewController.swift file in your Xcode project and import the Moltin SDK and Stripe by adding these lines at the top of the file:

  import Moltin
import PassKit
import Stripe

Then, in the viewDidLoad function in that file add:

  Moltin.sharedInstance().setPublicId("YOUR_STORE_ID")
Stripe.setDefaultPublishableKey("YOUR_KEY")

Replace YOUR_STORE_ID with the Moltin client ID of your store. This initializes the Moltin SDK for use with your Moltin store. You’ll also need to replace YOUR_KEY with the publishable key from your Stripe Dashboard.

Creating our Buy button

Now we’re going to add the ‘buy’ button. When tapped, this button will add an item to your cart, checkout and then pay via Apple Pay. In a production app, you’d have product lists and a full cart/checkout flow (like in our Swift and Objective-C example apps), but for the purposes of this tutorial, we’ll just have one button that does all three steps.

First, add the following code to your ViewController.swift file to create a buyButtonTapped function that will be called when our buy button is tapped…

  @IBAction func buyButtonTapped() {

}

Now, head to the Main.storyboard file and add a button, connected to the buyButtonTapped() function ‘on touch down’, like so…

Then, implement the buyButtonTapped() method to get an item from your store, add it to the cart, and start the check-out process. To do this, add the following code in the buyButtonTapped() method…

  Moltin.sharedInstance().product.listingWithParameters(nil, success: { (response) -> Void in
    // The array of products is at the "result" key
    let objects = response["result"]! as! [AnyObject]
    
    // Let's buy the first product we come to...
    if let productToBuy = objects.first {
  let productId:String = productToBuy["id"] as! String
  
  // Add it to the cart...
  Moltin.sharedInstance().cart.insertItemWithId(productId, quantity: 1, andModifiersOrNil: nil, success: { (response) -> Void in
      // Added to cart - now let's check-out!
      print("Added \(productId) to the cart - now going to check-out")
      self.checkOut()
      }, failure: { (response, error) -> Void in
          print("Something went wrong! \(error)")

  })
  
    }
    
    }, failure: { (response, error) -> Void in
  print("Something went wrong! \(error)")
})

Now, let’s create the checkOut() function mentioned previously, and get started with using Apple Pay to check-out…

Checking out the Moltin cart with Apple Pay

Now we’ve got the add to cart code implemented, the next stage is to set up the checkout procedure to integrate with Apple Pay.

In your production iOS apps, you’ll be offering beautiful checkout interfaces where users can enter their details elegantly (you can see an example of what we suggest in our iOS Example App project on GitHub), but in this example, we’re going to hard-code the checkout details into the app to keep the tutorial as easy to follow as possible.

First, we’ll create a function called checkOut(), and perform an Apple Pay payment via the PKPayment class - this is how your check out function should look…

  func checkOut() {
    let request = PKPaymentRequest()
    
    // Moltin and Stripe support all the networks!
    let supportedPaymentNetworks = [PKPaymentNetworkVisa, PKPaymentNetworkMasterCard, PKPaymentNetworkAmex]
    
    // TODO: Fill in your merchant ID here from the Apple Developer Portal
    let applePaySwagMerchantID = "YOUR_MERCHANT_ID_HERE"
    
    request.merchantIdentifier = applePaySwagMerchantID
    request.supportedNetworks = supportedPaymentNetworks
    request.merchantCapabilities = PKMerchantCapability.Capability3DS
    request.requiredShippingAddressFields = PKAddressField.All
    request.requiredBillingAddressFields = PKAddressField.All

    // TODO: Change these for your country!
    request.countryCode = "GB"
    request.currencyCode = "GBP"
    
    // In production apps, you'd get this from what's currently in the cart, but for now we're just hardcoding it
    request.paymentSummaryItems = [
  PKPaymentSummaryItem(label: "Moltin Swag", amount: 0.53)
    ]
    
    let applePayController = PKPaymentAuthorizationViewController(paymentRequest: request)
    applePayController.delegate = self
    self.presentViewController(applePayController, animated: true, completion: nil)

    
}

This causes an Apple Pay sheet to be shown asking the user for billing information and shows the total amount payable. In a production app, you’ll also want to calculate the total amount payable/item details and price here from the cart, and add shipping options to select, but for the sake of simplicity in this tutorial, we’re just hardcoding this data in. You’ll have to replace YOUR_MERCHANT_ID_HERE with the merchant ID that you created previously in the Apple Developer Portal.

Now, we’ll implement the PKPaymentAuthorizationViewControllerDelegate protocol so that we can receive callbacks and checkout with Moltin once the Apple Pay payment is confirmed.

To do this, add PKPaymentAuthorizationViewControllerDelegate next to UIViewController at the top of your ViewController class, and implement the methods below…

  func paymentAuthorizationViewController(controller: PKPaymentAuthorizationViewController, didAuthorizePayment payment: PKPayment, completion: ((PKPaymentAuthorizationStatus) -> Void)) {
    // Payment authorized, now send the data to Stripe to get a Stripe token...
    
    Stripe.createTokenWithPayment(payment) { (token, error) -> Void in
  let tokenValue = token?.tokenId
  // We can now pass tokenValue up to Moltin to charge - let's do the Moltin checkout.
  
  // TODO: Enter your store's default shipping option slug (if it's not 'free_shipping')!
  var orderParameters = [
      "shipping": "free_shipping",
      "gateway": "stripe",
      "ship_to": "bill_to"
      ] as [String: AnyObject]
  
  // In production apps, these values should be checked/validated first...
  var customerDict = Dictionary<String, String>()
  customerDict["first_name"] = payment.billingContact!.name!.givenName!
  customerDict["last_name"] = payment.billingContact!.name!.familyName!
  customerDict["email"] = payment.shippingContact!.emailAddress!
  orderParameters["customer"] = customerDict
  
  var billingDict = Dictionary<String, String>()
  billingDict["first_name"] = payment.billingContact!.name!.givenName!
  billingDict["last_name"] = payment.billingContact!.name!.familyName!
  billingDict["address_1"] = payment.billingContact!.postalAddress!.street
  billingDict["city"] = payment.billingContact!.postalAddress!.city
  billingDict["country"] = payment.billingContact!.postalAddress!.ISOCountryCode.uppercaseString
  billingDict["postcode"] = payment.billingContact!.postalAddress!.postalCode
  orderParameters["bill_to"] = billingDict

  Moltin.sharedInstance().cart.orderWithParameters(orderParameters, success: { (response) -> Void in
      // Order successful
      print("Order succeeded: \(response)")
      
      // Extract the Order ID so that it can be used in payment too...
      let orderId = (response as NSDictionary).valueForKeyPath("result.id") as! String
      
      print("Order ID: \(orderId)")
      
      // Now, pay using the Stripe token...
      let paymentParameters = ["token": tokenValue!] as [NSObject: AnyObject]
      
      Moltin.sharedInstance().checkout.paymentWithMethod("purchase", order: orderId, parameters: paymentParameters, success: { (response) -> Void in
          // Payment successful...
          print("Payment successful: \(response)")
          completion(PKPaymentAuthorizationStatus.Success)

          }, failure: { (response, error) -> Void in
              // Payment error
              print("Payment error: \(error)")
              completion(PKPaymentAuthorizationStatus.Failure)

      })
      
      }, failure: { (response, error) -> Void in
          // Order failed
          print("Order error: \(error)")
          completion(PKPaymentAuthorizationStatus.Failure)

  })
  
    }
    
}
    
func paymentAuthorizationViewControllerDidFinish(controller: PKPaymentAuthorizationViewController) {
    controller.dismissViewControllerAnimated(true, completion: nil)
}

This code sends the Apple Pay token to Stripe, then gets a Stripe token, which is then passed to Moltin where the checkout and payment is completed and the contact details selected in the Apple Pay sheet are used as the user’s billing/shipping details for the Moltin checkout process - no typing or further user input required! In production, you’d want to perform some error checking/validation where mentioned, but for simplicity, we’re just assuming the user selects enough valid data at the Apple Pay sheet.

If you run the app in the Simulator, you should see the following screenshot when you tap the buy button…

And if you run it on your device, you should be able to go ahead and make a real purchase!

Congratulations - you’ve just built Apple Pay into your Swift eCommerce app with Moltin! For a more thorough example that include a cart, collections, checkout flow and more, why not take a look at our Example Swift App our Example Objective-C app.

You can check out the source code for this tutorial project on GitHub.

Build something amazing with Moltin