简体   繁体   中英

How to integrate Paytm payment gateway in Swift

I have checked all the tutorial and also did a lot of R & D on gateway integration. But didn't find a way to integrate paytm payment gateway.

func paymentConfiguration()
{
    var orderDict = [AnyHashable: Any]()
    orderDict["MID"] = "WorldP64425807474247"
    orderDict["CHANNEL_ID"] = "WAP"
    orderDict["INDUSTRY_TYPE_ID"] = "Retail"
    orderDict["WEBSITE"] = "worldpressplg"
    orderDict["TXN_AMOUNT"] = "1"
    orderDict["ORDER_ID"] = ViewController.generateOrderID(withPrefix: "")
    orderDict["CALLBACK_URL"] = "https://securegw.paytm.in/theia/paytmCallback?ORDER_ID=<ORDER_ID>"
    orderDict["CHECKSUMHASH"] = "w2QDRMgp1/BNdEnJEAPCIOmNgQvsi+BhpqijfM9KvFfRiPmGSt3Ddzw+oTaGCLneJwxFFq5mqTMwJXdQE2EzK4px2xruDqKZjHupz9yXev4="
    orderDict["REQUEST_TYPE"] = "DEFAULT"
    orderDict["CUST_ID"] = "1234567890"
    var order = PGOrder(params: orderDict)
}



func openPaytmController()
{
    PGServerEnvironment.selectServerDialog(view, completionHandler: {(_ type: ServerType) -> Void in
        var txnController = PGTransactionViewController.initTransaction(forOrder: order)
        if type != eServerTypeNone {
            txnController.serverType = type
            txnController.merchant = mc
            txnController.delegate = self
            self.show(txnController)
        }
    })
}

Any help would be greatly appreciated. Thanks in advance

**

PayTM Integaration with swift with detail

**

##Download paytm sdk## https://github.com/Paytm-Payments/Paytm_iOS_App_Kit Make sure the dynamic lib and systemConfiguration.framwork is added in “Linked binaries and frameworks”

Add bridging header file into the project

        #import "PaymentsSDK.h"

You have to generate CheckSumHash key - PayTm unique key for transaction purpose

Pass the below parameters to generate checkSumHash

 let params:[String: Any] = [
            "CUST_ID”:<Your Customer ID>,  // you have to generate unique customer ID (Generate random string - less than 50 length count )
            "TXN_AMOUNT":"10.00", // sample amount
              “MID": <Your merchant ID>, 
             "ORDER_ID”:<Your Order ID>, // you have to generate unique order ID  (Generate random string - less than 50 length count )
             "INDUSTRY_TYPE_ID":"Retail",   //Staging Environment  
              "CHANNEL_ID":"WAP", //Staging Environment  
              "WEBSITE":"APPSTAGING",  //Staging Environment  - Mobile
             "CALLBACK_URL":"https://securegw-stage.paytm.in/theia/paytmCallback?ORDER_ID=\(<Your Order ID>)” // This should be important one and make sure the correct order ID. 
  ]

In your server , You have to setUp the the file that should generate CheckSumHash key based on the given parameters and merchant key (Which is stored in the file; Don't use inside your app ). That should be your CHECKSUM URL along with the above mentioned parameter. And finally, we get the CheckSumHash in the response

You have to given the above mentioned parameters along with checkSumHash (which you got the response - refer :step 3) to imitate PGTransactionViewCOntroller

       let params:[String: Any] = [
            "CUST_ID”:<Your Customer ID>,  // you have to generate unique customer ID (Generate random string - less than 50 length count )
            "TXN_AMOUNT":"10.00", // sample amount
              “MID": <Your merchant ID>, 
             "ORDER_ID”:<Your Order ID>, // you have to generate unique order ID  (Generate random string - less than 50 length count )
             "INDUSTRY_TYPE_ID":"Retail",   //Staging Environment  
              "CHANNEL_ID":"WAP", //Staging Environment  
              "WEBSITE":"APPSTAGING",  //Staging Environment  - Mobile
             "CALLBACK_URL":"https://securegw-stage.paytm.in/theia/paytmCallback?ORDER_ID=\(<Your Order ID>)”  // This should be important one and make sure the correct order ID. ,“CHECKSUMHASH”:<your geenrated CheckSumHash key> // which you got the response of generate CheckSumHash
]

  let order = PGOrder(params: params)

    let txnController = PGTransactionViewController(transactionFor: order)
    txnController?.serverType = eServerTypeStaging
    txnController?.merchant = PGMerchantConfiguration.default()
    txnController?.merchant.checksumGenerationURL = CheckSumGenerationURL
    txnController?.merchant.merchantID = "FlotaS90100524961231"
    txnController?.merchant.checksumValidationURL = CheckSumVerifyURL + orderID
    txnController?.loggingEnabled = true
    txnController?.merchant.website = "APPSTAGING"
    txnController?.merchant.industryID = "Retail"
    txnController?.serverType = eServerTypeStaging
    txnController?.delegate = self

    self.navigationController?.pushViewController(txnController!, animated: true)

PayTM delegates to handle response

func didSucceedTransaction(controller: PGTransactionViewController, response: [NSObject : AnyObject]) {
        print(response)
    }

    func didFinishedResponse(_ controller: PGTransactionViewController!, response responseString: String!) {
        print(responseString) // Response will be in string 
         let data = responseString.data(using: .utf8)!
    let obj = JSON(data: data)
    if obj["STATUS"].stringValue != "TXN_SUCCESS" {
       //handle what you want             
    }
     }
    }
    func didFailTransaction(_ controller: PGTransactionViewController!, error: Error!, response: [AnyHashable : Any]!) {
        print(error)

    }

    func didCancelTrasaction(_ controller: PGTransactionViewController!) {
        print("User camcelled the trasaction")
        controller.navigationController?.popViewController(animated: true)
    }

    func errorMisssingParameter(_ controller: PGTransactionViewController!, error: Error!) {
        print(error.localizedDescription)
        controller.navigationController?.popViewController(animated: true)
    }

Try this code:

func showController(controller: PGTransactionViewController) {

    if self.navigationController != nil {
        self.navigationController?.pushViewController(controller, animated: true)
    } else {
        self.present(controller, animated: true, completion: nil)
    }
}

func removeController(controller: PGTransactionViewController) {

    if self.navigationController != nil {
        self.navigationController?.popViewController(animated: true)
    } else {
        controller.dismiss(animated: true, completion: nil)
    }
}

//Creat Payment----------------
func creatPayment(CheckSum: String) {

    let mc = PGMerchantConfiguration.default()!
    var orderDict = [String : Any]()
    orderDict["MID"] = "WorldP64425807474247";
    orderDict["ORDER_ID"] = ViewController.generateOrderID(withPrefix: "");
    orderDict["CUST_ID"] = "1234567890";
    orderDict["INDUSTRY_TYPE_ID"] = "Retail";
    orderDict["CHANNEL_ID"] = "WAP";
    orderDict["TXN_AMOUNT"] = self.FINAL_AMOUNT;
    orderDict["WEBSITE"] = "APP_STAGING";
    orderDict["CALLBACK_URL"] = "https://pguat.paytm.com/paytmchecksum/paytmCallback.jsp";
    orderDict["CHECKSUMHASH"] = CheckSum;

    let pgOrder = PGOrder(params: orderDict )
    let transaction = PGTransactionViewController.init(transactionFor: pgOrder)
    transaction!.serverType = eServerTypeStaging
    transaction!.merchant = mc
    transaction!.loggingEnabled = true
    transaction!.delegate = self
    self.showController(controller: transaction!)
}

func didFinishedResponse(_ controller: PGTransactionViewController!, response responseString: String!) {
    print(responseString)
 }

func didCancelTrasaction(_ controller: PGTransactionViewController!) {
    print("CANCELLED")
}

func errorMisssingParameter(_ controller: PGTransactionViewController!, error: Error!) {
    self.removeController(controller: controller)
    print(error)
}

You have given the checksum as hardcore so, when the paytm decode your checksum and comapare with your parameters, the comparison will get fail. so you need to provide a new checksum when ever you make a payment.

The main thing you need to be care is that, the given parameters for checksum generation and payment setup should be same. Checksum can be generated in the backend with the help of checksum generation kit provided by paytm

you should call the func creatPayment(CheckSum: String) in success of Generate checksumApi and give the checksum to the argument in the function

In Swift 5.0 Follow the following steps:-

1:- Follow these steps to download and import the library in your project:-

  1. Download SDK from:- https://github.com/Paytm-Payments/Paytm_iOS_App_Kit

    Open your project in XCode and from the File menu, select Add files to "your project"

    Select Paytm.framework in the directory you just unzipped

    Make sure 'Copy items if needed' is checked and click 'Add' Under "Link Binary With Libraries" in the "Build Phases" tab of your project settings, add SystemConfiguration.framework

    Check if PaytmSDK.framework is added in both “Link Binary With Libraries” and “Embedded Binaries”. If not, add by clicking on the plus icon.

Import PaytmSDK to ViewController

 import PaymentSDK

Generate ChecksumHash

Security parameters to avoid tampering. Generated using server-side checksum utility provided by Paytm. Merchant has to ensure that this always gets generated on the server. Utilities to generate checksum hash is available

Add code on your payment ViewController to execute the payment process

     var txnController = PGTransactionViewController()
     var serv = PGServerEnvironment()
     var params = [String:String]()
     var order_ID:String?
     var cust_ID:String?


   func beginPayment() {
    serv = serv.createStagingEnvironment()
    let type :ServerType = .eServerTypeStaging
    let order = PGOrder(orderID: "", customerID: "", amount: "", eMail: "", mobile: "")
    order.params = ["MID": "rxazcv89315285244163",
        "ORDER_ID": "order1",
        "CUST_ID": "cust123",
        "MOBILE_NO": "7777777777",
        "EMAIL": "username@emailprovider.com",
        "CHANNEL_ID": "WAP",
        "WEBSITE": "WEBSTAGING",
        "TXN_AMOUNT": "100.12",
        "INDUSTRY_TYPE_ID": "Retail",
        "CHECKSUMHASH": "oCDBVF+hvVb68JvzbKI40TOtcxlNjMdixi9FnRSh80Ub7XfjvgNr9NrfrOCPLmt65UhStCkrDnlYkclz1qE0uBMOrmuKLGlybuErulbLYSQ=",
        "CALLBACK_URL": "https://securegw-stage.paytm.in/theia/paytmCallback?ORDER_ID=order1"]
    self.txnController =  self.txnController.initTransaction(for: order) as! PGTransactionViewController
    self.txnController.title = "Paytm Payments"
    self.txnController.setLoggingEnabled(true)
    if(type != ServerType.eServerTypeNone) {
        self.txnController.serverType = type;
    } else {
        return
    }
    self.txnController.merchant = PGMerchantConfiguration.defaultConfiguration()
    self.txnController.delegate = self
    self.navigationController?.pushViewController(self.txnController, animated: true)
 }

Change "CHECKSUMHASH": value in params that comes from API

    order.params["CHECKSUMHASH"] = checkSum // API checkSum value

confirm the protocol-delegate of 'PGTransactionDelegate' to Handle error and success responses

To handle success/errors on completion of payment, implement "didFinishedResponse", "didCancelTrasaction", "errorMisssingParameter" methods of the "PGTransactionDelegate". Code snippet provided below:-

extension PaymentViewController : PGTransactionDelegate {
//this function triggers when transaction gets finished
func didFinishedResponse(_ controller: PGTransactionViewController, response responseString: String) {
    let msg : String = responseString
    var titlemsg : String = ""
    if let data = responseString.data(using: String.Encoding.utf8) {
        do {
            if let jsonresponse = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:Any] , jsonresponse.count > 0{
                titlemsg = jsonresponse["STATUS"] as? String ?? ""
            }
        } catch {
            debugLog("Something went wrong")
        }
    }
    let actionSheetController: UIAlertController = UIAlertController(title: titlemsg , message: msg, preferredStyle: .alert)
    let cancelAction : UIAlertAction = UIAlertAction(title: "OK", style: .cancel) {
        action -> Void in
        controller.navigationController?.popViewController(animated: true)
    }
    actionSheetController.addAction(cancelAction)
    self.present(actionSheetController, animated: true, completion: nil)
}
//this function triggers when transaction gets cancelled
func didCancelTrasaction(_ controller : PGTransactionViewController) {
    controller.navigationController?.popViewController(animated: true)
}
//Called when a required parameter is missing.
func errorMisssingParameter(_ controller : PGTransactionViewController, error : NSError?) {
    controller.navigationController?.popViewController(animated: true)
  }
}

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