# iOS SDK

> Use the Paystack iOS SDK to accept payments in your iOS app.

<callout title="Beta release" type="warning">

The iOS SDK is currently in beta. If you encounter any issues or have suggestions, [don't hesitate to reach out](https://docs.google.com/forms/d/e/1FAIpQLSf8xRyyAp4_QIBCZisdzoMgoIyIlUuju387O6crTs63scdBag/viewform).

</callout>

## Introduction

The iOS SDK is collection of methods and interfaces that allow developers to build a secure, and convenient payment flow for their iOS applications. Integration is a two-step process:

1. Initiate the transaction on the server
2. Complete it on the SDK

## Project requirements

Paystack iOS SDK is designed to support iOS 13 and above. We don't support OS versions below iOS 13. Before using the SDK, you need to ensure your app meets the following requirements:

- iOS 13 and above
- Any OS version on any other OS
- Swift Package Manager

## Installation

The iOS SDK comes with two packages:

1. **PaystackCore**: This contains the APIs and methods for processing payments.
2. **PaystackUI**: This contains the UI components to collect the customer’s payment information and display the payment status.

You can install these packages via the [Swift Package Manager](https://www.swift.org/documentation/package-manager/). To add the required packages, ensure you have the [latest version of XCode](https://developer.apple.com/xcode/) installed and follow these steps:

1. Select File > Add Package Dependencies…
2. Copy [the repo URL and paste it](https://github.com/PaystackHQ/paystack-sdk-ios) in the search box of the package dependency

You can read the [Swift Package Manager documentation](https://developer.apple.com/documentation/xcode/adding-package-dependencies-to-your-app) to learn more about adding packages to your project.

## Paystack core

The `PaystackCore` module uses a builder pattern to handle housekeeping and foundational tasks before the UI components can be used.

```swift
import PaystackCore
```

The table below shows the methods available in the `Paystack` class:

<table>
<thead>
  <tr>
    <th>
      Methods
    </th>
    
    <th>
      Description
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        setKey("public-key")
      </code>
    </td>
    
    <td>
      This method is used to set the public key. Without a public key, you can’t complete a transaction.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        enableLogging()
      </code>
    </td>
    
    <td>
      This method determines if you get debug logs or not. By default, logging is disabled. Adding this method enables logging.
    </td>
  </tr>
</tbody>
</table>

```swift
let paystack = try? PaystackBuilder
        .newInstance
        .setKey("pk_domain_xxxxxxxx")
        .build()
```

## Initialize transaction

The SDK requires an `access_code` to display the UI component that accepts payment. To get the `access_code`, make a `POST` request to the [Initialize Transaction](/api/transaction#initialize) endpoint from your server:

<request-response>
<template v-slot:curl="">

```bash
curl https://api.paystack.co/transaction/initialize \
  -H "Authorization: Bearer $PAYSTACK_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "customer@email.com",
    "amount": 500000
  }' \
  -X POST
```

</template>

<template v-slot:js="">

```javascript
const https = require("https");

const params = JSON.stringify({
  "email": "customer@email.com",
  "amount": 500000
});

const options = {
  hostname: "api.paystack.co",
  port: 443,
  path: "/transaction/initialize",
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.PAYSTACK_SECRET_KEY}`,
    "Content-Type": "application/json",
  },
};

const req = https.request(options, (res) => {
  let data = "";
  res.on("data", (chunk) => {
    data += chunk;
  });
  res.on("end", () => {
    console.log(res.statusCode, JSON.parse(data));
  });
});

req.on("error", (error) => {
  console.error(error);
});

req.write(params);
req.end();
```

</template>

<template v-slot:php="">

```php
<?php
$fields = [
  "email" => "customer@email.com",
  "amount" => 500000,
];

$curl = curl_init();
curl_setopt_array($curl, array(
  CURLOPT_URL => "https://api.paystack.co/transaction/initialize",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => json_encode($fields),
  CURLOPT_HTTPHEADER => array(
    "Authorization: Bearer " . getenv("PAYSTACK_SECRET_KEY"),
    "Content-Type: application/json",
    "Cache-Control: no-cache",
  ),
));
$response = curl_exec($curl);
echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . " " . $response;
?>
```

</template>

<template v-slot:response="">

```json
{
  "status": true,
  "message": "Authorization URL created",
  "data": {
    "authorization_url": "https://checkout.paystack.com/nkdks46nymizns7",
    "access_code": "nkdks46nymizns7",
    "reference": "nms6uvr1pl"
  }
}
```

</template>
</request-response>

On a successful initialization of the transaction, you get a response that contains an `access_code`. You need to return this `access_code` back to your mobile app.

<callout title="Secret key safeguarding" type="danger">

Don't make an API request to the Initialize Transaction endpoint directly on your mobile app because it requires your secret key. Your secret key should only be used on your server where stronger security measures can be put in place.

</callout>

## Paystack UI

The `PaymentUI` modules holds the UI components that manages the payment form and the available payment channels. You can add this module to your project as shown below:

```swift
import PaystackUI
```

The `PaystackUI` module comes with two methods:

1. `chargeUIButton`: This is best suited for SwiftUI.
2. `presentChargeUI`: This is best suited for UIKit.

### chargeUIButton

We provide a button that you can customize to trigger the Payment UI. This method takes the following parameters:

<table>
<thead>
  <tr>
    <th>
      Parameter
    </th>
    
    <th>
      Type
    </th>
    
    <th>
      Description
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        accessCode
      </code>
    </td>
    
    <td>
      String
    </td>
    
    <td>
      This is gotten from your server after initializing a transaction.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        onComplete
      </code>
    </td>
    
    <td>
      Callback
    </td>
    
    <td>
      This method handles all post-payment processes. It’s argument has the type of <code>
        TransactionResult
      </code>
      
      .
    </td>
  </tr>
</tbody>
</table>

```swift
paystack?.chargeUIButton(accessCode: "ACCESS_CODE", onComplete: paymentDone) {
  Text("Initiate Payment")
}
```

### presentChargeUI

With this method, you need to create a button that would trigger the display of the Payment UI. The Payment UI requires a view to hook to, so you need to provide a reference to the view controller of the view being displayed, alongside other parameters listed in the table below:

<table>
<thead>
  <tr>
    <th>
      Parameter
    </th>
    
    <th>
      Type
    </th>
    
    <th>
      Description
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        on
      </code>
    </td>
    
    <td>
      ViewController
    </td>
    
    <td>
      The view controller of the current view.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        accessCode
      </code>
    </td>
    
    <td>
      String
    </td>
    
    <td>
      This is gotten from your server after initializing a transaction.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        onComplete
      </code>
    </td>
    
    <td>
      Callback
    </td>
    
    <td>
      This method handles all post-payment processes. It’s argument has the type of <code>
        TransactionResult
      </code>
      
      .
    </td>
  </tr>
</tbody>
</table>

```swift
@IBAction func payButtonTapped(_ sender: Any) {
  paystack?.presentChargeUI(on: self,
                            accessCode: "ACCESS_CODE",
                            onComplete: paymentDone)
}
```

## Transaction result

The `TransactionResult` exposes the different states of a transaction. It's the  argument type for the `PaystackUI` `onComplete` callback:

<table>
<thead>
  <tr>
    <th>
      State
    </th>
    
    <th>
      Description
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      Completed
    </td>
    
    <td>
      The customer completed the payment process. We return a <code>
        paymentCompletionDetails
      </code>
      
       that contains the transaction reference. You should use the transaction reference to verify the transaction status and amount on the server before providing value.
    </td>
  </tr>
  
  <tr>
    <td>
      Cancelled
    </td>
    
    <td>
      The customer cancelled the payment.
    </td>
  </tr>
  
  <tr>
    <td>
      Failed
    </td>
    
    <td>
      An error occurred during the payment process. This result contains a <code>
        ChargeError
      </code>
      
      . The <code>
        ChargeError
      </code>
      
       contains a <code>
        cause
      </code>
      
       property which details the actual error received and should be used for error handling and logging
    </td>
  </tr>
</tbody>
</table>

```swift
func paymentDone(_ result: TransactionResult) {
  switch (result){
    case .completed(let details):
      print("Transaction completed with reference: \(details.reference)")
    case .cancelled:
      print("Transaction was cancelled")
    case .error(error: let error, reference: let reference):
      print("An error occurred: \(error.message) with reference: \(String(describing: reference))")
  }
}
```
