iOS Payments SDK Integration Guide
Posted by Elijah Joshua Cayabyab • Wednesday February 03, 2016 07:23 AM

The PayMaya iOS Payments SDK allows your app to accept payments from your customers using any MasterCard and Visa card (credit, debit, or prepaid) while giving you the control and flexibility of the payment user experience.

 


Contents

 

Prerequisites

Overview

Integration

Using Payments

    Initializing the SDK

    Constructing Card object

    Executing Payment Token generation

Testing Your Payment Token

      Without Backend Integration

      With Backend Integration

Summary

 

Prerequisites

 

Compatibility

 

  • Xcode 6 or above
  • iOS 6.0+ target deployment
  • armv7, armv7s, and arm64 devices, and the simulator (not armv6)
  • iPhone and iPad of all sizes and resolutions

 

API Keys

 

To use the PayMaya iOS Payments SDK, you need to have a different set of API key for each environment (Sandbox and Production).

 

  • Sandbox

 

Sandbox credentials are useful for testing application integration. All transactions made in this environment are only simulated and will not reflect in production. The following sandbox API keys can be used for testing purposes:

 

Public-facing API Key: pk-sHQWci2P410ppwFQvsi7IQCpHsIjafy74jrhYb8qfxu

 

Secret API Key: sk-4Wub7pHVixHR8lm7vgdxgMq23TDJcms8EMEobM80uoo

 

  • Production

 

Upon successful integration testing, you can then request for your production credentials. Once received, just change your SDK initialization to use production environment to start accepting live transactions.

 

There are two (2) required fields in HTTP Basic Authentication, the username and password. API keys act as the "username" while passwords are set to blank ("").

 

Overview

 

Using Payments, you have more control of the whole payment process. You will have the option to create a custom view for customers where they can input their card information that conforms to the look and feel of your application. The SDK allows payment token creation from customer's card information that you can pass around and store in your application. This token does not reveal any card information within and should be passed to your servers for payment execution.

 

PayMaya Payments SDK flow

Figure 1 - Payments transaction flow

 

  1. Customer proceeds with payment and provides card information.
  2. Your app receives the payment token creation status.
  3. If payment token is successfully created, send the transaction details and payment token to your servers for payment execution. Otherwise, handle the failed token creation status accordingly and generate a new payment token.

 

 

Method completion status is received either via delegates or completion block. The former requires you to implement a class that conforms to a protocol while the latter requires understanding of blocks. As to which of the two callback options you will implement, it is entirely up to you. For more information, you can refer to the following references about delegates and blocks.

 

Integration

 

Via CocoaPods

 

If you use CocoaPods, then add these lines to your podfile:

platform :ios, '7.0' 
pod 'PayMayaSDK'

 

If you don't use CocoaPods, then you can clone the SDK:

  1. Clone the SDK (https://github.com/PayMaya/PayMaya-iOS-SDK).
  2. Copy the contents of the Pod directory consisting of header and implementation files to your Xcode project. It is recommended to check "Copy items..." and select "Create groups...".

 

Note: Since the SDK is written in Objective-C, projects written in Swift would need to configure a bridging header to use it. More information about this can be found here.

 

Using Payments

    1. Initialize the Payments SDK by providing your API key and specifying intended environment (sandbox or production). It is recommended to do this in your app delegate's didFinishLaunchingWithOptions: method. Sample credentials provided below should be updated accordingly.

#import “PayMayaSDK.h”
// If you included PayMaya SDK via Pods or as a framework, use: 
// #import PayMayaSDK/PayMayaSDK.h
//..

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // ...
    [[PayMayaSDK sharedInstance] setPaymentsAPIKey:@"pk-sHQWci2P410ppwFQvsi7IQCpHsIjafy74jrhYb8qfxu"
                                    forEnvironment:PayMayaEnvironmentSandbox];
    // ...
    return YES;
}

    2. Create a PMSDKCard object with card number, expiry month, expiry year, and CVV as defined in PMSDKCard.h

// SomeViewController.m

(void)generatePaymentTokenButtonClicked:(id)sender { 
    PMSDKCard *card = [[PMSDKCard alloc] init];
    card.number = self.cardNumberTextField.text;
    card.expiryMonth = self.expiryMonthTextField.text;
    card.expiryYear = self.expiryYearTextField.text;
    card.cvc = self.cvvTextField.text;

    // continued on step 3...

You can also initialize the card object with a dictionary using the defined keys.

    NSDictionary *cardDictionary = @{
        @"number" : self.cardNumberTextField.text,
        @"expMonth" : self.expiryMonthTextField.text,
        @"expYear" : self.expiryYearTextField.text,
        @"cvc" : self.cvvTextField.text
    };
    
    PMSDKCard *card = [[PMSDKCard alloc] initWithDictionary:cardDictionary];
    
    // continued on step 3...

    3. After creation of your card object, you can use this to generate a payment token. You can then get the payment token result via delegate method or completion block.

 

For Sandbox environment, you must only use credit cards from the following link: Credit Cards for Sandbox Testing

 

    3.a If you opt to use delegation, you must have a class that conforms to PayMayaPaymentsDelegate, call createPaymentTokenFromCard:delegate: method, and implement the required delegate methods.

 

Create a class that conforms to PayMayaPaymentsDelegate protocol

// SomeViewController.h 
#import "PayMayaSDK.h" 

@interface SomeViewController : UIViewController <PayMayaPaymentsDelegate>

// ... 

@end

 

Call the createPaymentTokenFromCard:delegate: method to get a payment token

    // ...continued from step 2

    [[PayMayaSDK sharedInstance] createPaymentTokenFromCard:card delegate:self];
}

 

Implement the required delegate methods to be called upon payment token creation. The required delegate methods are createPaymentTokenDidFinishWithResult: and createPaymentTokenDidFailWithError:. The former is called when payment token creation finished with a valid status while the latter is called when an error is encountered before successful creation.

// SomeViewController.h 

#pragma mark - PayMayaPaymentsDelegate methods

@implementation SomeViewController : UIViewController 

// ... 

- (void)createPaymentTokenDidFinishWithResult:(PMSDKPaymentTokenResult *)result
{
    if (result.status == PMSDKPaymentTokenStatusCreated) {
        // handle payment token created status
    }
}

- (void)createPaymentTokenDidFailWithError:(NSError *)error
{
    // handle error
}

@end

    3.b If you prefer to use blocks, use the createPaymentTokenFromCard:result: method and handle the result accordingly on the completion block.

    // ...continued from step 2

    [[PayMayaSDK sharedInstance] createPaymentTokenFromCard:card result:^(PMSDKPaymentTokenResult* result, NSError *error) {
        if (error) {
            // handle error
        }
        else {
            if (result.status == PMSDKPaymentTokenStatusCreated) {
                // handle payment token created status
            }
            else if (result.status == PMSDKPaymentTokenStatusUsed) {
                // handle payment token used status
            }
        }
    }];
}

 

Testing Your Payment Token

 

It is advised to log your payment token during development if you want to test it.

In here, we provide two (2) ways to test the payment token that you have received from your mobile app.

 

Without Backend Integration

 

To test your payment token without any backend integration, first we will check if you have cURL installed. To do this, open up a command prompt (if using Windows), command line (if using Linux), or Terminal (if using Mac). Type the following and hit enter:

curl --version

 

You will be able to see the cURL version if it is already installed. If not, you will see a message stating that curl is an unknown command.

 

In case you do not have curl installed, you may follow this link on how to install it and go back here once done:

 

If you have cURL installed and you used the Public-facing API Key in the Prerequisites above, simply copy the following to your command line (replacing "YOUR_PAYMENT_TOKEN" with the payment token you have received in your mobile app), then hit enter:

curl -H "Content-Type: application/json" -H "Authorization: Basic c2stNFd1YjdwSFZpeEhSOGxtN3ZnZHhnTXEyM1RESmNtczhFTUVvYk04MHVvbzo=" -X POST -d '{"paymentTokenId":"YOUR_PAYMENT_TOKEN","totalAmount" : {"amount": 100,"currency": "PHP"},"buyer": {"firstName": "Cza","middleName": "dela","lastName": "Bongat","contact": {"phone": "+63(2)1234567890","email": "paymayabuyer1@gmail.com"},"billingAddress": {"line1": "9F Robinsons Cybergate 3","line2": "Pioneer Street","city": "Mandaluyong City","state": "Metro Manila","zipCode": "12345","countryCode": "PH"}}}' https://api.paymaya.com/sandbox/payments/payments

 

If you used your own Public-facing API Key to request for a payment token on your mobile app, you will have to encode your Secret API Key to base64. You can use this online tool to encode your Secret API Key.

 

Once you have your base64-encoded Secret API Key, replace the header parameter Authorization with your base64-encoded Secret API Key from the curl command above.

 

Once you have received the server's response, you should be able to see something similar to the following:

{
   "id":"5dd0c1e3-db05-403d-8719-59275faefb10",
   "environment":"sandbox",
   "isPaid":true,
   "status":"succeeded",
   "refunded":false,
   "paymentTokenId":"PLSXITXSOGfsu3JBHntZkLe1JSI1o40F19ZFUnLRPSyZUrCeXLBOOt1kWfDjgBWyeYk2uIwS5fnCUlBYCGD4V8pIAtSBblIWVxgWz94ZEVXHnIyS1UpZcmSNDelae7KsqBjsFOZ1iTY7cIz97tw2fP300v59mXqA0tQA",
   "captured":true,
   "balanceTransaction":"txn_167NbiIdRJ2MkNGUwtXNOBkn",
   "failureMessage":null,
   "failureCode":null,
   "amountRefunded":0,
   "customer":null,
   "invoice":null,
   "description":"Charge for test@example.com",
   "dispute":null,
   "metadata":{

   },
   "statementDescriptor":null,
   "fraudDetails":{

   },
   "receiptEmail":null,
   "receiptNumber":null,
   "shipping":null,
   "destination":null,
   "applicationFee":null
}

 

With Backend Integration

 

To test your payment token with your own backend, simply prepare your secret key and follow the steps here: PayMaya Payments API

 

In case you do not have your own backend but want to set it up on your local machine to simulate, simply follow the steps in the following link and follow its README: PayMaya Payments Skeleton Backend

 

 

 

Summary

 

  • This SDK document includes an overview of usage, step-by-step integration instructions, and sample code.
  • A sample app is included in the SDK.
  • Header files are documented. Refer to them as needed for more information about any given property or parameter.
  • Documentation in appledoc format is available here.
  • Checkout API Documentation and Payments API Documentation are available which cover error codes and server-side integration instructions.