Friday 14 October 2016

Getting Started with Android Wearable App Development - Basics

The wearable device is really useful where you need to check updates on the go without unlocking your phone and swiping the notification at regular interval. But one may claim that it's too much to have a wearable and getting notifications instead checking your phone. The design and way it syncs with your handheld device are awesome and even more awesome when apps respond you based on contexts like location, temperature and other conditions.

Getting Started with Android Wearable App Development - Basics

Scope :

Android wearable application development is really a broad topic where as it's growing drastically. Even now recently Google announced inbuilt android play store, the keyboard for wearable and last year they introduced emoji and WiFi support for wearable apps. we will see about basics of Android wearable development and types to support existing apps.

Prerequisites : 

1) Knowledge on Basics of Android development

Design for wearable API :

Wearable is meant for checking updates on the go and quick replies. It's not same as your handheld device to show all available information to the user. It must be optimised to show the relevant and Updated data to the user in regular intervals.

For example : consider the Weather app, which shows you weather details for next seven days in single activity and it's data structure will be like 
  • Min temperature
  • Max temperature
  • Type of weather condition ( cloudy, sunny, rainy or moderate )
  • Atmospheric Pressure details
But your wearable app doesn't need such amount of data to be displayed on that small screen. so choose wisely which is more relevant data for the user to adapt Round or square wearable devices. In my opinion what I'll choose is
  • Today's Min Temperature
  • Today's Max Temperature
  • Type of Weather condition as Drawable ( Bitmap )
with time and date.

So, It's important to focus more on design and relevant data to the end user based on context.

Getting Started with Android Wearable App Development - Basics

Types of Wearable Development 

Basically, whenever your app shows notification in your handheld device it will automatically push to the wearable device at no cost of coding it. But when you need to support it extensively with actions, paging additional information as slider you should support it via notification App compat support library.

1) Notifications App compat support library.
2) Watch Face design and Data communication and syncing.
3) Extensively designing UI and installing an app in wearable.

Notification App compat : 

Notification App compat is all about extending support for existing notification in wearable devices without writing additional code for wearable. with notification app compat library you can simply create a notification for your device and wearable devices with additional options such as Actions, Quick reply intents etc.

Watch Face Design : 

Basically, watch face is nothing but just like your home screen with widgets but it can run only one app at a time, showing multiple data such as temperature, steps your while jogging, the heartbeat can be obtained through content providers or sensors. There are tonnes of watch face in play store. Watch face is considered as a home screen where you can check regular and frequent updates.

It has two modes namely ,

1) Ambient Mode
2) Normal Mode

In the Ambient mode, your watch tries to save battery by not allowing to update the screen frequently. you will get the chance to get updates in minutes basis. Most specifically your watch face should use Black and white pixel colour while in the Ambient mode to save energy by repainting the view now and then. you can't able to update second hand in the clock where it requires every second update.

In normal mode, you are allowed to use colours and drawable but that doesn't require high resource and frequent updates that make your watch face unresponsive sometimes.

When the user is using we can switch over to normal mode, where other times wearable will be going automatically to ambient mode after the speicific interval of time.( checked in Moto 360) 

Designing UI for wearable :

Designing extensively for Android wearable using layouts such box inset layout, grid view pager, Watch view stubs and a variety of layout is supported by support libraries. Data communication API, Message API is available with Wearable API that comes under google play services, which delivers and sync data between the handheld device and a wearable device.


So we just covered the basics of Android Wearable App development which is different from app development in terms of Design and types to support your app. I'll soon publish the post on these types to designing and work with these API for wearable apps.

Recently Google announced that Wearable major update 2.0 preview that doesn't require a phone to be connected always. you can use it wherever you go and sync via the cloud. we're eagerly waiting for stable SDK support and watch yet to be released early 2017. For now preview 2.0 is available at official Android developer site.

For bugs, hugs just comment below. in case any doubts drop me a mail, or chat wiht me in G+/ Facebook. share is care.

Friday 7 October 2016

Facebook Account Kit Tutorial - Backend Verification using Node.js

Recently I have been developing secure production app using Facebook account kit for seamless authentication across mobile and web platform. Account kit is widely used in many apps such as Saavn and many other. I found that backend verification in Account kit for every request from mobile/ SPA should be handled manually by developers and no libraries available till date. so, I'm writing this post for Indie Game and mobile developers as a reference guide.

So what's Facebook Account kit all about ? 

It's seamless authentication method via OTP way to verify the user with Mobile Number and login into App without any passwords. Whereas it provides access token to verify the authenticated user in backend server without worrying about the access token generation, revocation logics. It's all about securing the access token and using it over HTTPS connection while connecting between your app and backend.

Facebook Account Kit Tutorial - Backend Verification using Node.js
Facebook Account Kit Tutorial - Backend Verification using Node.js

Prerequisites :

In this tutorial, we'll solely concentrate on Backend verification and authorising the legal request made by the apps.
  • Facebook Developer Account 
  • Good Knowledge on Node.js routeing
  • Rest API client
  • Good logical error handling skill

How Does Account Kit works ?

When the user signup using his mobile number, he would receive the OTP via SMS Carrier from facebook server. after authenticating OTP password, the account kit sdk gives you the long live Access token or Client side temporary exchange token(this depends on application).

  • With the received access token, securely post it your Mobile backend server (probably HTTPS to avoid man-in-the-middle attack)
  • with that access token you can call the Account Kit API end point to check that the access token is valid as well it provides you mobile number or E-mail
  • As response contains mobile number, you can identify the user and provide the user with the service appropriately.
  • Most important thing is you should pass the access token everytime from the client to the server in order to verify the authenticity of the user.

Getting Started :

You should have good knowledge in routeing technique since we are going to concentrate on Express.js, if you're beginner check out this link to learn more.

Concept :

Since we need to authenticate every request from the app that comes along with access token and others data we could write a middleware to authenticate the every request in the beginning before it executes the API code.

Middleware is nothing but a piece of code which is executed before each and every request entering our express routes. probably we need to write the Account kit verification code here and if it is a success we can make the request to propagate to the corresponding the function else just terminate the live request with authentication errors spitting.

Sample code : 

here is sample code to authenticate your mobile backend API end points. we use request module to send a get request to account kit server by providing the accesstoken in url param while if it responds with 200 status code, we are going to extract the mobile number else we are going to consider the request as failed on and informing to the client as error message. before trying this source code, in Facebook Developer dashboard turn off the App-secret required option and enable client access token flow.


That's it. this is base tutorial on verifying the backend for facebook account kit integrated development.
for any bugs/hugs comment below. For detailed source code and other information just comment below or mail me, chat with me in Google+ or facebook.share is care.

Wednesday 31 August 2016

P1 Popular Movies App - Udacity Android Nanodegree Recap and Review

Recently, became Udacity project reviewer where I would be reviewing Android Nanodegree Basics Course student project works.so, Continuing exciting the Nanodegree journey with Udacity, the second project was building popular movies application.This was challenging one to build because we need to use the same source-code to build for the next upcoming project which concentrates on extending the user interface for tablets too.so,let's see what we learnt and implemented as project.
P1 Popular Movies App - Udacity Android Nanodegree Recap and Review
Project Repo : link 

Scope of this project :

To understand & implement themoviedb.org api and performing networking operations in AsyncTask (background thread) and updating UI(main) thread.

Process and Concepts :

The ultimate aim of this project is

  • Connect mobile app with Cloud
  • Performing Network operations in background thread
  • loading images from Internet and deciding optimised sizes for corresponding views.
  • Clear understanding with RecyclerView or ListView working
  • Intents to navigate between activities 
  • Concentrating more on SavedInstance State Bundle

Concepts demystified :

We'll look into the above mentioned concepts with few lines and reference links which i've used to learn while building the App.

Connect mobile app with Cloud :

The first thing about android app it should fetch data from cloud or API or server with updated details and making sure it works offline by caching it in Sqlite database or sharedpreferences.This Google I/O session is the best session ever made to understand the networking operations coding approach while you build your app for the next billion users coming over online.


Developer reference : link

Loading Images from internet :

One of the major nightmare of mobile developer is out of memory error in java,it means you have consumed the Heap memory in VM and having strong reference to the objects created.since, we have created strong reference to the object GC can't collect it to free the VM Heap memory.especially, when you're about to load Bitmap through JPEG image into the memory it's really nightmare for developers to manage the memory. 

So, here comes Jake Wharton to help us with his image loading library named as Picasso and it also supports cache,recycling the images,animations and effects.
there are few other libraries named Glide,Fresco from facebook.

Developer reference : link

Clear understanding of ListView & Recyclerview :

Listview & Recyclerview is useful view for developers from google engineers is to show large homogeneous data in our mobile device.Consider you have 1000's of contacts in your contacts app where you need to show them all on demand, you can't load all the contacts in to memory at once where you may lead to Out of Memory error very soon.
Obviously, some Algorithmic students may claim  that we could use binary search algorithm to view the contacts, but in real life is the user is going to type and search contacts every time ? That will be a bad User Experience.
so,how does the listview or recyclerview works ?
yes we've learnt in our concepts of operating system namely Paging concept.when the listview gets initialise it measures the height of the layout and decides the number of list to be shown in the view and loads the particular count of data from adapter to the view, it also prefetches few data set front and back to manage stagger less scrolling.it uses the same object and recycles for other data set and inflates the view into the Listview.Note that Recyclerview is enhanced version of Listview.

difference between Listview and Recyclerview - Stackoverflow Link

Developer Reference : link

What the Hell is savedInstanceState bundle ?

before understanding the saving the instance state of View in android, you must be aware of the lifecycle of android application such as onCreate, onStop, onResume, onPause and even more for handling orientation and configuration changes.one of the best video to understand why we need concentrate more on Activity lifecycle.


so, when the apps move foreground and background we need to save our current state of the app so that it, can be resumed when the user once again visits the application.we need to manage this smoothly without any lag while recovering the state of the application.

consider the scenario :

when you type important whatsapp message to your friends/crush, all of a sudden you receive phone call from someone continuing you get facebook message from friend after replying back you come back to  whatsapp what if whole message has been destroyed which you have typed already ? It hurts User Experience so,here comes savedinstance state to guarantee you to save some text/image/serializable object for you in background to recover you back when user renters the app.

so, by default activity lifecycle callbacks such as onCreate, onResume , OnPause,onConfigurationChanged passes you bundle to save the state of the current activity before the lifecycle event happens.

Most popular guide for fragments and activity : inthecheesefactoy guide for savedinstancestate

Developer Reference : link 

That's it.These were the main challenges I faced and learnt during the Project 2 Android Nanodegree.hope the above resource will be helpful to get started with Android development.

My Screencast of the Project :

Next Project Preview :

The next project was awesome, it's all about using the same source code to optimize the android app to work for Tablet user Interface consuming large amount of user space and handling the orientation changes.

for bugs,hugs and comments just comment below or mail me.Chat with me in G+/Facebook for help and improved version of this article.Share is care.

Friday 8 July 2016

P0 Android Basics - Udacity Android Nanodegree Recap and Review

Udacity with Google has done excellent job in delivering standard and updated courses via Udacity android development courses with variety of categories such as Games,Beginners,Building App with Google API's and even more.They are also about to provide Associate Android Developer certificates by taking few test as projects over online as announced in Google I/O 2016.Me and My friends +venkat raman , Ajay are in track with Android Nanodegree course and projects.The course objective is to master basic Android concepts and adapt to future changes in design,coding style and updates.I'll try to reproduce the concept i learnt and applied during the project and passed reviews in this post.


Project Repo : Link

Process & Concepts :

The first project was just to build a mere Android app with specified layout,buttons and Onclick listeners implementations.(you can check my code).The goal was to ensure that users are able to work with Android studio and produce results from those by running it in emulator or phone.Luckily I have latest Android Smartphone with latest updates from Google.(6.0.1).

What I've Concentrated ?

  • Making my Java code readable one :D 
  • Concentrating on strings.xml file organising and not hard coding it.
    Though it was tough in beginning when you move forward and app grows in many countries and your user may expect in different languages,this technique will be scalable approach and managing it in one place.
  • writing reusable code in java - link
  • Few patient in testing in emulator,device.
Accomplishment of P0 - udacity android nanodegree





The next part was basics of Android such as components,form factors and do's and don't in the development process.with those installation and Android jargon such as Android API levels and Numbers,SDK levels,Compile version,Minimum and maximum SDK target levels and few more publishing techniques too.

Next Video Lectures :

The first section video consist of Android Studio tutorials,drag and drop widget tutorials and connecting the xml design file with java code and maintaining their lifecycle,connecting the app to the cloud with network code(http) and few views such ListView to handle huge amount of homogeneous data types.This leads to next level project as Popular Movies app by consuming themoviedb.org API to display popular movies running in nearby theatres.Mean while check out my Github repo and try practising it. 

Results : 

That's it and i've passed the project 0 with flying colours within a hour of starting the course :D with my friends +venkat raman and ajay.

Subscribe the blog for next upcoming recap and reviews.chat with me in G+/fb.for more discussion just leave a comment below.Thanks for reading.share is care.


Thursday 2 June 2016

Top 100 motivational Quotes - MotiveTown - Motivational App

Recently Launched Mobile & web app based on concept of motivating others using inspiring pictures and quotes from various sources such as simpleremainders,spiritofscience & Motivational guides.combining all resource and categorizing the quotes and images,generated a unified format to form a web service.Additional to this we've optimized the Image using opensource tools such as Imagemagick and few shell scripts to automate the process.We named the App as MotiveTown - Motivational App So,let's see about the various features implemented in mobile app below.



Download From Playstore | Download from Amazon Store - Rate and review the app at playstore/amazonstore

Why this App ?

Everyone needs motivation in some point of life either letting-go or to chase their dream,this makes us to search to read books,quotes,inspiring videos,lectures even in soundcloud for audio speech.Some peoples watch movies,videos where others check out magazines,daily.And targeting this fragmented categories,we decided to bring unified platform with personalized newsfeed contents with videos,audio and quotes with images via simple Mobile App.Thus as a result we were able to publish first version of this app with limited contents of news,images and quotes and features.

Why Ads ? 

We need to provide you reliable backend service without outages and crash.so, we rented a economy server package and customized backend to adapt daily updates.we too optimized several hundred KB image files to less than 100 KB JPG compressed files with automated scripts and Imagemagick opensource tools.so,to keep running these operations smooth and more faster we adopted ads to generate some amount to maintain hosting.

Categories - MotiveTown App

We have Daily updated 23+ categories of Motivational quotes 
• Achieving Gratitude
• Daily Inspiration
• Business Leadership
• Changing the World
• Community Thoughts
• Conquer Negativity
• Walking in Faith
• Various Saying
• Uplifting Music
• Success Secrets
• Staying Motivated
• Relationship Dynamics
• Recover and Loss
• Positive Thinking
• Overcoming Fear
• New Awakenings
• Mindful Living
• Letting Go
• Law of Attraction
• Impact Media
• Healthy Living
• Forgiveness
• Exploring Thoughts
About 23+ categories and 3000+ images,quotes,articles and videos combined we're making a unified platform for everyone to engage and get the benefits out of it.Download the MotiveTown - Motivational App from Playstore.

App description :

MotiveTown App Provides various categories of motivational quotes,images and text poems.Motivation is the Key point for everyone and that can act as turning point in their life.Push them Ahead with spirit in their mind to succeed and compete with others.It also providesMotivational quotes for success in Tamil,English and even more supported languages.Start your day with motivational quotes everyday category to get some random quotes and you can customize your own news feed for Motivational Quotes for Daily inspiration.Share quotes,images directly with your friends from the motivational quotes by great persons.

Screenshots :

check it out in playstore : Link


To Become Beta tester,developing for other platforms,exposing API's and join with me for further development drop me a mail : s.shivasurya@gmail.com or chat with me in G+ hangouts/Facebook.Don't forget to rate the App in Playstore.

Saturday 12 September 2015

Exploring HTML5 API for Enriched Web App Development & Experience

Few days back,somehow i noticed chrome browser way of handling and enhancing the API for web similar to the Apps that run on devices.Such as prompting for Notifications,locations,Vibrations,Offline Storage and even more API and making it more interesting to develop apps for Web and Web based mobile apps.So,skimming and getting deep into the API's using Javascript and enhancing the user experience and Developer experience.Using it Appropriately at right place at right time will really be gain on both sides.This tutorial will help you to get to know and learn about more powerful Javascript API.

Exploring HTML5 API for Enriched Web App Development & Experience

Reference : Demo | Download

Prerequisites :

  • HTML5 based web browser.(probably Chrome,which i love it more.)
  • few considerable skill to work on Javascript.
  • little patience to work with code.

Procedure :

we'll try to work on few API such as Notification API,Location API,Offline Storage API and with Server Sent Events.

Notification API : 

Notification plays vital part in showing new information received to the corresponding service and showing to the end users.you would have experienced this when you get an email notification when you work in desktop and getting chat notifications while working with other tabs.
function notify() {
if (!("Notification" in window)) {
alert("This browser does not support desktop notification");
} else if (Notification.permission === "granted") {
var notification = new Notification("Hi there!");
} else if (Notification.permission !== 'denied') {
Notification.requestPermission(function(permission) {
if (permission === "granted") {
var notification = new Notification("Shiva has Messaged You!");
}
});
}
}
from the above snippet we have written as function for notification handling,in which it requires users permission to send notification,So we are just requesting the user for the Permission as soon as user gives away the permission and callback function is invoked for making further actions.Note that always check for the permission before sending the notification and send only legit/reasonable notification because it may irritate users on seeing more notifications.And perform a check over the browser supports notification API in advance as initialization and perform the other related tasks.

Location API :

Location is another aspect for developers to choose languages,localtime or even advertisements and stats of the website may be useful for future purpose(Business decisions) and knowing about the website users geolocation.
function shareLocation() {
var output = document.getElementById("out");
if (!navigator.geolocation) {
output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
return;
}

function success(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;

output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>';

var img = new Image();
img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=13&size=700x250&sensor=false";

output.appendChild(img);
};

function error() {
output.innerHTML = "Unable to retrieve your location";
};

output.innerHTML = "<p>Locating…</p>";

navigator.geolocation.getCurrentPosition(success, error);
}

And in the above code we just requested the browser for the current location on and browser and probable(Chrome) explicitly asks for permission to share the info to the particular site.here as an callback success we have got latitude and longitude ,with those using the Google Maps API service call we just bought the map into the document(The locations may be vary since it is based on your ip.(if you're a broadband user you may get a correct location where as such as 2G and 3G service you may get the Server location
(As far i had seen).

Offline Storage API :

With this powerful API in HTML5 we could easily use the database on front end client side and making the load time and process time easier on server side.For example,When you look like application facebook,G+ posts can be saved locally in database (offline storage) and can be updated when they are connected to the network next time.this will really increase the loading time and rendering time minimum.instead of  requesting the server for the whole newsfeed contents.

IndexedDB - Offline Database 

This support storing object,create,update and delete like relational Database and have a look at it here.

LocalStorage : 

Before HTML5 there was a big story behind this,have a read.So we are in the age of good developed and matured API.
function localstore() {
if (typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage.
localStorage.setItem("name", "Shivasurya");
localStorage.setItem("company", "i-visionblog");
alert("saved the values");
} else {
alert("Your Browser Doesnt Support Storage Feature");
}
}

function retrieveStore() {
alert(localStorage.getItem("company"));
}
So from the above code you can utilize the localstorage as key pair value and retrieved using the key from the storage.this is mostly used among the web developers,However try to use the indexed DB for complex apps and solve a loading time and increasing the productivity.

Live Demo : 



function notify() {
if (!("Notification" in window)) {
alert("This browser does not support desktop notification");
} else if (Notification.permission === "granted") {
var notification = new Notification("Hi there!");
} else if (Notification.permission !== 'denied') {
Notification.requestPermission(function(permission) {
if (permission === "granted") {
var notification = new Notification("Shiva has Messaged You!");
}
});
}

}

function shareLocation() {
var output = document.getElementById("out");
if (!navigator.geolocation) {
output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
return;
}

function success(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;

output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>';

var img = new Image();
img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=13&size=700x250&sensor=false";

output.appendChild(img);
};

function error() {
output.innerHTML = "Unable to retrieve your location";
};

output.innerHTML = "<p>Locating…</p>";

navigator.geolocation.getCurrentPosition(success, error);
}

function localstore() {
if (typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage.
localStorage.setItem("name", "Shivasurya");
localStorage.setItem("company", "i-visionblog");
alert("saved the values");
} else {
// Sorry! No Web Storage support..
alert("Your Browser Doesnt Support Storage Feature");
}
}

function retrieveStore() {
alert(localStorage.getItem("company"));
}

See the Pen HTML5 API - i-visionblog by s.shivasurya (@shivasurya) on CodePen.

Final note :

And thus we have seen few rich set API which can be used at appropriate need in web apps and enhance the user experience.However always check for support of the API on load itself and then invoke calls and respect the users behavior always and forcing them for permission and locking them this will be creating bad impressions.

And there are still lot in HTML5 API such as detecting online/offline status,Canvas 2D drawing,animation,vibration API,full screen API,Audio & videos and WebRTC api for live webcam access and peer-to-peer communications.

for Hugs/bugs/errors/enhancements just comment below or drop me a mail to s.shivasurya@gmail.com or chat with me in G+/facebook/Quora and do follow me in twitter/newsletter for regular updates.Share is care.

Saturday 22 August 2015

Working with Instamojo Payment Integration For Websites And Mobile Apps

Few week back was working with a company for a premium project for Hybrid mobile app development and came across a wonderful service named as instamojo payment service/gateway for selling service/physical goods/events and tickets and even more.we used this service for adding credit amount to the Hybrid mobile apps.And the service charge is too nominal fee i hope since i got paid Sample Rs.100 and the service charge was around Rs.2.And it was awesome to talk with the developers of instamojo since it is a startup company.




Reference :    



Prerequisites :

  • A Valid website or Mobile App to Integrate.
  • Fully Activated Instamojo Account.
     You should submit your Bank statement and PAN card for verification and Phone number to prove that you're a legitimate user.
  • Developer keys private/Oauth key and Hash Secret.
  • Little patience to set up everything around :)

procedure:

We will see about initiating the Payment from our site along with the Web Hook request as well API service from Instamojo.Additional to this we will see how to implement the HMAC-SHA1 Integrity check for Safer transactions and protecting the user data over Network.

Initial Setup :

Create Instamojo Account here.And verify KYC by submitting your Bank Account Passbook photo snap and PAN Card with few more documents as instructed by instamojo.com.And get verified and it allows you to create links for new payment where you can sell your service or products over online.

After the approval process :

Create new Link for payment :

Instamojo Provides excellent features such as Events,Physical goods,service and membership plans and even more.with this they offer to index the link in search engine and they do SEO for the links you have created.

Follow the steps to create your own links: have a look at it.








So,from the Above Example snaps you can create your own service.The only thing here may be new is WebHook url,it is just a POST request made by the instamojo server to our server after every successful transactions made by the users.so that we could update our database faster and provide service to the user who have paid without any delay.

Note : The Above Screenshots are just for depiction and may Contain Fake Data and you need to create it with correct information inorder to ensure payment goes correctly.
Dont share your WebHook URL in public may be someone can try making Bruteforce attacks by making POST request and attack your DATABASE.never reveal your Private/Ouath and Hash keys.

Setup Payment in Web or App :

Here you can setup two types of Payment integration within the site either by prefiling the user information and proceed to payment or just redirecting the user to Gateway where he fills the info and process the payment.

hereby we will see the just redirection to the Payment gateway and user fills the Payment information at the Processing time.Prefilling the form contains HMAC-SHA1 verification and verifying the integrity check of the transfered information over network.We will see this in Next Post.



Select Dashboard > Corresponding link > payment Button will show you this form and can customize it.
Note : if you want to remove powered by instamojo you need to pay them some credits in their market place seems.

paste the code in our web app or mobile app.Coming to the mobile app(HTML5 hybrid apps) just you have to do the transaction in in-app browsers and writing listeners function for url change you could detect the success of the payment and return back to your app.[for further clarification drop me a Mail or Hire me to set up payment gateway in Mobile Apps].

Handling Webhooks :

Most important part of this application is handling webhooks from Instamojo server with Integrity check of source and data for updating our payment database.

<?php
$filename = "/tmp/webhook_data.txt";
foreach($_POST as $key => $value)
{
    file_put_contents($filename, "$key: $value\n", FILE_APPEND);
}
file_put_contents($filename, "----------\n", FILE_APPEND);
?>


The above code will just receive the payment data from the instamojo server when they try to post in our URL.it can be viewed when opening this file.This is really a bad approach of saving users data in flat file and we should check the REQUEST was made actually from INSTAMOJO server by checking Hash sum  calculation using our private key provided by instamojo.

A clear understanding : 



first of all instamojo with the users data they combine all data in alphabetical of the keys taking their values and adding '|' as concatenation and therefore combining all them as Strings.They calculate the hash with your private hash key.(You can get it here) and append it to the post request as sign as key and value as hash.

After reaching our server,for most step is to check for SQL injection attacks,Scan all POST variables and filter all variables.Then retrieve all key pair values from the request part.once again concatenate all the Values with '|' except the Sign part and recalculate the HMAC-SHA1 hash.

Compare both hash and if it is true,the request from instamojo server is legitimate one and you can trust the data and save it in your business Database.

I have implemented this in Node.js - HMAC-SHA1 verification - if you're interested drop me mail to get samples.

Note : Calculate the Hash as prescribed by the Instamojo( get the Complete guide here) or else it may lead to false value and ignoring valid customer data sometimes and lead to dual work and overhead.

Always try with all testcases in Development mode before moving to Production mode of app because,payment gateway can cause many troubles.Read more error codes from Instamojo website for better understanding.

Final Word :

Test all possible testcase in development mode itself and hadle all security checks in development mode and try with all testcase in webhooks,even a single loop hole can cause danger to your Customer data and business logics.

Thus instamojo made our life easy by integrating payments more simplified with pay with links as motto.my next post will be completely how to add custom data,prefilled form,HMAC-SHA1 check sum calculation for web and mobile apps.

for bugs/errors/hugs/comments/help/projects just drop me a mail to s.shivasurya@gmail.com.or chat with me in G+ / Fb chat.Share is care.do comments.