简体   繁体   中英

How to integrate Atom payment gateway in iOS app?

I am new to static library with extension.a, I am trying to impliment atom tech payment gateway to an iOS app. They provide 2 files 1.libAtomPayLib(Live).a 2.libAtomPayLib(UAT).a And a very brief documentation

As per their documentation I have added.a files to project, "added other link flag" "$(OTHER_LDFLAGS) -ObjC".

There is one point in the documentation which I didn't understand

Add Bundle ”resourcesLib” in Build Phases selecting your project target(Copy Bundle Resources).

The following code is from documentation

    #import <UIKit/UIKit.h>
#import "nb.h"
#import "card.h"
#import "NSString+DES.h"
#import "NSData+DES.h"

@interface ViewController : UIViewController <NSXMLParserDelegate,nbDelegate,cardDelegate>
{
NSXMLParser *parser;
}
@property (weak, nonatomic) IBOutlet UIButton *InitiateRequest;
@property (nonatomic,retain) NSXMLParser *parser;

-(IBAction)callVC:(id)sender;//Call for all transaction


@end

I tried to use this code in a viewcontroller.h file, but i am getting error "nb.h not found" I guess these headers are from the library, if it is linked with the project properly nb.h will available everywhere. I am also adding the documentation details

ATOM Mobile SDK Integration

The Atom mobile integration is designed to enable you to process payments through mobile applications.

Integration Type:- Non-Seamless:

Setup

•   Create new Group in your project hierarch & add all the files from “payAtom” in it.
•   Select your Project from Left Panel
•   Go to targets tab & select the application
•   Go to Build Setting & select Basic & Combined Tabs
•   Add the following property as shown below

If you cannot find “Other Linker Flags” then you can do these steps below

•   Select the project file from the project navigator on the far left side of the window.

•   Select the target for where you want to add the linker flag.

•   Select the "Build Settings" tab

•   Choose "All" to show all Build Settings.

•   Scroll down to the "Linking" section, and double-click to the right of where it says "Other Linking Flags".
•   A box will appear, Click on the "+" button to add a new linker flag.

•   Type "$(OTHER_LDFLAGS) -ObjC" (no quotes) and press enter.





•   Add Bundle ”resourcesLib” in Build Phases selecting your project target(Copy Bundle Resources).

Integration:

•   Merchant will design a screen wherein he will accept all the required fields including the bank detail, payment options and card details.
•   Pass the data to Library as follows in the same format:

ViewController.h File

#import <UIKit/UIKit.h>
#import "nb.h"
#import "card.h"
#import "NSString+DES.h"
#import "NSData+DES.h"

@interface ViewController : UIViewController <NSXMLParserDelegate,nbDelegate,cardDelegate>
{
NSXMLParser *parser;
}
@property (weak, nonatomic) IBOutlet UIButton *InitiateRequest;
@property (nonatomic,retain) NSXMLParser *parser;

-(IBAction)callVC:(id)sender;//Call for all transaction


@end

ViewController.m File

#import "ViewController.h"
#import "nb.h"
#import "card.h"


@interface ViewController ()

@end

@implementation ViewController
@synthesize parser;
    •   (void)viewDidLoad { [super viewDidLoad];
}

    •   (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}






-(IBAction)callVC:(id)sender
{

nb *netB = [[nb alloc] init]; netB.myDelegate = self; netB.loginid=@"459"; netB.txnscamt=@"0"; netB.loginid=@"459"; netB.password=@"Test@123"; netB.prodid=@"NSE"; netB.txncurr=@"INR"; netB.clientcode=@"001"; netB.custacc=@"100000036600"; netB.amt=@"100.000"; netB.txnid=@"9Q6";//unique each time
netB.date=@"23/08/2010%2011:57:00";//unique each time netB.bankid=@"2001"; netB.ru=@"https://paynetzuat.atomtech.in/paynetz/param"; [self presentViewController:netB animated:YES completion:nil];
}


-(void)secondviewcontrollerDissmissed:(NSString *)stringToFirst
{
NSString *getResult; getResult = stringToFirst;
NSLog(@"received---->%@",getResult); //This will return status success or Fail of Transaction
}

@end

This is an issue with atom payment gateway, they should provide ah file along with.a file, but it is not available in the downloaded files. So I used an alternative solution using web view to integrate atom payment gateway. I have created a class for get payment url. This method uses the web payment gateway used in the web site for the same project.

import Foundation
import Alamofire
import SwiftyXMLParser

class PaymentData {

    var totalPrice:String
    var taxId:String
    var userName:String
    var email:String
    var mobile:String
    var userId:String
    var currentDateTimeString:String
    init(totalPrice:String) {

        let time = Date().timeIntervalSince1970
        let taxId = "WVC"+String(time)
        let userId = UserDefaults.standard.string(forKey: "UserId")
        let name = UserDefaults.standard.string(forKey: "full_name")
        let phone = UserDefaults.standard.string(forKey: "phone")
        let email = UserDefaults.standard.string(forKey: "email")

        self.totalPrice = totalPrice
        self.taxId = taxId
        self.userId = userId!
        self.email = email!
        self.mobile = phone!
        self.userName = name!
        self.currentDateTimeString = NSDate().getStringWith(format: "dd/MM/yyyy")!

    }

    func getVenderUrl()->String{
        // Create vender url using user details
        var vVenderURL:String = "https://payment.atomtech.in/paynetz/epi/fts?login=test&pass=test@123&ttype=NBFundTransfer&prodid=test&amt=" + "\(totalPrice)"+"&txncurr=INR&txnscamt=0&ru=https://www.test.in/payment-success&clientcode=lisas00940&txnid="+"\(taxId)"+"&date="+"\(currentDateTimeString)"+"&udf1="+"\(userName)"+"&udf2="+"\(email)"+"&udf3="+"\(mobile)"+"&udf4=Bangalore&custacc="+"\(userId)"+"";

        vVenderURL = vVenderURL.replacingOccurrences(of: " ", with: "%20")
        print(vVenderURL)
        return vVenderURL

    }

    func getRedirectUrl(callBack:@escaping (URL)->Void){
        // get url to load in webview
        var xmlURL:String = ""
        var xmlttype:String = ""
        var xmltoken:String = ""
        var xmltempTxnId:String = ""
        var xmltxnStage:String = ""


        let headers: HTTPHeaders = [
            "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
            "Accept": "application/json"
        ]

        // Call api for get payment url to load in webview
        Alamofire.request(getVenderUrl(), method: .get, parameters: nil, encoding: URLEncoding.default, headers: headers)
            .responseString { response in

                var statusCode = response.response?.statusCode

                switch response.result {
                case .success:
                   // parsing xml data recieved from response, and extracting element required for generating the payment url
                    if let string = response.result.value {
                        print("XML: \(string)")
                        let xml = try! XML.parse(string)
                       print(xml["MMP","MERCHANT","RESPONSE"])
                        xmlURL = xml["MMP","MERCHANT","RESPONSE","url"].text!
                        let params = xml["MMP","MERCHANT","RESPONSE","param"]


                        for param in params {

                            if (param[0].attributes["name"])  == "ttype" {
                                xmlttype = param.text!
                            }
                            if (param[0].attributes["name"])  == "tempTxnId" {
                                xmltempTxnId = param.text!
                            }
                            if (param[0].attributes["name"])  == "token" {
                                xmltoken = param.text!
                            }
                            if (param[0].attributes["name"])  == "txnStage" {
                                xmltxnStage = param.text!
                            }

                        }

                        // creating payment url from extracted data
                        var  Atom2Request:String = "\(xmlURL)" + "?ttype=" + "\(xmlttype)" + "&tempTxnId=" + "\(xmltempTxnId)" + "&token=" + "\(xmltoken)" + "&txnStage=" + "\(xmltxnStage)";
                        Atom2Request = Atom2Request.replacingOccurrences(of: " ", with: "%20") //(" ", "%20");
                        print("ATOM 2nd Request URl" + "\(Atom2Request)")
                        callBack(URL.init(string: Atom2Request)!)


                    }
                case .failure(let error):
                    statusCode = error._code // statusCode private
                    print("status code is: \(String(describing: statusCode))")
                    print(error)
                }
        }

    }
}

This class helps to create data for generating url for atom payment gateway, next step is to load this url to a web view

Create a view controller and add web view in it, and add the following code

@IBOutlet weak var paymentWebView: UIWebView!
    var paymentAmount:String?
    override func viewDidLoad() {

        super.viewDidLoad()
        self.title = "Payment Gateway"
        if paymentAmount != nil {

            let paymentData = PaymentData.init(totalPrice: paymentAmount!)
            paymentData.getRedirectUrl(callBack:{ url in

                let request = URLRequest(url: url)
                self.paymentWebView.loadRequest(request)


            })

        }

    }

Implementing Atom Payment Gateway In Swift Is Just Easy..

Just follow the simple steps.

  1. Download the SDK from the below link. https://www.atomtech.in/help-resource/payment-gateway-integration-kits

  2. Unzip the file.

  3. Run the 'testSample.xcodeproj' in Xcode in iOS device. Don't worry the code is in Objective C.

  4. Create your own Swift project.

  5. Inside your project create a folder 'include'. Create another nested folder 'AtomPayLib' under 'include' folder.

  6. Drag all the header files (.h) including 'resourceLib.bundle' from the testSample project to your project folder 'AtomPayLib'. Don't forget to check the tick box for your Target.

  7. Just create any Objective C ViewController class to you project. Xcode will ask you to add Bridging Header to your project. Choose Yes. After the Bridging header added delete the newly created Objective class.

  8. Add the below two lines inside your Bridging Header. #import "nb.h" #import "card.h"

  9. Inside your 'AtomPay' button which you can take wherever you like in your project write the below code. The delegate method is also written just below it. Don't forget to add the method. Also add the conformance 'nbDelegate' to your ViewController class.

     //MARK: Atom Payment @IBAction func atomPay(_ sender: Any) { var netB = nb() netB.discriminator = "All" netB.myDelegate = self netB.merchantId = "197" netB.txnscamt = "0" netB.loginid = "197" netB.password = "Test@123" netB.txncurr = "INR" netB.clientcode="007" netB.custacc="100000036600" netB.amt = "100.00" netB.txnid = "013"; netB.date = "23/08/2019 11:57:00" netB.bankid = "2001" netB.signatureRequest = "KEY123657234" netB.signatureResponse = "KEYRESP123657234" netB.prodid = "NSE" netB.isLive = false netB.ru = "https://paynetzuat.atomtech.in/mobilesdk/param" // netB.customerName = "ABC"; // netB.customerEmailID = "abc@gmail.com"; // netB.customerMobileNo = "5555555555"; // netB.billingAddress = "Kolkata"; // netB.optionalUdf9 = "Peter"; self.present(netB, animated: true) { print("Completed...") }

    }

     func secondviewcontrollerDissmissed(_ stringForFirst: String,: withResponseKeys ResponseKeyArray, NSMutableArray:, andResponseValues ResponseValueArray. NSMutableArray.) { print("received---->%@".stringForFirst.) let deadlineTime = DispatchTime:now() + .seconds(5) DispatchQueue.main.asyncAfter(deadline: deadlineTime) { print("test") //code to be executed on the main queue after delay }

    }

  10. Run your app in your iOS device.

Cheers!

Usually a static library (like libAtomPayLib.a) contains just code, but not UI resources (like images, sounds, fonts, config files etc.). One way to solve it is to provide a resource bundle. A bundle is actually a directory containing various file inside, but on macOS (with programs like Finder) it looks like a single file (for example resourcesLib.bundle ). If you just add such file to your project Xcode (by default) will actually add it to your "copy bundle resources" phase. You can check that by going to TARGETS, select your target, open "Build Phases", and expanding "Copy Bundle Resources".

代码截图

After you have built your app you can actually make sure that the bundle was copied by expanding "Products" group, right-click your Example.app "Show in Finder", then right click that file and "Show Package Contents". You should see what files are copied inside your app, including the resources bundle.

If you add some "test.a" static library file to your project the default Xcode behaviour is to add it to "Linked Frameworks and Libraries" list. You can verify it by going to TARGETS, select your target, open "General" and scroll down to "Linked Frameworks and Libraries".

代码截图 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM