Braintree Payment Gateway Integration

Brief:

Braintree provides payment processing options for many devices. Braintree provides businesses with the ability to accept payments online or within their mobile application. Its full-stack payment platform can replace the traditional model of sourcing a payment gateway and merchant account from different providers. It provides range of Client SDKs (iOS, Android, Web/Javascript) and Server SDKs (Ruby, Python, PHP, Node.js, Java, .Net).

Need:
 

If we are implementing an eCommerce site or providing any paid service online, we need to implement an option for our customers to do payments online. One option is to contact to different banks and implement for each. Also we will have to make sure that we are compliant  with the rules & regulation and standards led by respective authorities to accept the payments.
Another option is to contact to online payment systems like Braintree and let them take care of the things. You just need to forward the users to Braintree site for payments and they return back after payment along with process.

How It Works:

First need to create a page with all the details required for payment like, Credit card number, name on card, expiry date and CVV. Also need to set some parameters in encrypted format which is required by Braintree to identify the Merchant who the funds should be transferred. When user submits the page, the data directly goes to Braintree site. All the validation and processing is done by Braintree. Whatever is the status, it returns back to our site to a specific page (result page) we specified in the parameter.
On the result page we can extract the values along with transaction status and show appropriate message to user and update the transaction status in our system.
Here is sample code.

Default.aspx

<form id='payment-form' action='<%=TransparentRedirectURL %>' method='POST'>
      <input type='hidden' name='tr_data' value='<%=TrData %>' />
      <div>
        <h2>Credit Card</h2>
        <span>Amount = $<%=Amount %></span>
        <label for='braintree_credit_card_number'>Credit Card Number</label>
        <input type='text' name='transaction[credit_card][number]' id='braintree_credit_card_number' value='4111111111111111'></input>
        <label for='braintree_credit_card_exp'>Credit Card Expiry (mm/yyyy)</label>
        <input type='text' name='transaction[credit_card][expiration_date]' id='braintree_credit_card_exp' value='12/2015'></input>
        <label for='braintree_credit_card_cvv'>CVV</label>
        <input type='text' name='transaction[credit_card][cvv]' id='braintree_credit_card_cvv' value='100'></input>
      </div>
      <input class='submit-button' type='submit' value="Submit" />
    </form>


Default.aspx.cs

protected string TrData,TransparentRedirectURL,Amount;
    protected void Page_Load(object sender, EventArgs e)
    {
        Amount = (10.00M).ToString("f2");
        TrData = Constants.Gateway.Transaction.SaleTrData(
                new TransactionRequest
                {
                    Amount = 10.00M,
                    Options = new TransactionOptionsRequest
                    {
                        SubmitForSettlement = true
                    }

                },
                "http://localhost:51641/result.aspx"
            );
        TransactionRequest a = new TransactionRequest();
      
        TransparentRedirectURL = Constants.Gateway.TransparentRedirect.Url;
    }



Constants.cs

using Braintree;
public class Constants
{
    public Constants()
    {
        //
        // TODO: Add constructor logic here
        //

    }

    public static BraintreeGateway Gateway = new BraintreeGateway
    {
        Environment = Braintree.Environment.SANDBOX,
        MerchantId = "<<Merchant id here>>",
        PublicKey = "Public key here",
        PrivateKey = "Private Key here"
    };
}


SessionUtils.cs

public class SessionUtils
{
    #region Singleton

    private const string SESSION_SINGLETON_NAME = "<<Singleton name here>>";

  
    #endregion

    public object TrData { get; set; }
    public object TransparentRedirectURL { get; set; }
    public string Message { get; set; }
}



Result.aspx.cs

Result<Transaction> result = Constants.Gateway.TransparentRedirect.ConfirmTransaction(Request.Url.Query);
        if (result.IsSuccess())
        {
            Transaction transaction = result.Target;
            //string Message = transaction.Status.ToString();
            lblStatus.Text = transaction.Status.ToString();
            //transaction.
        }
        else
        {
            List<ValidationError> errors = result.Errors.DeepAll();
            lblStatus.Text = "Transaction failed. Possible errors are<br/>";
            foreach (ValidationError er in errors)
            {
                lblStatus.Text += er.Message + "<br/>";
            }
            //string[] errors = result.Errors.DeepAll();
            //SessionUtils.Instance.Message = string.Join(", ", result.Errors.DeepAll());
        }

How to add firebase Real Time database in Android App

Steps to add firebase Real Time database in android app
  
A) Add firebase to your app

    1. Create firebase project from firebase console. If you have Google project associated to your android app then just click on import Google project option otherwise proceed with new project option in firebase console.
    2. If you are clicking on import google project option then everything will be configured  by firebase, you just need to follow steps and lastly download the config file.
    3. If you click on new project option, then new project will be created. Your application is  recognised by package name entered in project name field in create project wizard.
    4. At the end download google-services.json file and paste this file in your android project's app folder.
       
B) Add firebase sdk

    1. In your root level build.gradle file add classpath in dependencies section :
        dependencies {
            classpath 'com.google.gms:google-services:3.0.0'
        }

    2. Then add apply plugin:'com.google.gms.google-services' at the bottom of the file in your app level build.gradle file.
    3. Add compile 'com.google.firebase:firebase-core:9.2.0' in your app  level dependencies.

C) Adding firebase realtime database to android project

    1. Add compile 'com.google.firebase:firebase-database:9.2.0' to your projects app level gradle dependency
    2. Configure firebase database rule. The database configuration is important in firebase, by default data in firebase is authenticated and can not be read write by anyone . But you can make it public by clicking on public tab in database tab in project of firebase console.
    3. You can now write your database to firebase and you can easily retrieve it by calling valueEventListener() on database reference object

How to add firebase cloud messaging in Android App

Steps to add firebase cloud messaging in android app
  
A) Add firebase to your app

    1. Create firebase project from firebase console. If you have Google project associated to your android app then just click on import Google project option otherwise proceed with new project option in firebase console.
    2. If you are clicking on import Google project option then everything will be configured  by firebase, you just need to follow steps and lastly download the config file.
    3. If you click on new project option, then new project will be created. Your application is  recognized by package name entered in project name field in create project wizard.
    4.    At the end download google-services.json file and paste this file in your android project's app folder.
       
B) Add firebase sdk

    1. In your root level build.gradle file add classpath in dependencies section :
        dependencies {
            classpath 'com.google.gms:google-services:3.0.0'
        }

    2. Then add apply plugin:'com.google.gms.google-services' at the bottom of the file in your app level build.gradle file.
    3. Add compile 'com.google.firebase:firebase-core:9.2.0' in your app  level dependencies.

C) Adding fcm to android project

    1. Add  compile 'com.google.firebase:firebase-messaging:9.2.0' to your app level dependency.
    2. Create one service class extending FirebaseMessagingService class. Declare this service class in android manifest.xml file as below :

            <service android:name=”.MyFirebaseMessagingService”>
       <intent-filter>
       <action android:name=”com.google.firebase.MESSAGING_event”>
       </intent-filter>
     </service>


    3. Create another service class extending FirebaseInstanceIdService class which handles creation ,update , rotation of registration token. Declare this class as below in androidmanifest.xml file.

    <service android:name=”.MyFirebaseInstanceIdService”>      
       <intent-filter>
       <action android:name=”com.google.firebase.INSTANCE_id_event”>
       </intent-filter>
    </service>


    4. You can get token in onTokenRefresh() in your MyFirebaseInstanceIdService.
    5. Now you can send messages from your project in firebase console. For that just go to your project in firebase console which you have created earlier for fcm notification .
    6. Open the project and select notification option present in firebase console to send whatever   messages you want for your app notification by selecting package name for your application.
    7. There are two options for sending push notifications:
        i) Single device (firebase token is needed for user identification)
        ii) All applications with same package name.
    8. Right now only single line notifications can be sent to the devices.

How to add authentication in firebase


Steps to add authentication in firebase

A) Add firebase to your app.

    1. Create firebase project from firebase console. If you have Google project associated to your android app then just click on import Google project option otherwise proceed with new project option in firebase console.
    2. If you are clicking on import Google project option then everything will be configured  by firebase, you just need to follow steps and lastly download the config file.
    3. If you click on new project option, then new project will be created. Your application is  recognized by package name entered in project name field in create project wizard.
    4. At the end download google-services.json file and paste this file in your android project's app folder.

B) Add Firebase SDK.

    1. In your root level build.gradle file add classpath in dependencies section :
         dependencies {
                 classpath 'com.google.gms:google-services:3.0.0'
         }

    2. Then add apply plugin:'com.google.gms.google-services' at the bottom of the file in your app level build.gradle file.
    3. Add compile 'com.google.firebase:firebase-core:9.2.0' in your app  level dependencies.

C) Authenticate FireBase using Password-Based accounts


    1. Add the dependency for Firebase Authentication to your app-level build.gradle file:
                  compile 'com.google.firebase:firebase-auth:9.2.0'
    2. Enable Email/Password in
        1. In firebase console open auth section
        2. On sign in method tab, enable email id/ password tab and click save.
    3. For signing up new user an instance of FirebaseAuth needs to be declare in onCreate() method of activity handling sign up operation.
    4. Set up an AuthStateListener that responds to changes in the user's sign-in state:
    5. When a new user signs up using your app's sign-up form, complete any new account validation steps that your app requires, such as verifying that the new account's password was correctly typed and meets your complexity requirements.
    6.  Create a new account by passing the new user's email address and password.

D) Sign in user with Email ID and Password


    1. In onCreate() method of activity handling sign-in, get the shared instance of FirebaseAuth object.
    2. Set up AuthStateChangeListener
    3. When user signs in to your app, pass the user email address and password to signInWithEmalAdressAndPassword.
    4. If sign-in succeed ,the AuthStateListener runs the AuthStateChanged callback. In callback you can get the current user using getCurrentUser().

E) Google Sign In

    1. For integrating Google sign in to your app follow step A) and step B)
    2. Add the dependencies for firebase authentication and Google sign-in to your app-level build.gradle file:
           Compile 'com.google.firebase:firebase-auth:9.2.0'
           Compile 'com.google.android.gms:play-services-auth:9.2.0'
    3. Connect your app to firebase project
    4. Enable Google sign in in the firebase console
        1. In firebase console open auth section
        2. On sign in methods tab enable Google sign in
    5. Integrate google sign-in into app
    6. In onCreate() method of activity handling sign-in, configure google sign-in to request the data.
    7. Create googleSignInOption with default_sign_in parameters.
    8. In onCreate() mehtod of activity handling sign-in, create googleApicClient object with access to Google sign-in api.
    9. Add Google sign-in button to your app in your layout xml file. In onClick method start the sign in intent with startActivityForResult. For capturing sign in result from sign in activity. In the activity's onActivityResult method, retrieve the sign-in result with getSignInResultFromIntent. If you retrieve the sign-in result you can check weather user signs in or not. When you configure the GoogleSignInOptions object call requestIdToken(serverId).
    10. In onCreate() method of your activity an object of FirebaseAuth. Set Up an authStateListener that responds to changes in the user's sign-in state. To get credentials from firebase use ID as a token from googleSignInAccount object and exchange it with firebase, and authenticate with firebase with firebase credentials.
                  If sign in with credentials succeed then  in that callback you can get user information.

F) Facebook sign in

    1. Follow step A) and step B)
    2. Add compile 'com.google.firebase:firebase-auth:9.2.0' this app level dependency in your gradle file.
    3. On the facebook developer site, get the app id and an app secret for your app
    4. Enable facebook sign in firebase
        1. Go to firebase console open auth section
        2. Click on sign in method tab and select facebook sign in and enter your app id and secret there.
    5. Integrate facebook login and once integrated login configuration with loginbutton, you will get registercallback with success or failure of facebook login result.
    6. In activity oncreate() get the instance of firebaseauth object
    7. Set up authstatelistener.
    8. After successful sign in , in register call back method get user token and exchange it for firebase token, authenticate it with firebase credentials.
    9. If the call to signinWithCredential succeeds, the authStateListener runs the onAuthStateChanged callback. In the callback, you can use the getCurrentUser method to get the user's account data.

G) Twitter sign in

    1. Follow step  A) and step  B)
    2. Add compile 'com.google.firebase:firebase-auth:9.2.0' dependency to your app level gradle file.
    3. Register your app as a developer application on twitter and get your app's api key and api secret.
    4. Enable twitter login
        1. Go to auth section in firebase console
        2. In sign in method tab enable twitter sign button. And enter app id and secrete
    5. In activity onCreate() get the instance of firebaseaAuth object
    6. Set up authStateListener.

    7. After successful sign in, in register call back method get user token and exchange it for firebase token, authenticate it with firebase credentials.
    8. If the call to signInwithCredential succeeds, the authStateListener runs the onAuthStateChanged callback. In the callback, you can use the getCurrentUser method to get the user's account data.

Box Integration with PHP


Brief:

Now a days most of the users use the cloud storage for storing their data and documents. Box is one type of cloud platform which provide online storage system to store documents, create folders, share documents, etc. on cloud instead of storing on PC, Hard Disk or any other devices. Box provides an third party API which can be used to integrate box in any of the website or mobile devices. Using Box you can easily access your documents from any place at anytime. Box provide libraries or SDK for most of the technology to integrate with it. Box is not provide all feature in it free version, so you need to purchase its license version to access all features.

Need:

Box is generally used to provide a platform to users to store a project related documents and create workspace for the project online at any website. Mostly all organizations used the manual system to create document and shared it with their employees via email or any other way. So to remove this manual system Box provide a very good alternative approach to create and share documents online in your project area only.

How It Works:

To integrate Box in PHP you need to use Content API for box. And you can use Content API  by creating your project box app on the developer Box portal. So firstly create Box app on the developer portal by using following steps:

  • Login with your Box Credentials on Developer box portal and click on “Create a Box Application”  link.
  • Enter your application name and click on “Create Application” button.
  • It will create a new app and redirect you to its configuration settings page and asked you for more details about your project.
  • Enter general information and keep save client_id and client_secret at your end.
  • Select the User Type as “App Users” and select the scopes which you would like to give to the app users.
  • Now generate an RSA key pair to retrieve the access token. You can create an RSA key pair by using following command:
           Generate Private Key

        openssl genrsa -aes256 -out private_key.pem 2048
         
            Generate Public Key

        openssl rsa -pubout -in private_key.pem -out public_key.pem

  • Now Add your public key under “Public Key Management” and verify it. Your public key and key ID will display in the settings.
  • Take a note of your client_id and client_secret and save the application details.

Now you require an app user token to access the Box Conent API. To create an app user token you will require JWT (Json Webs Token)  token. JWT assertion composed with three sections:
  1. Header – It specifies the algorithm for JWT signature.
  2. Claims – It contain required information to validate correct auth token.
  3. Signature – It is used to identify the request call through our website only and it is verified through public key.
You can use the below PHP libraries to generate the JWT token for your project:

        Firebase PHP-JWT : https://github.com/firebase/php-jwt
 

After generating the JWT token you need to create an app user to call the Box APIs. To create an App user you will require an enterprise access token. To request an enterprise token you need to use the JWT assertion grant and specify the “enterprise” as the box_sub_type  and enterprise_id as sub. You can find the enterprise id from your box account Admin Console enterprise settings.

Once you done with the generation of the enterprise access token you can use that access token to create an App User by following request:

    curl https://api.box.com/2.0/users \
    -H "Authorization: Bearer ACCESS_TOKEN" \
    -d '{"name": "James Anderson", "is_platform_access_only": true}' \
    -X POST


After the app user creation you can use the App User ID to create and app user access token to perform an content API call like create folder,upload file, create shared link, invite collaborator, etc. To request the App user token, you need to use the JWT assertion grant and specify the “user” as the box_sub_type and user_id as sub. So now you are all set to access any API of Box  with the app user access token.

There are lots of APIs available for accessing the box. Few important APIs are listed below:
  • Create Folder – To create a folder on box
  • Upload File – To upload a file on any particular folder or at root.
  • Invite Collaborations – Invite a people to particular folder to share the documents other stuffs.
  • Create Shared Link – To create shared link for any file or folder.
  • Preview File – To open the file in preview mode to view the content of the file
  • Upload new version of file – To upload a new version of any file (maintain version history )

Submit Hive And SQOOP jobs


Brief :

This procedure allows you to submit Hive jobs to Azure HDInsight Cluster and Run SQOOP queries to export Hive table data to SQL database.

Need:

Azure provides the Hive editor to submit Hive jobs on HDInsight Cluster by user interaction. If there are large number of jobs which needs to submit daily, then we can use the automated procedure which is explained below.

How It Works:
 
    Requirements-
  •  SQL Database
  • HDInsight Cluster (Running Status)
  • Install NuGet Package given below,
  • Install-Package Microsoft.Azure.Management.HDInsight.Job

To Submit Hive and SQOOP jobs use below class,


public class HiveQueryManager
    {
        private string SqlDatabaseServerName { get; set; }

        private string SqlDatabaseLogin { get; set; }

        private string SqlDatabaseLoginPassword { get; set; }

        private string SqlDatabaseDatabaseName { get; set; }

        private HDInsightJobManagementClient _hdiJobManagementClient;

        public Dictionary<string, string> defines;

        public List<string> args;

        public HiveQueryManager(string existingClusterUsername, string existingClusterPassword, string existingClusterUri)

        {

            var clusterCredentials = new BasicAuthenticationCloudCredentials { Username = existingClusterUsername, Password = existingClusterPassword };

            _hdiJobManagementClient = new HDInsightJobManagementClient(existingClusterUri, clusterCredentials);

        }

        public string SubmitHiveJob(string query)

        {

            try

            {

                var parameters = new HiveJobSubmissionParameters

                {

                    Query = query,

                    Defines = defines,

                    Arguments = args

                };

                System.Console.WriteLine("Submitting the Hive job to the cluster...");

                var jobResponse = _hdiJobManagementClient.JobManagement.SubmitHiveJob(parameters);

                var jobId = jobResponse.JobSubmissionJsonResponse.Id;

                System.Console.WriteLine("Response status code is " + jobResponse.StatusCode);

                System.Console.WriteLine("JobId is " + jobId);

                System.Console.WriteLine("Waiting for the job completion ...");

 
                // Wait for job completion

                var jobDetail = _hdiJobManagementClient.JobManagement.GetJob(jobId).JobDetail;

                while (!jobDetail.Status.JobComplete)

                {

                    Thread.Sleep(1000);

                    jobDetail = _hdiJobManagementClient.JobManagement.GetJob(jobId).JobDetail;

                }

                System.Console.WriteLine("Job Exit Code " + jobDetail.ExitValue.ToString());

                return "Job Exit Code " + jobDetail.ExitValue.ToString();

            }
            catch (Exception ex)

            {
                Console.WriteLine(ex.Message);

                return ex.Message;
            }
        }


        public void SetSQLDatabase(string sqlDatabaseServerName, string sqlDatabaseLogin, string sqlDatabaseLoginPassword, string sqlDatabaseDatabaseName)
        {
            SqlDatabaseServerName = sqlDatabaseServerName;

            SqlDatabaseLogin = sqlDatabaseLogin;

            SqlDatabaseLoginPassword = sqlDatabaseLoginPassword;

            SqlDatabaseDatabaseName = sqlDatabaseDatabaseName;
        }

        public string ExportTableToSQLDatabase(string hdfsPath, string tableName, string saperator)

        {

            try

            {

                var exportDir = hdfsPath; // "/hive/warehouse/tablename";

                // Connection string for using Azure SQL Database.

                // Comment if using SQL Server

                var connectionString = "jdbc:sqlserver://" + SqlDatabaseServerName + ".database.windows.net;user=" + SqlDatabaseLogin + "@" + SqlDatabaseServerName + ";password=" + SqlDatabaseLoginPassword + ";database=" + SqlDatabaseDatabaseName;

                // Connection string for using SQL Server.

                // Uncomment if using SQL Server

                //var connectionString = "jdbc:sqlserver://" + sqlDatabaseServerName + ";user=" + sqlDatabaseLogin + ";password=" + sqlDatabaseLoginPassword + ";database=" + sqlDatabaseDatabaseName;

                var parameters = new SqoopJobSubmissionParameters

                {
                    //Files = new List<string> { "/user/oozie/share/lib/sqoop/sqljdbc41.jar" }, // This line is required for Linux-based cluster.

                    Command = "export --connect " + connectionString + " --table " + tableName + " --export-dir " + exportDir + " --input-null-string \\\\N --input-null-non-string \\\\N --fields-terminated-by " + saperator + " -m 1"

                };

                var response = _hdiJobManagementClient.JobManagement.SubmitSqoopJob(parameters);

                var jobId = response.JobSubmissionJsonResponse.Id;

                System.Console.WriteLine("Response status code is " + response.StatusCode);

                System.Console.WriteLine("JobId is " + jobId);

                System.Console.WriteLine("Waiting for the job completion ...");

 
                // Wait for job completion

                var jobDetail = _hdiJobManagementClient.JobManagement.GetJob(jobId).JobDetail;

                while (!jobDetail.Status.JobComplete)

                {

                    Thread.Sleep(1000);

                    jobDetail = _hdiJobManagementClient.JobManagement.GetJob(jobId).JobDetail;

                }

                System.Console.WriteLine("Job Exit Code " + jobDetail.ExitValue.ToString());

                return "Job Submitted Successfully. The JobId is " + response.JobSubmissionJsonResponse.Id;

            }

            catch (Exception ex)

            {

                return ex.Message;

            }

        }

    }

  Below are the parameter details,
  • existingClusterUsername HDInsight Cluster User Name where we want to run the jobs.
  • existingClusterPassword HDInsight Cluster Password.
  • existingClusterUri HDInsight Cluster Uri.
  • existingClusterUri = ExistingClusterName + ".azurehdinsight.net";
  • hdfsPath – Path of hive table on HDFS.
  • Saperator – Saperator used while creating Hive Table.
  • tableName – Name of the table which needs to be exported (Create table in SQL Database with same structure and name).
Use HiveQueryManager class object to Submit Hive and SQOOP jobs. (Using SubmitHiveJob and ExportTableToSQLDatabase Methods).

Boston Byte Grabs a Spot in Clutch’s List of Top Software Developers in Massachusetts

Boston Byte is a collective of highly-skilled and highly-professional developers dedicated to solving your technological ...