How to Integrate Payu Money in Swift

How to integrate PayU Money in swift

This answer is taken from PayU documentation itself, i am answering here just because it took me hours to implement with their documentation.

Hi i can guide you with NON seamless integration.
https://github.com/payu-intrepos/Documentations/wiki/8.-iOS-SDK-integration#nonseamless

In non seamless integration PayU is already providing UI and will handle the card type and all payment process and at the end you will be notified for the status of your transaction with reason if failed and all details.

Download the SDK from Here:https://github.com/payu-intrepos/iOS-SDK-Sample-App/archive/3.8.1.zip

From Sample code copy file from "BusinessLayer" folder.

So i hope you have all required files now we can go further with integration.

You are integrating PayU with swift, as there is no swift SDK is not present from PayU team we have to proceed with Briding to Objective-C .
You can find about this here:How to call Objective-C code from Swift

Once header file is created and configured in build setting, import the following Headers of SDK

#import "PayU_iOS_CoreSDK.h"
#import <CommonCrypto/CommonHMAC.h>
#import "PUUIPaymentOptionVC.h"
#import "PUSAWSManager.h"
#import "PUSAWSManager.h"
#import "PUSAHelperClass.h"

Now we are ready to use PayU SDK into our environment/project.

Create new instance of 3 main object used for payment
1)Payment parameters
2)Hash Values
2)Helperclass// to calculate hash value

paste this above your viewDidLoad()

let paymentParam: PayUModelPaymentParams  = PayUModelPaymentParams()
var hashes :PayUModelHashes = PayUModelHashes()
let PUSAhelper:PUSAHelperClass = PUSAHelperClass()

Here is function i have created for further processing

func continueWithCardPayment()  {

paymentParam.key = "gtKFFx"
paymentParam.transactionID = "umangtxn123"
paymentParam.amount = "100.0"
paymentParam.productInfo = "Nokia"
paymentParam.SURL = "https://google.com/"
paymentParam.FURL = "https://facebook.com/"
paymentParam.firstName = "Umang"
paymentParam.email = "umangarya336@gmail.com"
paymentParam.environment = ENVIRONMENT_MOBILETEST
paymentParam.udf1 = "udf1"
paymentParam.udf2 = "udf2"
paymentParam.udf3 = "udf3"
paymentParam.udf4 = "udf4"
paymentParam.udf5 = "udf5"
paymentParam.offerKey = "" // Set this property if you want to give offer:
paymentParam.userCredentials = ""

PUSAhelper.generateHashFromServer(self.paymentParam) { (hashes, errorString) in
self.hashes = hashes
self.paymentParam.hashes = hashes
self.callPaymentGateway()
}
}

func callPaymentGateway() {

let webServiceResponse :PayUWebServiceResponse = PayUWebServiceResponse()

webServiceResponse.getPayUPaymentRelatedDetailForMobileSDK(paymentParam) { (paymentDetail, errString, extraParam) in

if errString == nil {

let payOptionVC: PUUIPaymentOptionVC = loadVC("PUUIMainStoryBoard", strVCId: VC_IDENTIFIER_PAYMENT_OPTION) as! PUUIPaymentOptionVC

payOptionVC.paymentParam = self.paymentParam
payOptionVC.paymentRelatedDetail = paymentDetail

runOnMainThread({
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.paymentResponseReceived(_:)), name: kPUUINotiPaymentResponse, object: nil)
self.navigationController?.pushViewController(payOptionVC, animated: true)
})
}
else{
print("Failed to proceed for payment : \(errString)")
}
}
}

There are some My custom function that will through error at your side you copy paste, i am mentioning them here. Do take care of them

1)loadVC("PUUIMainStoryBoard", strVCId: VC_IDENTIFIER_PAYMENT_OPTION)
//Loadvc function i have created to load view controller, you have to change it as you call your view controller

2)runOnMainThread({
// This function is for running code on main thread.

I have used all test credentials provided by PayU team
you can find more in their doc :https://www.payumoney.com/pdf/PayUMoney-Technical-Integration-Document.pdf

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.paymentResponseReceived(_:)), name: kPUUINotiPaymentResponse, object: nil)

//With this line we are adding notification sent by payment gateway to notify us regarding the status of the payment process, lets cash the notification.

func paymentResponseReceived(notify:NSNotification) {
print(notify)
}

You will get the response in notify.object.
You can find more sophisticated language and way at their document:https://github.com/payu-intrepos/Documentations/wiki/8.-iOS-SDK-integration.

Hope this answer may help you.

How to integrate PayUMoney iOS SDK in swift project?

To integrate Obj-C libraries into a Swift Project all you have to do is use a so-called Bridging Header. Those literally work as bridge between the Obj-C code and the Swift code. Here is an exact representation from the Apple Docs:
Explanation Basically what this does it let's Swift access everything through the one header file and for Obj-C it generates a .m file with all methods and other code.

  1. To add a bridging header, simply create a new File -> iOS -> Source -> CocoaTouch -> UIViewcontroller and then as language select Objective-C. You can name it yourNewlyCreatedClass for example.
    whatever you want as we'll later delete it.
  2. Once you do that you will get this Pop Up:
    Pop Up asking you if you want to create the bridging header.
    Select the create function and open the newly created file that should be named something like Briding-Header.h
  3. Now, you can remove the line that say #import
    "yourNewlyCreatedClass.h"
    and replace it with #import
    <PayUMoney/PayUMoney.h>
    or whatever the framework is called.
  4. To finish up, you can now delet the two created classes from before. Simply select yourNewlyCreatedClass.h and yourNewlyCreatedClass.m and you're good to go.

    Congrats, now you can access any of the methods you see in their docs through simply typing them in your swift file.

For further reference, please advise the Apple Docs found here. Images were used from the official Apple Docs.

Hope that helps,
Julian

PayUMoney payment gateway issue

I found answer successfully. My working code is listed below

int i = arc4random() % 9999999999;
NSString *strHash = [self createSHA512:[NSString stringWithFormat:@"%d%@",i,[NSDate date]]];// Generatehash512(rnd.ToString() + DateTime.Now);
NSString *txnid1 = [strHash substringToIndex:20];
NSLog(@"tnx1 id %@",txnid1);
NSString *key = @"JBZaLc";
NSString *amount = @"1000";
NSString *productInfo = @"Nice product";
NSString *firstname = @"Mani";
NSString *email = @"mani.ingenius@gmail.com";
NSString *phone = @"1234566";
NSString *surl = @"www.google.com";
NSString *furl = @"www.google.com";
NSString *serviceprovider = @"payu_paisa";

NSString *hashValue = [NSString stringWithFormat:@"%@|%@|%@|%@|%@|%@|||||||||||GQs7yium",key,txnid1,amount,productInfo,firstname,email];
NSString *hash = [self createSHA512:hashValue];
NSDictionary *parameters = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:txnid1,key,amount,productInfo,firstname,email,phone,surl,furl,hash,serviceprovider
, nil] forKeys:[NSArray arrayWithObjects:@"txnid",@"key",@"amount",@"productinfo",@"firstname",@"email",@"phone",@"surl",@"furl",@"hash",@"service_provider", nil]];
__block NSString *post = @"";
[parameters enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if ([post isEqualToString:@""]) {
post = [NSString stringWithFormat:@"%@=%@",key,obj];
}else{
post = [NSString stringWithFormat:@"%@&%@=%@",post,key,obj];
}

}];

NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://test.payu.in/_payment"]]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
[request setHTTPBody:postData];

[_webviewSample loadRequest:request];

then functions to be used

-(NSString *)createSHA512:(NSString *)string
{
const char *cstr = [string cStringUsingEncoding:NSUTF8StringEncoding];
NSData *data = [NSData dataWithBytes:cstr length:string.length];
uint8_t digest[CC_SHA512_DIGEST_LENGTH];
CC_SHA512(data.bytes, (CC_LONG)data.length, digest);
NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA512_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_SHA512_DIGEST_LENGTH; i++)
[output appendFormat:@"%02x", digest[i]];
return output;
}

Payu money Payment GateWay Integration

#define Merchant_Key @"your merchant key "
#define Salt @"your salt key"
#define Base_URL @"https://secure.payu.in"

> //this base url in case of origional payment key's if you want to integarate with
test key's write base Url can check in payumoney Faq

**
#define Success_URL @"https://www.google.co.in/"
#define Failure_URL @"http://www.bing.com/"
#define Product_Info @"Denim Jeans"
#define Paid_Amount @"1549.00"
#define Payee_Name @"Suraj Mirajkar"
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:YES];
[self setTitle:@"Make A Payment"];
[self initPayment];
}

- (void)viewDidLoad {
[super viewDidLoad];
activityIndicatorView = [[UIActivityIndicatorView alloc] init];
activityIndicatorView.center = self.view.center;
[activityIndicatorView setColor:[UIColor blackColor]];
[self.view addSubview:activityIndicatorView];
}

-(void)initPayment {
int i = arc4random() % 9999999999;
NSString *strHash = [self createSHA512:[NSString stringWithFormat:@"%d%@",i,[NSDate date]]];// Generatehash512(rnd.ToString() + DateTime.Now);
NSString *txnid1 = [strHash substringToIndex:20];
strMIHPayID = txnid1;
NSString *key = Merchant_Key;
NSString *amount =[[NSUserDefaults standardUserDefaults]
stringForKey:@"orderprice"];

//NSString *amount = Paid_Amount;
NSString *productInfo = Product_Info;
NSString *firstname = Payee_Name;
NSString *email = [NSString stringWithFormat:@"suraj%d@yopmail.com",i];

//ADD A fake mail For Payment for testing purpose

// Generated a fake mail id for testing
NSString *phone = @"9762159571";
NSString *serviceprovider = @"payu_paisa";

NSString *hashValue = [NSString stringWithFormat:@"%@|%@|%@|%@|%@|%@|||||||||||%@",key,txnid1,amount,productInfo,firstname,email,Salt];
NSString *hash = [self createSHA512:hashValue];
NSDictionary *parameters = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:txnid1,key,amount,productInfo,firstname,email,phone,Success_URL,Failure_URL,hash,serviceprovider
, nil] forKeys:[NSArray arrayWithObjects:@"txnid",@"key",@"amount",@"productinfo",@"firstname",@"email",@"phone",@"surl",@"furl",@"hash",@"service_provider", nil]];
NSLog(@"%@",parameters);
__block NSString *post = @"";
[parameters enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if ([post isEqualToString:@""]) {
post = [NSString stringWithFormat:@"%@=%@",key,obj];
} else {
post = [NSString stringWithFormat:@"%@&%@=%@",post,key,obj];
}
}];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/_payment",Base_URL]]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
[request setHTTPBody:postData];
[_webviewPaymentPage loadRequest:request];
[activityIndicatorView startAnimating];
}
-(NSString *)createSHA512:(NSString *)string {
const char *cstr = [string cStringUsingEncoding:NSUTF8StringEncoding];
NSData *data = [NSData dataWithBytes:cstr length:string.length];
uint8_t digest[CC_SHA512_DIGEST_LENGTH];
CC_SHA512(data.bytes, (CC_LONG)data.length, digest);
NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA512_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_SHA512_DIGEST_LENGTH; i++) {
[output appendFormat:@"%02x", digest[i]];
}
return output;
}
#pragma UIWebView - Delegate Methods
-(void)webViewDidStartLoad:(UIWebView *)webView {
NSLog(@"WebView started loading");
}
-(void)webViewDidFinishLoad:(UIWebView *)webView {
[activityIndicatorView stopAnimating];
if (webView.isLoading) {
return;
}
NSURL *requestURL = [[_webviewPaymentPage request] URL];
NSLog(@"WebView finished loading with requestURL: %@",requestURL);
NSString *getStringFromUrl = [NSString stringWithFormat:@"%@",requestURL];
if ([self containsString:getStringFromUrl :Success_URL]) {
[self performSelector:@selector(delayedDidFinish:) withObject:getStringFromUrl afterDelay:0.0];
} else if ([self containsString:getStringFromUrl :Failure_URL]) {
// FAILURE ALERT
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Sorry !!!" message:@"Your transaction failed. Please try again!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
alert.tag = 1;
[alert show];
}
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
[activityIndicatorView stopAnimating];
NSURL *requestURL = [[_webviewPaymentPage request] URL];
NSLog(@"WebView failed loading with requestURL: %@ with error: %@ & error code: %ld",requestURL, [error localizedDescription], (long)[error code]);
if (error.code == -1009 || error.code == -1003 || error.code == -1001) { //error.code == -999
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Oops !!!" message:@"Please check your internet connection!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
alert.tag = 1;
[alert show];
}
}
- (void)delayedDidFinish:(NSString *)getStringFromUrl {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSMutableDictionary *mutDictTransactionDetails = [[NSMutableDictionary alloc] init];
[mutDictTransactionDetails setObject:strMIHPayID forKey:@"Transaction_ID"];
[mutDictTransactionDetails setObject:@"Success" forKey:@"Transaction_Status"];
[mutDictTransactionDetails setObject:Payee_Name forKey:@"Payee_Name"];
[mutDictTransactionDetails setObject:Product_Info forKey:@"Product_Info"];
[mutDictTransactionDetails setObject:Paid_Amount forKey:@"Paid_Amount"];
[self navigateToPaymentStatusScreen:mutDictTransactionDetails];
});
}

#pragma UIAlertView - Delegate Method
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (alertView.tag == 1 && buttonIndex == 0) {
// Navigate to Payment Status Screen
NSMutableDictionary *mutDictTransactionDetails = [[NSMutableDictionary alloc] init];
[mutDictTransactionDetails setObject:Payee_Name forKey:@"Payee_Name"];
[mutDictTransactionDetails setObject:Product_Info forKey:@"Product_Info"];
[mutDictTransactionDetails setObject:Paid_Amount forKey:@"Paid_Amount"];
[mutDictTransactionDetails setObject:strMIHPayID forKey:@"Transaction_ID"];
[mutDictTransactionDetails setObject:@"Failed" forKey:@"Transaction_Status"];
[self navigateToPaymentStatusScreen:mutDictTransactionDetails];
}
}

- (BOOL)containsString: (NSString *)string : (NSString*)substring {
return [string rangeOfString:substring].location != NSNotFound;
}

- (void)navigateToPaymentStatusScreen: (NSMutableDictionary *)mutDictTransactionDetails {
dispatch_async(dispatch_get_main_queue(), ^{
PaymentStatusViewController *paymentStatusViewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"PaymentStatusScreenID"];
paymentStatusViewController.mutDictTransactionDetails = mutDictTransactionDetails;
[self.navigationController pushViewController:paymentStatusViewController animated:YES];
});
}

Important Note : you can check your Merchant key and Salt in seller Dashboard after Login ... Go To my account and check your merchant key and salt


Related Topics



Leave a reply



Submit