Swiftpack.co - Package - afterpay/sdk-ios
Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.

Afterpay iOS SDK

Build and Test Swift Package Manager compatible Carthage compatible CocoaPods compatible Platform License

The Afterpay iOS SDK provides conveniences to make your Afterpay integration experience as smooth and straightforward as possible. We're working on crafting a great framework for developers with easy drop in components to make payments easy for your customers.

Table of Contents

Integration

Requirements

  • iOS 12.0+
  • Swift 5.2+
  • Xcode 11.4+

Swift Package Manager

dependencies: [
    .package(url: "https://github.com/afterpay/sdk-ios.git", .upToNextMajor(from: "1.0.0"))
]

Carthage

github "afterpay/sdk-ios" ~> 1.0

CocoaPods

pod 'Afterpay', '~> 1.0'

Manual

If you prefer not to use any of the supported dependency managers, you can choose to manually integrate the Afterpay SDK into your project.

Source

GitHub Release

Download the latest release source zip from GitHub and unzip into an Afterpay directory in the root of your working directory.

Git Submodule

Add the Afterpay SDK as a git submodule by navigating to the root of your working directory and running the following commands:

git submodule add https://github.com/afterpay/sdk-ios.git Afterpay
cd Afterpay
git checkout 1.4.2

Project / Workspace Integration

Now that the Afterpay SDK resides in the Afterpay directory in the root of your working directory, it can be added to your project or workspace with the following steps:

  1. Open the new Afterpay directory, and drag Afterpay.xcodeproj into the Project Navigator of your application's Xcode project or workspace.
  2. Select your application project in the Project Navigator to navigate to the target configuration window and select the application target under the "Targets" heading in the sidebar.
  3. In the tab bar at the top of that window, open the "General" panel.
  4. Click on the + button under the "Frameworks, Libraries, and Embedded Content" section.
  5. Select the Afterpay.framework for your target platform.

And that's it, the Afterpay SDK is now ready to import and use within your application.

XCFramework

  1. Download the latest release framework zip from GitHub and unzip it.
  2. Select your application project in the Project Navigator to navigate to the target configuration window and select the application target under the "Targets" heading in the sidebar.
  3. Drag the Afterpay.xcframework under the "Frameworks, Libraries, and Embedded Content" section of your application target in the General tab.

Features

The Afterpay SDK contains a checkout web flow with optional security features as well some UI components.

Web Checkout

Provided the URL generated during the checkout process we take care of pre approval process during which the user will log into Afterpay. The provided integration accounts for cookie storage such that returning customers will only have to re-authenticate with Afterpay once their existing sessions have expired.

Note

These cookies are stored in the default web kit website data store and can be cleared if required by writing code similar to:

let dataStore = WKWebsiteDataStore.default()
let dataTypes = [WKWebsiteDataTypeCookies] as Set<String>

dataStore.fetchDataRecords(ofTypes: dataTypes) { records in
  let afterpayRecords = records.filter { $0.displayName == "afterpay.com" }
  dataStore.removeData(ofTypes: dataTypes, for: afterpayRecords) {}
}

Security

For added security, a method to hook into the SDKs WKWebView Authentication Challenge Handler is provided. With this you can implement things like SSL Pinning to ensure you can trust your end to end connections. An example of this has been provided in the example project and in the snippet below using TrustKit. In this handler you must return whether or not you have handled the challenge yourself (have called the completionHandler) by returning true, or if you wish to fall back to the default handling by returning false.

Swift

Afterpay.setAuthenticationChallengeHandler { challenge, completionHandler -> Bool in
 let validator = TrustKit.sharedInstance().pinningValidator
 return validator.handle(challenge, completionHandler: completionHandler)
}

Objective-C

typedef void (^ CompletionHandler)(NSURLSessionAuthChallengeDisposition, NSURLCredential *);

BOOL (^challengeHandler)(NSURLAuthenticationChallenge *, CompletionHandler) = ^BOOL(
 NSURLAuthenticationChallenge *challenge,
 CompletionHandler completionHandler
) {
 TSKPinningValidator *pinningValidator = [[TrustKit sharedInstance] pinningValidator];
 return [pinningValidator handleChallenge:challenge completionHandler:completionHandler];
};

[APAfterpay setAuthenticationChallengeHandler:challengeHandler];

Views

Color Schemes

Color schemes can be set on the badge view or payment button to either have a single style in both light and dark mode or to change automatically.

// Always black on mint
badgeView.colorScheme = .static(.blackOnMint)

// White on black in light mode and black on white in dark mode
badgeView.colorScheme = .dynamic(lightPalette: .whiteOnBlack, darkPalette: .blackOnWhite)

Badge

The Afterpay badge is a simple UIView that can be scaled to suit the needs of your app. As per branding guidelines it has a minimum width constraint of 64 points.

let badgeView = BadgeView()

Below are examples of the badge in each of the color schemes:
Black on Mint badge Mint on Black badge White on Black badge Black on White badge

Payment Button

The Afterpay Payment Button is a subclass of UIButton that can be scaled to suit your layout, to guarantee legibility it has a maximum width constraint of 256 points.

Below are examples of the button in each of the color schemes:

Mint and Black Black and White
Black on Mint button White on Black button
Mint on Black button Black on White button

Price Breakdown

The price breakdown component displays information about Afterpay instalments and handles a number of common scenarios.

A configuration should be set on the Afterpay SDK in line with configuration data retrieved from the Afterpay API. This configuration can be cached and should be updated once per day.

A locale should also be set matching the region for which you need to display terms and conditions. This also affects how currencies are localised as well as what branding is displayed, for instance usage of the "en_GB" locale will display Clearpay branding.

do {
  let configuration = try Configuration(
    minimumAmount: response.minimumAmount?.amount,
    maximumAmount: response.maximumAmount.amount,
    currencyCode: response.maximumAmount.currency,
    locale: Locale(identifier: "en_US")
  )

  Afterpay.setConfiguration(configuration)
} catch {
  // Something went wrong
}

A total payment amount (represented as a Swift Decimal) must be programatically set on the component to display Afterpay instalment information.

// A zero here will display the generic 'pay with afterpay' messaging
let totalAmount = Decimal(string: price) ?? .zero

let priceBreakdownView = PriceBreakdownView()
priceBreakdownView.totalAmount = totalAmount

After setting the total amount the matching breakdown string for the set Afterpay configuration will be displayed.

For example:
Four payments available

Accessibility and Dark mode

By default this component updates when the trait collection changes to update text and image size as well as colors to match. A components page in the Example app has been provided to demonstrate.

Getting Started

We provide options for integrating the SDK in Swift and Objective-C.

Presenting Web Checkout

The Web Login is a UIViewController that can be presented modally over the view controller of your choosing.

Swift (UIKit)

import Afterpay
import UIKit

final class CheckoutViewController: UIViewController {
  // ...
  @objc func didTapPayWithAfterpay() {
    Afterpay.presentCheckoutModally(over: self, loading: self.checkoutUrl) { result in
      switch result {
      case .success(let token):
        // Handle successful Afterpay checkout
      case .cancelled(let reason):
        // Handle checkout cancellation
      }
    }
  }
}

Objective-C (UIKit)

#import "ViewController.h"
#import <Afterpay/Afterpay-Swift.h>
#import <UIKit/UIKit.h>

@implementation ViewController

// ...

- (void)didTapPayWithAfterpay {

  void (^completion)(APCheckoutResult *) = ^(APCheckoutResult *result) {

    if ([result isKindOfClass:[APCheckoutResultSuccess class]]) {
      // Handle success with [(APCheckoutResultSuccess *)result token]
    } else {
      // Handle cancellation with [(APCheckoutResultCancelled *)result reason]
    }

  };

  [APAfterpay presentCheckoutModallyOverViewController:self
                                    loadingCheckoutURL:self.checkoutUrl
                                              animated:true
                                            completion:completion];

}

@end

SwiftUI

struct MyView: View {

  // Updating this state with a retrieved checkout URL will present the afterpay sheet
  @State private var checkoutURL: URL?

  var body: some View {
    SomeView()
      .afterpayCheckout(url: $checkoutURL) { result in
        switch result {
        case .success(let token):
          // Handle successful Afterpay checkout
        case .cancelled(let reason):
          // Handle checkout cancellation
        }
      }
  }

}

Examples

The example project demonstrates how to include an Afterpay payment flow web experience. This project is powered by the example server which shows a simple example of integration with the Afterpay API.

Building

Mint

The Afterpay SDK uses Mint to install and run Swift command line packages. This has been pre-compiled and included in the repository under the Tools/mint directory, meaning it does not need to be installed or managed externally.

NOTE: Mint will automatically download the packages it manages on demand. To speed up the initial build of the SDK, the packages can be downloaded by running the Scripts/bootstrap script.

Running

Building and running the project is as simple as cloning the repository, opening Afterpay.xcworkspace and building the Afterpay target. The example project can be built and run via the Example target.

XCFramework

A .xcframework can be generated by running the included create-xcframework.

Contributing

Contributions are welcome! Please read our contributing guidelines.

License

This project is licensed under the terms of the Apache 2.0 license. See the LICENSE file for more information.

Github

link
Stars: 5

Dependencies

Releases

1.4.2 - External Link Hotfix - 2021-01-14T02:31:06

What's Changed

  • Ensure all links requesting to be opened in a new window are opened externally @adamjcampbell (#129)

1.4.1 - Swift Update (5.2) - 2021-01-11T03:28:22

What's Changed

  • Update minimum requirements to Swift 5.2 and Xcode 11.4 @adamjcampbell (#128)
  • Add latest sandbox PIN @adamjcampbell (#126)

1.4.0 - Pay Now Button - 2020-12-01T03:19:24

What's Changed

  • Add reference to the example server project @adamjcampbell (#122)
  • Fix swiftlint-example script to respect the Mintfile @adamjcampbell (#123)

🚀 Features

  • Add 'Pay Now' button to Afterpay framework and example project @adamjcampbell (#125)

1.3.0 - Clearpay - 2020-10-19T03:08:16

What's Changed

This release marks full support for the Clearpay branding and pound sterling within the price breakdown component. This is achieved by setting the configured locale to "en_GB". In addition to this clearpay URLs have been added to the valid set for the checkout web flow.

🚀 Features

  • Ensure currency formatting matches expected currency formatting @adamjcampbell (#120)
  • Ensure SVGView updates when a change in locale causes a change in the SVG @adamjcampbell (#119)
  • Add Clearpay SVGs to the price breakdown component @adamjcampbell (#118)
  • Added Clearpay as a valid host for UK transactions. @JakeHoldom (#116)

🧰 Maintenance

  • Updates documentation to show locale configuration and refer to 1.3.0 @adamjcampbell (#121)
  • Xcode 12 and Swift 5.3 updates @adamjcampbell (#117)

1.2.0 - Minty Fresh - 2020-08-14T07:22:16

What's Changed

  • Prepare iOS for a 1.2.0 release adding documentation and ensuring features are accessible @adamjcampbell (#114)

🚀 Features

  • Match on Locales to serve the correct "Info" modal @adamjcampbell (#112)
  • Add accessibilty label to the badge attachement in price breakdown @adamjcampbell (#110)
  • Format with correct currency symbol @adamjcampbell (#109)
  • Update attributed text in breakdown components via notification center @adamjcampbell (#107)
  • Add the ability to view the purchase-payment-agreement in browser @adamjcampbell (#105)
  • Price Breakdown Logic @adamjcampbell (#103)
  • Allow the option to implement a delegate and launch the info modal @adamjcampbell (#102)
  • Add link and limit UITextView interactions @adamjcampbell (#101)
  • Add InfoWebViewController for viewing Afterpay information links @Rypac (#100)
  • Adds afterpay badge to PriceBreakdownView and makes the text responsive @adamjcampbell (#98)
  • Cache Afterpay configuration in example app @Rypac (#96)
  • Presents the correct afterpay badge in light or dark style @adamjcampbell (#97)
  • Add afterpay badge view and components tab @adamjcampbell (#95)
  • Adds SwiftSVG as a dependency of the AfterpaySDK @adamjcampbell (#94)
  • Set the merchant configuration in the example app @adamjcampbell (#92)
  • Add GitHub action to validate Afterpay SDK pod @Rypac (#90)
  • Add settable Configuration object to the SDK @adamjcampbell (#89)

🐛 Bug Fixes

  • Fix scroll view height ambiguity by adding containment views @adamjcampbell (#106)

🧰 Maintenance

  • Make use of the locale region code to form the info link @adamjcampbell (#113)
  • Configuration observation example @adamjcampbell (#108)
  • Add unit tests for PriceBreakdown @adamjcampbell (#104)
  • Update assets and refactor color schemes @adamjcampbell (#99)
  • Add Validate Swift Package Job @adamjcampbell (#91)

1.1.0 - Put a PIN in it - 2020-07-23T03:48:11

What's Changed

  • Update integration docs @adamjcampbell (#87)

🚀 Features

  • Add an authentication challenge handler to the SDK @adamjcampbell (#88)

1.0.2 - A warm ☕️ of Cocoa - 2020-07-22T04:44:19

What's Changed

🚀 Features

  • Add Cocoapods support and release deployment @adamjcampbell (#84)

🐛 Bug Fixes

  • Update CocoaPods deployment to run on published releases @adamjcampbell (#86)

1.0.1 - The Day-One Patch - 2020-07-22T00:14:39

What's Changed

  • Update the README with version 1.0.1 relevant content @adamjcampbell (#81)

🐛 Bug Fixes

  • Harden Swiftlint build phase script to avoid build failures @adamjcampbell (#80)

🧰 Maintenance

  • Bump version to 1.0.1 @adamjcampbell (#82)

1.0.0 - Ready Set Afterpay - 2020-07-21T05:53:01

First public release of the Afterpay SDK for iOS. 🚀