DEV Community

Cover image for FusionPayments: Part I - Integrate Apple Pay SDK
SCADE for Developers
SCADE for Developers

Posted on • Edited on

FusionPayments: Part I - Integrate Apple Pay SDK

Introduction

Hi everyone 🙋🏻‍♂️! My name is Vedant, and this time we are going to explore another Fusion library, FusionPayments. This is part 1 of the article which explains how to integrate Apple Pay. Apple Pay is a mobile payment and digital wallet service by Apple Inc. that allows users to make payments in person, in iOS apps, and on the web. Integrating Apple Pay into a website or application can provide a seamless and secure payment experience for customers.

In this article, we will discuss how to create a Fusion library for payments, the steps involved in integration, and the requirements for integrating Apple Pay into a website or application. Overall, this article aims to provide a comprehensive guide for developers and businesses looking to integrate Apple Pay into their payment systems, and later on, will integrate Google Pay for Android-specific devices.

Benefits of Cross-Platform(SCADE + Fusion) SDKs

  1. Cost-effective: Cross-platform SDKs allow developers to write code once and use it on multiple platforms, reducing the time and cost of development.
  2. Consistent User Experience: Cross-platform SDKs provide a consistent user experience across different platforms, which enhances the overall user experience and helps to build brand recognition.
  3. Reach a wider audience: By developing SDKs for multiple platforms, a business can reach a wider audience and expand its customer base.
  4. Easier Maintenance: Cross-platform SDKs make it easier to maintain and update the code, as changes can be made in one place and then applied to all platforms. Access to
  5. Native Features: Cross-platform SDKs provide access to native features of different platforms, allowing for enhanced functionality and better performance.
  6. Faster Time-to-Market: Cross-platform development enables businesses to launch their applications faster, as they don't have to develop separate versions for each platform.

Fusion SDK

Recently, the SCADE team has gone open-source with their breakthrough technology called Fusion libraries. Fusion enables us to invoke the Android APIs using the SCADE Fusion SDK. The benefit is that we don’t have to bother about setting up the Android platform-specific stuff in the gradle or anywhere. Even iOS-specific settings are very straightforward and no further prerequisite is required.

SCADE swift codebase acts as the single source of truth in this case, and Fusion SDK makes it possible. Currently, Fusion SDK provides easy integrations for the Geolocation, Bluetooth, NFC, and Media Player, and many more Fusion libraries are in development by the SCADE developers.

Image description

Understand FusionPayments Implementation!

You can check the codebase of FusionPayments here. It is open-source and you are most welcome to contribute to the Fusion repository to add more features.

You need to first understand the protocol of FusionPayments. It contains the method initiatePayment which accepts the PaymentRequest object and returns the callback function for PaymentStatus and PaymentSheet view state.

public protocol FusionPaymentsManagerProtocol  {
    init(paymentRequest: PaymentRequest)

    /*
     * @property initiatePayment
     *
     * @discussion request payment(Apple/Google pay)
     *             paymentRequest is passed as input parameter
     *
     * @param paymentRequest: passed as input parameter
     *        paymentStatus: contains the payment result
     *        paymentSheetViewState: contains the current state of the payment-sheet
     *
     */
    func initiatePayment( paymentRequest: PaymentRequest, paymentStatus: @escaping (PaymentStatus, PaymentError?) -> Void, paymentSheetViewState: @escaping (PaymentSheetViewState) -> Void )
}
Enter fullscreen mode Exit fullscreen mode

The iOS part of the FusionPayments uses the PassKit module to implement the Apple Pay feature. The payment view controller presents the payment sheet and accepts the payment request object. \

// Using PassKit methods to intiate the Apple Pay transaction
        if PKPaymentAuthorizationViewController.canMakePayments(usingNetworks: paymentNetworks) {
            let request = PKPaymentRequest()
            request.currencyCode = paymentRequest.currencyCode  // 1
            request.countryCode = paymentRequest.countryCode  // 2
            request.merchantIdentifier = paymentRequest.merchantIdentifier//"merchant.com.vedant.fusionpayments"  // 3
            request.merchantCapabilities = PKMerchantCapability.capability3DS  // 4
            request.supportedNetworks = paymentNetworks  // 5
            request.paymentSummaryItems = [paymentItem]  // 6

            guard let paymentVC = PKPaymentAuthorizationViewController(paymentRequest: request) else {
                print("Unable to present Apple Pay authorization dialog")
                completionHandler?(.FAILED, .AUTHORIZATION_ERROR)
                return
            }
            paymentVC.delegate = self
            self.paymentVC = paymentVC
#if os(iOS)
            UIApplication.shared.delegate?.window??.rootViewController?.present(
                paymentVC, animated: true, completion: nil)
            paymentSheetViewState(.PAYMENT_SHEET_OPENED)
#endif

        } else {
            // displayDefaultAlert(title: "Error", message: "Unable to make Apple Pay transaction.")
            print("Unable to make Apple Pay transaction!")
            completionHandler?(.FAILED, .UNSUPPORTED_PAYMENT_NETWORK)
        }

        completionHandler = paymentStatus
        self.paymentSheetViewState = paymentSheetViewState
Enter fullscreen mode Exit fullscreen mode

Integrate FusionPayments SDK

We will now start the development of the SCADE app by integrating the FusionPayments SDK into our project. Navigate to Package.swift and add the below code snippet.

// swift-tools-version:5.3

import PackageDescription
import Foundation

let SCADE_SDK = ProcessInfo.processInfo.environment["SCADE_SDK"] ?? ""

let package = Package(
    name: "ScadePaymentsApp",
    platforms: [
        .macOS(.v10_14)
    ],
    products: [
        .library(
            name: "ScadePaymentsApp",
            type: .static,
            targets: [
                "ScadePaymentsApp"
            ]
        )
    ],
   dependencies: [
    .package(
      name: "FusionPayments", url: "https://github.com/scade-platform/FusionPayments.git",
      .branch("main")),

  ],
    targets: [
        .target(
            name: "ScadePaymentsApp",
            dependencies: [
                .product(name: "FusionPayments", package: "FusionPayments"),
            ],
            exclude: ["main.page"],
            swiftSettings: [
                .unsafeFlags(["-F", SCADE_SDK], .when(platforms: [.macOS, .iOS])),
                .unsafeFlags(["-I", "\(SCADE_SDK)/include"], .when(platforms: [.android])),
            ]
        )
    ]
)
Enter fullscreen mode Exit fullscreen mode

Call the FusionPayments Methods

We will now start the development of the SCADE app by creating some UI like adding a payment button. As the next step, initialize the fusionPaymentsManager variable at the class level.

import FusionPayments
var paymentManager: FusionPaymentsManager?
Enter fullscreen mode Exit fullscreen mode

Then, declare the supported Payment Networks like Visa, Mastercard, etc which will be used to make the payments, and declare the countries where this payment will be valid.

let pNetworks: [PaymentNetwork] = [PaymentNetwork.amex, .visa, .masterCard]

let countries: Set<String> = ["US", "UK"]
Enter fullscreen mode Exit fullscreen mode

Now we will create a PaymentSummaryItem which will contain the amount to pay and the title for the payment.

let paymentSummaryItem: PaymentSummaryItem = PaymentSummaryItem(
        label: "SomeLabelForShopping", amount: 3.3)
Enter fullscreen mode Exit fullscreen mode

The above-created variables are required to create a final PaymentRequest object which will be passed to paymentManager to initiate the payment.

let paymentRequest: PaymentRequest = PaymentRequest(
        merchantIdentifier: "merchant.com.vedant.fusionpayments", countryCode: "US",
        currencyCode: "USD", supportedNetworks: pNetworks,
        paymentSummaryItem: paymentSummaryItem, supportedCountries: countries)

      self?.paymentManager = FusionPaymentsManager(paymentRequest: paymentRequest)
Enter fullscreen mode Exit fullscreen mode

Finally, we will have to call the intiatePayment method of the paymentManager object.

It will take the paymentRequest as the parameter and will provide a callback function for the payment status and the view state of paymentSheetViewState.

      self?.paymentManager?.initiatePayment(
        paymentRequest: paymentRequest,
        paymentStatus: { (status: PaymentStatus, error: PaymentError?) in
          print(status)
          print(error)

        },
        paymentSheetViewState: {
          viewState in
          print("viewed state")
          print(viewState)
        })
Enter fullscreen mode Exit fullscreen mode

As you can notice from the above snippet, we have printed the status of the payment or the error if payment didn’t go through successfully. Furthermore, it also returns the current state of the payment bottom sheet whether it is visible or hidden.

Run the App!

Let’s now run the app on any iOS simulator and check if it’s working fine or not.

Image description

Voila 🎉! It is very easy to integrate FusionPayments SDK into the SCADE app. We are able to make a successful Apple Pay transaction now. You can find the full source code of the demo application here. We recommend you use the FusionPayments SDK in your cross-platform Swift apps if you want to accept payments from the users. Thank you for reading and see you in the next article!

Top comments (0)