Friday, 20 November 2015

Notifications Style in Android

Introduction:

Android Jelly Bean (API level 16) Google has improved a lot of features and introduced new features. One of them is the Notification. Now they have made the notification more versatile by introducing media rich notification. Google has come up with three special style of notification which are mentioned below. Even developer can write his own customized notification style using Remote view. The old Notification class constructor has been deprecated and a brand new and enhanced version of Notification has been introduced.

Notification Type:

  • Basic Notification – Shows simple and short notification with icon.
  • Big Picture Notification – Shows visual content such as bitmap.
  • Big Text Notification – Shows multiline Textview object.
  • Inbox Style Notification – Shows any kind of list, e.g messages, headline etc. 
  • Custom Notification – Shows the custom notification with custom layout.

             Old syntax requires us to create an object of notification but now Android uses builder patter to create the notification object. Notification.Builder class has been introduced to make this task easier. This class returns the builder object which is configurable according to your requirements.
The helper classes have been introduced like Notification.BigPictureStyle, Notification.BigTextStyle, and Notification.InboxStyle. These classes are re-builder classes which take object created by Notification.Builder class and  modify the behavior like so. For the backword compatibility in API Level below 16  there are the classes NotificationCompat.BigPictureStyle, NotificationCompat.BigTextStyle, and NotificationCompat.InboxStyle.
NotificationCompat.Builder is part of the Android Support Library and has a minimum API level of 4 while Notification.Builder is a part of Android and has a minimum API level of 11. By now, there is little benefit in supporting API levels below 16, so compatibility with previous API levels is not a good enough reason to use NotificationCompat.

Notification Priority:
Not all notifications are equally important. A notification’s priority specifies its importance and can take any of these values: Notification.PRIORITY_MIN, Notification.PRIORITY_LOW, Notification.
PRIORITY_DEFAULT, Notification.PRIORITY_HIGH, or Notification.PRIORITY_MAX.


Notification Category:

  1. Lock Screen Notifications : To view notifications prior to Android 5.0, users had to unlock their devices and open the notification drawer.
    In particular, the “when a device is locked” setting can take the following values:
    1. show all notification content: displays all notifications on the lock screen.
    2. hide sensitive notification content: this setting is only available on devices that have a secure lock screen (that is, one that requires a pattern, PIN, or password to unlock). If selected, the lock screen modifies the way certain notifications are displayed, as explained below.
    3. don’t show notifications at all: does not show any notifications on the lock screen.
A notification’s visibility parameter controls how they are displayed on the lock screen when “hide sensitive notification content” is selected:
      Notification.VISIBILITY_PUBLIC (default): shows the entire content of the notification.
      Notification.VISIBILITY_SECRET: completely hides a notification
      Notification.VISIBILITY_PRIVATE: shows a notification but replaces its content with generic or redacted text.

Note that notifications with a visibility of secret would still be displayed on the lock screen if “when a device is locked” is set to “show all notification content”. That is, while apps can specify the sensitivity of notifications, users have the final say as to how they’re displayed on the lock screen.

Implementing Public, Private, and Secret Notifications 
To implement a private or secret notification, simply replace setVisibility's parameter with Notification.VISIBILITY_PRIVATE or Notification.VISIBILITY_SECRET,respectively. The sample project implements notifications with these visibilities in the onPrivateNotificationClick and onSecretNotificationClick methods.
Implementation
1.Create a notification with the desired visibility.
                 Notification notification = new NotificationCompat.Builder(this)
                                         .setContentTitle("Public Notification")
                                         .setContentText("Public content here")
                                        .setSmallIcon(R.drawable.ic_stat_notify)
                                         .setCategory(Notification.CATEGORY_STATUS)
                                         .setVisibility(Notification.VISIBILITY_PUBLIC) 
                                         .build();
2.Issue the notification.
                NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
         notificationManager.notify(NOTIFICATION_ID, notification);
Implementing Private Notifications with a Public Version
When “hide sensitive notification content” is selected, the content of private notifications on the lock screen is hidden. In particular, the notification’s content title is replaced with the name of the activity that triggered the notification, and its content text is replaced with the text “Contents hidden.” Notifications can override this default behavior by providing an alternate “public version” that is shown on the lock screen. For instance, a chat notification could provide a public version that indicates how many messages have been received as opposed to showing the content of the messages.
Implementation
                        1.Create a public version for the notification.
                                        Notification publicNotification = new NotificationCompat.Builder(this)
                                                      .setContentTitle("Public Version Notification")
                                                      .setContentText("Redacted private content here")
                                                      .setSmallIcon(R.drawable.ic_stat_notify)
                                                      .setCategory(Notification.CATEGORY_STATUS)
                                                      .build();
                        2.Create the private notification and set the notification from step 1 as its public version.
                                        Notification notification = new NotificationCompat.Builder(this)
                                                      .setContentTitle("Private Notification")
                                                      .setContentText("Sensitive or private content here")
                                                      .setSmallIcon(R.drawable.ic_stat_notify)
                                                      .setCategory(Notification.CATEGORY_STATUS)
                                                      .setVisibility(Notification.VISIBILITY_PRIVATE)
                                                      .setPublicVersion(publicNotification)
                                                      .build();
                     3.Issue the private notification.
                                     NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
                                     notificationManager.notify(NOTIFICATION_ID+2, notification);

2. Heads-up Notifications:  An interruptive priority is either Notification.PRIORITY_HIGH or Notification.MAX. A notification that has both an interruptive priority and an alert is called an interruptive notification. When users receive an interruptive notification in Android 5.0, it initially appears as a heads-up notification, which is a small floating window that allows users to immediately view and interact with notifications without having to check the notification drawer.
Implementation
             1.Create a notification with an interruptive priority and an alert.
                                    Notification notification = new NotificationCompat.Builder(this)
                                                     .setContentTitle("High priority")
                                                     .setContentText("Important message here")
                                                     .setSmallIcon(R.drawable.ic_stat_notify)
                                                     .setPriority(Notification.PRIORITY_HIGH)
                                                     .setDefaults(Notification.DEFAULT_ALL)
                                                     .setCategory(Notification.CATEGORY_STATUS)
                                                     .build();
          2.Issue the notification.
                         NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
                         notificationManager.notify(NOTIFICATION_ID, notification);
     3.Rich Notifications: Rich notifications, which were introduced with Android Jellybean (API 16), let you create notifications with large content areas, images, and buttons. These rich notification features 
            let you display a lot more information in a notification than you are able to display in a standard notification. Rich notifications have two states: a normal state and an expanded state. To expand
           a notification, users must swipe down on the notification with two fingers. Additionally, the notification may appear expanded by default if there is enough available room.
               Chat applications such as Hangouts deliver a notification every time you receive one or more messages. While only short messages can be displayed in standard notifications, rich notifications can display messages with long text and pictures.

      4. BigTextStyle Notification: Some chat messages are very long, but a standard notification’s content text can only show a single line of text. Before rich notifications were available, the user would have to tap the notification to open the app and see the rest of the chat message. A type of rich notification called a BigTextStyle notification shows multiple lines of text when the notification is expanded. When it’s not expanded, the notification shows the same content as a standard notification.
Implementation
                    1.Create an instance of NotificationCompat.BigTextStyle.
                            String longText = "Without BigTextStyle, only a single line of text would be visible. " +"Any additional text would not appear directly on the notification. " +"The entire first line would not even be on the notification if it were too long! " +"Text that doesn't fit in a standard notification becomes ellipsized. " +"That is, the characters that don't fit are removed and replaced by ellipsis.";
                           NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle().bigText(longText);
                         
                  2. Create a notification and set its style to bigTextStyle.
                                    Notification bigTextStyleNotification = new NotificationCompat.Builder(this)
                                              .setContentTitle("All Hail BigTextStyle")
                                              .setContentText(longText)
                                              .setSmallIcon(R.drawable.ic_stat_notify)
                                              .setContentIntent(activityPendingIntent)
                                              .setCategory(Notification.CATEGORY_STATUS)
                                              .setStyle(bigTextStyle)
                                              .build();
                3. Issue the notification.
                                    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
                                    notificationManager.notify(NOTIFICATION_ID, bigTextStyleNotification);

The notification should be able to stand by itself regardless of whether or not it’s expanded.That is, users will not necessarily see both the normal and the expanded notification. Your app should continue to work without any major disruptions no matter which version of the notification the user views.

       5.BigPictureStyle Notification:  If you receive a picture as a chat message, you can display it in an expanded notification with BigPictureStyle. If the notification is not expanded, it will look just like a standard notification.
 Implementation
                       1.Create an instance of NotificationCompat.BigPictureStyle.
                     Bitmap bigPicture = BitmapFactory.decodeResource(getResources(), R.drawable.mandrill);
                     String contentText = "A classic image processing test image.";
                     String summaryText = "This mandrill is often used as a test image.";
                     NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle()
                                      .setSummaryText(summaryText)
                                      .bigPicture(bigPicture);

The BigPictureStyle summary text replaces the content text while the notification is expanded. Also note that the maximum height of the big picture is 256dp.
                     2. Create a Notification and set its style to bigPictureStyle.
                     PendingIntent activityPendingIntent = getActivityPendingIntent();
                     Notification bigPictureStyleNotification = new NotificationCompat.Builder(this)
                                          .setContentTitle("Rando Fact")
                                          .setContentText(contentText)
                                          .setSmallIcon(R.drawable.ic_stat_notify)
                                          .setContentIntent(activityPendingIntent)
                                          .setCategory(Notification.CATEGORY_STATUS)
                                          .setStyle(bigPictureStyle)
                                          .build();
                    3.Issue the notification.
                               NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
                     notificationManager.notify(NOTIFICATION_ID, bigPictureStyleNotification);

      6. InboxStyle Notification: With InboxStyle, you can preview multiple messages in the expanded notification, one per line.If the notification is not expanded, it behaves like a standard notification.
Implementation
                     1.Create a helper method that formats a single line of the expanded notification.
                 private Spannable formatInboxStyleLine(String username, String message) {
                           Spannable spannable = new SpannableString(username + " " + message);
                           int color = getResources().getColor(R.color.notification_title);
                           spannable.setSpan(new ForegroundColorSpan(color), 0, username.length(),
                           Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);.
                           return spannable;
                    }
               2.Create an instance of NotificationCompat.InboxStyle.
                NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle()
                                .addLine(formatInboxStyleLine("Alice", "hey there"))
                                .addLine(formatInboxStyleLine("Bob", "what are you doing?"))
                                .addLine(formatInboxStyleLine("Eve", "give me a call when you get a chance"))
                                .addLine(formatInboxStyleLine("Trudy", "I like potatoes"))
                                .addLine(formatInboxStyleLine("Mallory", "Dinner tomorrow?"));
                       The addLine method takes a CharSequence to display in the expanded notification.A CharSequence is the superclass of String, so you could pass a String into addLine. In this
case, however, we want to use the formatted Spannables from the first step.
              3.Create a Notification and set its style to inboxStyle.
                     PendingIntent activityPendingIntent = getActivityPendingIntent();
                     Notification inboxStyleNotification = new NotificationCompat.Builder(this)
                                          .setContentTitle("5 messages received")
                                          .setContentText("Alice, Bob, Eve, Trudy, Mallory")
                                          .setSmallIcon(R.drawable.ic_stat_notify)
                                          .setPriority(Notification.PRIORITY_HIGH)
                                          .setContentIntent(activityPendingIntent)
                                          .setCategory(Notification.CATEGORY_MESSAGE)
                                          .setStyle(inboxStyle)
                                          .build();
           4. Issue the notification.
                               NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
                               notificationManager.notify(NOTIFICATION_ID, inboxStyleNotification);
      
         7.Custom Notifications: 

            This notification has a few interesting features:
    • The normal (unexpanded) notification has buttons.
    • The expanded notification has three lines of text, and
    • both versions have a “close” button at the right.

These features cannot be implemented without custom layouts. Regular notifications can’t use custom layouts and they can’t display any actions when unexpanded. Custom notifications are more complicated to implement than regular notifications and should be used sparingly. If you can display all the content you deem essential in regular notifications, then you should not use a custom notification. “But custom layouts can make my notifications stand out, man!” you say. I completely agree. However, when users look at notifications, they won’t be wowed by your out-of-the-box thinking, but rather distracted
and annoyed.
Implementation
1.Create the layouts for your custom notifications.
                  The standard (that is, unexpanded) view and the expanded view are two different layouts. In this example, we’ll borrow these layouts directly from the Play Music app (and modify them
only slightly). You can find them in the book’s example source code. The standard layout is in res ➤ layout-v11 ➤ statusbar.xml and the expanded layout is in res ➤ layout-v16 ➤
statusbar_expanded.xml.
2.Create the PendingIntents that are triggered by actions. 
           PendingIntent pausePendingIntent =getMediaCommandPendingIntent(MediaCommandService.ACTION_PAUSE);
           PendingIntent nextPendingIntent =getMediaCommandPendingIntent(MediaCommandService.ACTION_NEXT);
           PendingIntent prevPendingIntent =getMediaCommandPendingIntent(MediaCommandService.ACTION_PREV);
           PendingIntent closePendingIntent =getMediaCommandPendingIntent(MediaCommandService.ACTION_CLOSE);



3.Create an instance of RemoteViews and initialize it with the standard layout (that is, the one in statusbar_expanded.xml).
           RemoteViews contentView = new RemoteViews(getApplicationContext().getPackageName(),R.layout.statusbar);
                      contentView.setImageViewResource(R.id.albumart, R.drawable.bg_default_album_art);
                      contentView.setTextViewText(R.id.trackname, "Song Name");
                      contentView.setTextViewText(R.id.artistalbum, "Artist Name");
                      contentView.setOnClickPendingIntent(R.id.playpause, pausePendingIntent);
                      contentView.setOnClickPendingIntent(R.id.next, nextPendingIntent);
                      contentView.setOnClickPendingIntent(R.id.veto, closePendingIntent);
RemoteViews is essentially a view that can be displayed in another process. This requirement limits the types of views that can be used in layouts for RemoteViews.

4.Create the Notification and set contentView as its content.
          PendingIntent activityPendingIntent = getActivityPendingIntent();
          Notification customNotification = new NotificationCompat.Builder(this)
                    .setContentTitle("Song Name")
                    .setContentText("Artist Name")
                    .setSmallIcon(R.drawable.ic_stat_notify)
                    .setPriority(Notification.PRIORITY_HIGH)
                    .setContentIntent(activityPendingIntent)
                    .setCategory(Notification.CATEGORY_TRANSPORT)
                    .setContent(contentView)
                    .setOngoing(true)
                    .build();

The call to setOngoing(true) prevents the user from swiping the notification away. Since the user is always aware of whether a music app is running (even if it’s in the background), an ongoing notification guarantees that the user always gets proper feedback. That is, it guarantees that a notification will always be present when there is music playing. The user can still dismiss the notification by pressing the “close” button. In a real implementation,pressing close would also stop the music.
We’ll create the expanded view in the next few steps. 
5.create a helper method that returns true if running Jellybean (API level 16) or above.
            private boolean isJellybeanOrAbove() {
              return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;
            }
6.Set the expanded content view only if running Jellybean (API 16) or above. Trying to set the expanded view on any previous version of Android would result in a crash.
         if(isJellybeanOrAbove()) {
               RemoteViews expandedNotificationView =new RemoteViews(getApplicationContext().getPackageName(),R.layout.statusbar_expanded);
               expandedNotificationView.setImageViewResource(R.id.albumart,R.drawable.bg_default_album_art);
               expandedNotificationView.setTextViewText(R.id.trackname, "Song Name");
               expandedNotificationView.setTextViewText(R.id.artist, "Artist Name");
               expandedNotificationView.setTextViewText(R.id.album, "Album Name");
               expandedNotificationView.setOnClickPendingIntent(R.id.playpause, pausePendingIntent);
               expandedNotificationView.setOnClickPendingIntent(R.id.prev, prevPendingIntent);
               expandedNotificationView.setOnClickPendingIntent(R.id.next, nextPendingIntent);
               expandedNotificationView.setOnClickPendingIntent(R.id.veto, closePendingIntent);
               customNotification.bigContentView = expandedNotificationView;
          }

Note that the expanded content view must be set directly on the notification and not on the Builder.
7.Issue the notification.
             NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
             notificationManager.notify(NOTIFICATION_ID, customNotification);

Reference:
  1. http://developer.android.com/training/notify-user/index.html
  2. http://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html
  3. http://www.javacodegeeks.com/2013/10/android-notificationlistenerservice-example.html
  4. http://stackoverflow.com/questions/15350998/determine-addaction-click-for-android-notifications
  5. http://www.programcreek.com/java-api-examples/index.php?api=android.support.v4.app.NotificationCompat
  6. http://code4reference.com/2012/07/android-jelly-bean-notification/
  7. http://www.scriptscoop.net/t/2269661ee9bc/notification-bar-icon-turns-white-in-android-5-lollipop.html
  8. https://books.google.co.in/books?id=OOkmCAAAQBAJ&pg=PA33&lpg=PA33&dq=set+NotificationCompat.Builder+set+Public+Version+in+android&source=bl&ots=UScY9hHQYi&sig=X22xLSF3IF6-50upr9n0ZWgrLDI&hl=en&sa=X&ved=0CEEQ6AEwBWoVChMI9-abpNDiyAIVYZSmCh2FxQFp#v=onepage&q&f=false

Friday, 30 October 2015

PayUMoney Integration in Android Application

Hello Friends,

Today I am going to share about how you can integrate PayUMoney in your application to make flexible transactions.

Introduction:

       PayU is the Online Payment Gateway to accept Payments Online. PayU is India's most comprehensive payment gateway with credit cards, debit cards and net banking.Go live with all payment options fastest in India.


PayU Group is owned by Naspers MIH that provides services base on different media and communication technologies all over the world. PayU is a comprehensive operator of online payments. The highest level of provided services is guaranteed by innovative technological platforms,high functionality,stable development as well as a wide and constantly extended offer.

The aim of PayU is to integrate existing online payment services and develop new ones as well as provide tools to facilitate e-commerce activity in the web. PayU supports mostly all the frameworks available like HTML,PHP,ASP,ASP.NET,VB.NET,JAVA,Ruby on Rails,Perl,Paython. PayU avails you the readymade kits for mentioned frameworks and renowned shopping carts to make the integration easy.
  • A wide range of credit card,debit card,internet and mobile banking options.
  • Secure and flexible payments to existing bank accounts of merchants.
  • Faster settlements and instant reports on dropped transactions.
  • Verified By Visa & Master Card Secure Code enabled gateway.
  • Ability to offer services on the Web,Mobile & IVR.
PayU Payment Gateway
                PayU offers electronic payment services to merchant website through its partnerships with various banks and payment instrument companies. Through PayU, the customers would be able to make electronic payments through a variety of modes which are mentioned below:
  • Credit cards
  • Debit cards
  • Online net banking accounts
  • EMI payments
  • Cash Cards
  • Email Invoicing
  • IVR
  • Cash on Delivery (COD)
PayU also offers an online interface (known as PayU Dashboard) using the username and password provided to you, where the merchant has access to various features like viewing all the transaction details, settlement reports, analytical reports etc.Through this interface, the merchant can also execute actions like capturing, cancelling and refunding the transactions. 


Payment Process Flow



The following diagram explains how the customer makes the payment and how the process flows:



  • Step 1: The consumer selects the product on your website and clicks on “Pay Now” button.
  • Step 2: The consumer is then taken from your website to the transaction page of www.payumoney.com where in all the payment related details are entered by the consumer.
  • Step 3: Payumoney.com.com redirects the consumer to Visa, MasterCard or the relevant bank for the next level of authorization.
  • Step 4: The Bank/Visa/MasterCard authorizes and confirms the transaction.
  • Step 5: The consumer is sent back to PayUMoney.
  • Step 6: PayUMoney sends the consumer back to your website along with the transaction status.


Status of a Transaction

A transaction can have several different statuses as explained below.
  1. Not Started – The transaction has not been started yet.
  2. Initiated – The transaction has been started but not completed.
  3. Money With PayUMoney– The transaction was successful and the transaction amount is with PayUMoney.
  4. Under Dispute – A dispute for the transaction has been raised.
  5. Refunded – The entire amount of the transaction has been refunded.
  6. Partially Refunded – A part of the amount of the transaction has been refunded.
  7. Bounced – Incomplete or no details provided at PayUMoney payment page.
  8. Failed – The transaction didn’t complete due to a failure.
  9. Settlement in Process – Settlement for the transaction is in process.
  10. Completed – The transaction is settled and complete.

PayUMoney Integration Methods:

The merchant can integrate with PayU by using one of the below methods:

        1) Non-Seamless Integration In this mode during the transaction, the customer would be re-directed from merchant website to PayU payment page. On the PayU payment page, he would need to select the payment option and enter the respective card details. After this, PayU would re-direct the customer to the desired bank webpage for further authentication.

        2) Seamless Integration - In this mode, the merchant needs to collect the customer card details on their own website and post them to PayU. Here, the customer would not be stopped at PayU payment page at all, as the payment option and card details are already received from the merchant. The merchant must be PCI-DSS certified in this case. For further information on PCI-DSS certification please contact your Account Manager at PayU.

         Also, the merchant website can be based either on a shopping cart or can be developed by the
merchant (not based upon any shopping cart). Based on the type (out of these two), PayU would
provide integration kit (code) to the merchant which they needs to incorporate at their end.

Steps for Integration Process

The steps for integrating with PayU can technically be described as below:

         1) To start off the integration process, you would be provided a test setup by PayU where you would be given a test merchant account and test credit card credentials to have a first-hand experience of the overall transaction flow. Here, you need to make the transaction request on our test server (and not the production server). Once your testing is complete, then only you will be ready to move to the PayU production server.

        2) To initiate a transaction, the merchant needs to generate a POST REQUEST - which must consist of mandatory and optional parameters. This POST REQUEST needs to be hit on the below mentioned PayU URLs:

           For PayU Production (LIVE) Server:

                         POST URL: https://secure.payu.in/_payment


          For PayU Test Server:

                            POST URL: https://test.payu.in/_payment

  • Test Key  JBZaLc
  • Test Salt – GQs7yium
  • Test Card Name: any name
  • Test Card Number: 5123456789012346
  • Test CVV: 123
  • Test Expiry: May 2017


In order to integrate your website with PayUMoney, you can use our test server and test key if your

application is not yet approved.


Please note that the Key and Salt for test server are different and should be used only with test server.The purpose of the test server & Key-Salt is to enable you to integrate and do test transaction. It cannot be used for actual transactions from your website.

    Key notes and terms
  • Key (MerchantID) : This ID is generated at the time of activation of your site and helps to uniquely identify you to PayUMoney.
  • TxnID: A Unique alphanumeric Transaction ID generated by you to uniquely identify a transaction. The TxnID should be unique since it would allow you to identify the transaction easily.
  • Amount: Amount is the total amount of the transaction (greater than 0) in INR, without a currency symbol or other non-numeric character. Only a decimal allowed.
  • MIHPayID: Unique ID generated for a transaction by PayU.in.
  • Hash (Checksum): This refers to a random numeric string generated using a mathematical algorithm to ensure that data is not tampered along the way. Let’s say a message has to be sent from location X to Y. X and Y both mutually agree on a Secret Key called “Salt” that only both of them possess. A checksum is generated by a mathematical function using the message and the Salt as input. This checksum is then sent along with the message to Y. Y then recalculates this checksum using the Salt and the same algorithm. If the checksum that Y calculates is different from the checksum that X passed then the data was tampered along the way and is thus rejected.

       The Checksum algorithm used is SHA2 which is globally well known algorithm. To need help with implementation, feel free to call us, mail us or use Google to find the desired function library for your implementation. Some example codes are also mentioned at the end of this document.

  • Product Info: It is a json encoded array of various payment parts where each part contains ‘name’,‘description’, ‘value’ and ‘isRequired’ fields. JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate.
It is based on a subset of the JavaScript Programming Language. JSON is a text format that is completely language independent.

The format of the json encoding for productinfo is as follows:-


 Productinfo={  
  “paymentParts”: [  
   {  
    "name": "abc",  
    "description": "abcd",  
    "value": "500",  
    "isRequired": "true",  
    “settlementEvent”: “EmailConfirmation”  
   },  
   {  
    "name": "xyz",  
    "description": "wxyz",  
    "value": "1500",  
    "isRequired": "false",  
    “settlementEvent”: “EmailConfirmation”  
   }  
  ],  
  {  
   “paymentIdentifiers”: [  
    {  
     "field": "CompletionDate",  
     "value": "31/10/2012” },   
 { "field":"TxnId", "value":"abced" }]}  


            3) In the merchant initiated POST REQUEST, one of the mandatory parameters is named as
hash. The details of this hash parameter have been covered in the later section. But it is absolutely critical for the merchant to calculate the hash correctly and post to us in the request.

           4) When the transaction POST REQUEST hits the PayU server, a new transaction entry is
created in the PayU Database. To identify each new transaction in the PayU Database, a unique identifier is created every time at PayU’s end. This identifier is known as the PayU ID (or MihPayID).

           5) With the POST REQUEST, customer would be re-directed to PayU’s payment page. Customer now selects the particular payment option on PayU’s page (Credit Card/Debit Card/Net Banking etc) and clicks on ‘Pay Now’. PayU re-directs the customer to the chosen bank. The customer goes through the necessary authorization/authentication process at bank’s login page, and the bank gives the success/failure response back to PayU.

           6) PayU marks the transaction status on the basis of response received from Bank. PayU provides the final transaction response string to the merchant through a POST RESPONSE. The parameters in this response are covered in the subsequent sections.

           7) In the POST RESPONSE sent by PayU, you would receive the final status of the transaction. You will receive the hash parameter here also. Similar to step 3, it is absolutely crucial to verify this hash value at your end and then only accept/reject the invoice order. This is done to strictly avoid any tampering attempt by the user.



DISCLAIMER:

1. Test URL: The Test URL is provided to PayU merchants to test the integration of their server with that of PayU or Bank. It is understood that since this is merely a Test URL, the Merchant should not treat any transactions done on this Test server as live and should not deliver the products/services with respect to any such test transactions even in the case your server receive a successful transaction confirmation from PayU/Bank.

2. Merchants are herein forth requested to set up required control checks on their (merchant)
systems/servers to ensure that only those transactions should get routed to the PayU test server
which are initiated with sole intention of test the environment.


Additional Charges – Convenience Fee Model (To be used only if recommended by Account Manager at PayU)

There are 2 different methods to implement Additional Charges on PayU.

Method 1: Enabled from backend at PayU


The merchant would be posting the transaction amount of the product in the transaction request.



1) Once the customer lands on PayU payment page and clicks on 'Pay Now' option, the additional amount would be added to the amount of the product by PayU (based upon the TDR values) and the total amount would be passed on to the bank’s page while re-directing.


2) After PayU receives the status of transaction from the bank, it sends the response of back to
the merchant. In this response, the amount and additional amount can be differentiated with the below parameters.

  • Original Transaction Amount - amount
  • Additional Amount -   additionalCharges
3) Once you receive the response from PayU, you need to check for reverse hash. If you are verifying the reverse hash at your end (which is strictly recommended to avoid any tamper cases), its formula will also change in case additionalCharges value is sent. 

Here, if the additionalCharges parameter is posted in the transaction response, then hash formula is:

sha512(additionalCharges|SALT|status||||||udf5|udf4|udf3|udf2|udf1|email|firstname|productinfo|amount|txnid|key)

4) If additionalCharges parameter is not posted in the transaction response, then hash formula
is the generic reverse hash formula:

sha512(SALT|status||||||udf5|udf4|udf3|udf2|udf1|email|firstname|productinfo|amount|txnid|key)


Method 2: Merchant Calculates and Posts Additional Charges to PayU

1) The merchant would be posting both the transaction amount and additional charges in the transaction request. The parameters used for these are amount and additional_charges respectively. 
The way to pass the additional_charges parameter is as below:

<bankcode1> :< additional charge value>, < bankcode2> :< additional charge value>
Example: CC:12,AMEX:19,SBIB:98,DINR:2,DC:25,NB:55

2) In this method of applying additional charges, hash sequence would be affected for both Pre-Transaction and Post-Transaction.

Pre-Transaction hash sequence:

Merchant needs to form the below hash sequence before posting the transaction to PayU:

sha512(key|txnid|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5||||||SALT|additional_charges)

Where additional_charges value would be same as the value posted in transaction request.
For example, CC:12,AMEX:19,SBIB:98,DINR:2,DC:25,NB:55


3) Now, once the transaction request hits PayU server and re-direction happens, the customer lands upon PayU payment page. Here, depending on the payment option selection by the customer, the additional charge value would be added to transaction amount. For example, for the above example, if the customer selects Credit Card, Rs 12 would be added to the transaction amount. If the customer selects AMEX option, Rs 19 would be added to the transaction amount. For SBI Net Banking, Rs 98 would be added to the transaction amount and so on. Please note that the additional charges would be added only once the customer clicks on ‘Pay Now’ option.

4) When PayU receives the response from Bank, a POST Response is sent to the merchant.
Here also, the hash sequence needs to be changed.

Post-Transaction hash sequence:

Merchant needs to form the below hash sequence and verify it with the hash sent by PayU
in the Post Response:

sha512(additionalCharges|SALT|status||||||udf5|udf4|udf3|udf2|udf1|email|firstname|productinfo|amount|txnid|key)

Where, additionalCharges value must be same as the value Posted from PayU to the
merchant in the response.


5) This hash value must be compared with the hash value posted by PayU to the merchant. If both match, then only the order should be processed. If they don’t match, then the transaction has been tampered with by the user and hence should not be processed further.


Important Things to remember: Characters allowed for parameters
  • For parameters address1, address2, city, state, country, product info, email, and phone following characters are allowed:
  • Characters: A to Z, a to z, 0 to 9
  • -(Minus)
  • _ (Underscore)
  • @ (At the Rate)
  • / (Slash)
  • (Space)
  • . (Dot)
If the merchant sends any other special characters then they will be automatically removed. The address parameter will consider only first 100 characters.

Formula for hash (checksum) after transaction

This time the variables are in reverse order and status variable is added between salt and udf1.

sha512(SALT|status||||||udf5|udf4|udf3|udf2|udf1|email|firstname|productinfo|amount|txnid|key)

It is absolutely mandatory that the hash (or checksum) is computed again after you receive
response from PayU and compare it with post back parameters below. This will protect you from any tampering by the user and help in ensuring safe and secure transaction experience.

Reference:
For more details here i am sharing the integration documents and sdk download links.


2. Android SDK - 
         Integration Steps - Integration Document PayU Android SDK v3.0.pdf
         Android SDK (Custom browser included) Android-SDK
        Android Sample App (see branches) Android-SDK-Sample-App
3.Android Custom Browser - 
         Integration Steps - Integration Document PayU Android Custom Browser.pdf
         Android Custom Browser Download - Android-Custom-Browser
         Android Custom Browser Sample App Download - CBWithoutSDK


Thank you.