iOS Integration

Integrate smallcase Gateway iOS SDK to allow your users to transact in stocks, ETFs & smallcases, and much more

Step 1 - Install and Configure

A. Using Cocoapod

smallcase Gateway iOS SDK is available as a private cocoa pod dependency.

To install the iOS SDK:

  1. add following code to your Podfile
  2. run pod install
# default source for all other pods
source 'https://cdn.cocoapods.org'

# private podspec for smallcase (only for versions < 3.10.0)
source 'https://github.com/smallcase/cocoapodspecs.git'

target '${CLIENT_PROJECT_NAME}' do

  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!
  
  # Add the SCGateway pod dependency and replace ${FRAMEWORK_VERSION}
  # with latest version code (example: 3.11.2).
  pod 'SCGateway', '~> ${FRAMEWORK_VERSION}'
  end

end

B. Using Swift Package Manager

To install the iOS SDK as a Swift Package Dependency to your Xcode project:

i - Select File > Swift Packages > Add Package Dependency

ii - Enter the following repository URL:

https://github.com/smallcase/SCGatewayPackageIos

iii - Decide whether your project accepts updates to a package dependency up to the next major version or up to the next minor version.

Step 2- Environment Setup

To start using gateway setup the gateway with the desired configuration by calling setup.

let config = GatewayConfig(
    gatewayName : "your-gateway-name",
    brokerConfig : [],
    apiEnvironment : .production,
    isLeprechaunActive : true,
    isAmoEnabled : true
)

SCGateway.shared.setup (config: config)
{
    success,
    error in if (success)
    {
        //init sdk successfull
    }
    else {
        //retry init
    }
}

Params :

  1. Gateway Name (required): This is a unique name given to every gateway consumer eg: gatewaydemo
  2. Broker Config (required): If you want to support only certain brokers use [<String array of supported broker names>] else the value can be an empty array or a nil

If selected brokers should be shown, pass comma separated broker keys, else ignore.
Possible values for brokers: aliceblue, angelbroking, axis, dhan, edelweiss, fisdom, fivepaisa, fundzbazar, groww, hdfc, icici, iifl, kite, kotak, motilal, trustline & upstox

public enum BrokerConfigType {
    case defaultConfig
    case custom([String])
}
  1. Environment (optional): This defines the URL environment to which all the gateway apis would point to Possible values
@objc public enum Environment: Int {
    case production
}
typedef SWIFT_ENUM(NSInteger, Environment, closed) {
  EnvironmentProduction = 1
};
  1. isLeprechaunActive (required): For Testing purpose only. The default value is false
  2. isAmoEnabled (required): To control after-market order placement.

📘

Note

  1. Re-initialize the user every time there is any change in the setup configuration.

  2. Setup method must be the first method to be fired. If the setup is not called all other methods will throw an error.

Step 3- Initialise user session

User initialization starts a session between the distributor and the gateway. Whenever there is a change in user session, this method needs to be triggered.

SCGateway.shared.initializeGateway(sdkToken: "<Insert SDK Token>") { success, error in
       if success {
           // Initialisation successfull
       } else {
      		// Initialisation failed
       }
 }
[SCGateway.shared initializeGatewayWithSdkToken:authToken completion:^( BOOL success, NSError * error) {
                    NSLog(@"Initialization triggered");
                    if (success) {
                        //Initialisation success
                    } else {
                        [self showAlert:@"Failure" message:@"Init Failure"];
                    }
                }];

Params :

  1. sdkToken (required): JWT with the information of user signed using a shared secret between smallcase API and gateway backend. Learn more about Using JWT
  2. completion (optional): Result type with success(bool) and error. Triggered after initialisation is completed.

Step 4- Triggering SDK Method

A. For transactional flows

Transactional flows are those user journeys where interaction with their broker is required to complete the flow. For example - placing stocks / smallcase order, importing user holdings, connecting broker account to your app.

smallcase Gateway assigns a unique transactionId for each such user intent. The transactionId is a short-lived identifier that represents a single user interaction session.

i - Create transactionId

The transactionId can be created by making a server-to-server request to create transactionId API with relevant order config. The API call must be made from your backend (it is critical that secrets not be used on the app).

So whenever your user wants to perform transaction action, your app must call your backed with relevant order config, which in turn will hit smallcase Gateway's create transactionId API and respond back with transactionId.

Create transactionId API reference -

ii - Call triggerTransaction SDK method

To start the actual transactional flow, call the triggerTransaction method.

func connectGateway(transactionId: String) {  
        do {
            try SCGateway.shared.triggerTransactionFlow(transactionId: transactionId,
                                                        presentingController: self) { [weak self]  result in
                switch result {
                case .success(let response):
                  //Transaction successfull
                  
                  //Switch response for transaction intent
                    switch response {
                    	case let .connect(response):
                       	// Transaction success response of intent CONNECT
                      
                      case let .transaction(smallcaseAuthToken, transactionData):
                      	// Transaction success response of intent TRANSACTION
                      
                    	default:
                        return
                   	}
                
               case .failure(let error):
                    // Transaction Failure
                }
            }
        }
        catch SCGatewayError.uninitialized {
          // Catch exception here if Gateway SDK is not initialised
          // Initialise SDK
        }
        catch let err {
            // Any other exception
        }
    }
[SCGateway.shared triggerTransactionFlowWithTransactionId: transactionId presentingController:self completion:^(id response, NSError * error) {
              if (error != nil) {
                  NSLog(@"%@", error.domain);
                  [self showAlert:@"Failure" message:[NSString stringWithFormat:@"%@ %ld",error.domain,(long)error.code]];
                  return ;
              }

              if ([response isKindOfClass: [ObjcTransactionIntentTransaction class]]) {

                  ObjcTransactionIntentTransaction *trxResponse = response ;
                  NSLog(@"response: %@", trxResponse.transaction);
                  // Decode Base64 encoded string response
                  NSData *decodedStringData = [[NSData alloc] initWithBase64EncodedString:trxResponse.transaction options: 0];
                  NSString *decodedResponse = [[NSString alloc] initWithData:decodedStringData encoding:1];
                  NSLog(@"%@", decodedResponse);
                  [self showAlert:@"Success" message:decodedResponse];
                 // NSLog(trxResponse.)
              }

          }];

Params :

  1. transactionId (required): a unique string that you received from backend in the previous step
  2. presentingController (required): current viewController reference.

B. For Non-transactional flows

i - Call relevant SDK method

DescriptionSDK Method
Broker account openingtriggerLeadGen
Logout from smallcase platformbrokerLogout

(More details in Non-transactional flow section)

Step 5 - Save order response

Order response is shared in the onSucess() block of the triggerTransaction method as well as over API webhooks
Check response structure here

In case the transaction is not placed with the broker, any error is available in the onError block

A list of transaction errors is available here


Non-transactional flows

📘

Note:

In order to use any of the following methods, the gateway session should be initialized with relevant user data.

Broker Account Opening

To trigger account opening flow call triggerLeadGen method which is available in SCGateway class.

SCGateway.shared.triggerLeadGen (
	presentingController: self,
	params: params
)
[SCGateway.shared triggerLeadGenWithPresentingController:[[[UIApplication sharedApplication] keyWindow] rootViewController] params:params];

Params

  1. presentingController (required): Current view controller reference.

  2. params (optional): pass user information in a dictionary or nil if no user information is passed.

  • params can have one or more of the following string keys containing user details:
  • name - Full name
  • email - Email address
  • contact - Contact number

The keys inside the params object are optional.

And for all relevant keys passed to the triggerLeadGen method, the SDK will pre-populate relevant user data in the signup flow, ensuring a smooth user experience.

Logout from smallcase platform

This method is particularly useful when your users want to switch accounts for the same broker. When triggered, this method will make sure that the user gets logged out from the smallcase platform. So that the next time user interacts with smallcase Gateway, they will be asked to log in again.

Note: This flow is only available for connected users.

SCGateway.shared.logoutUser (
    presentingController : self,
    completion : { (success, error) in 
      if (success) {
            // Logout Successfull
        }
        else {
            // Logout Failure
        }
    }
)

Params

  1. presentingController (required): Current view controller reference.

Show Orders

This will display a list of all the orders that a user recently placed. This includes pending, successful, and failed orders.

SCGateway.shared.showOrders(presentingController: self) {
  success, error in
  	if success{
      /**
    	* success is true once user closes the Order List page successfully.
    	*/
    } else {
      /**
    	* Gateway flow ended before viewing the Order List page
    	* https://developers.gateway.smallcase.com/docs/transaction-errors#show-orders-error
    	*/
    }
}

Params

  1. presentingController (required): Current view controller reference.