Showing posts with label ionic. Show all posts
Showing posts with label ionic. Show all posts

Tuesday, 19 September 2017

SIGNUP Form With Validation AngularJs

No comments
HTML

<form class="register-form" name="formRegister">
                    <p class="form_logo">
                        <img title="" alt="" src="img/logo.png" class="">
                    </p>
                    <label ng-class="{ 'has-errors' : formRegister.userEmail.$invalid && !formRegister.userEmail.$pristine, 'no-errors' : formRegister.userEmail.$valid}">
                        <input focus id="registerEmails" type="email" placeholder="Email" ng-model="userEmail">
                    </label>              
                    <label ng-class="{ 'has-errors' : formRegister.userPassword.$invalid && !formRegister.userPassword.$pristine, 'no-errors' : formRegister.userPassword.$valid}">
                        <input focus type="password" placeholder="Password" id="userPassword" name="userPassword" ng-model="userPassword" required />
                    </label>
                    <label ng-class="{ 'has-errors' : formRegister.confirmPassword.$invalid && !formRegister.confirmPassword.$pristine, 'no-errors' : formRegister.confirmPassword.$valid}">
                        <input focus type="password" id="confirmPassword" name="confirmPassword" placeholder="Retype Password" ng-model="confirmPassword" required compare-to="userPassword">
                    </label>
                    <div class="msg-block ng-invalid" ng-show="formRegister.$error">
                        <span class="msg-error ng-invalid" ng-show="formRegister.confirmPassword.$error.pwmatch">
                            Password doesn't match.
                        </span>
                    </div>
                    <button ng-click="doRegister()" class="button button-block button-balanced" ng-disabled="formRegister.$invalid" style="padding:0 !important">
                        SIGN UP
                    </button>
                    <p class="message">Already registered? <a ng-href="#/app/login">Sign In</a></p>
                 
                </form>


Directive


//password compare
app.directive('compareTo', [function () {
    return {
        require: "ngModel",
        scope: {
            otherModelValue: "=compareTo"
        },
        link: function (scope, element, attributes, ngModel) {
            var firstPassword = '#' + attributes.compareTo;
            element.on('keyup', function () {
                scope.$apply(function () {
                    var v = element.val() === $(firstPassword).val();
                    ngModel.$setValidity('pwmatch', v);
                });
            });
        }
    };

}]);


//move to next input when enter
app.directive('focus', function () {
    return {
        restrict: 'A',
        link: function ($scope, elem, attrs) {
            elem.bind('keydown', function (e) {
                var code = e.keyCode || e.which;
                if (code === 13) {
                    e.preventDefault();
                    //          elem.next().focus();

                    if (elem.attr('id') == "registerEmail") {
                        $(':input:eq(' + ($(':input').index(this) + 1) + ')').on('focus', function () {
                            $(this).attr('type', 'date');
                        });
                        $(':input:eq(' + ($(':input').index(this) + 1) + ')').focus().click();
                    }
                    else {
                        $(':input:eq(' + ($(':input').index(this) + 1) + ')').focus();
                    }
                }
            });
        }
    }
});
read more

Friday, 21 July 2017

Textbox with autocomplete dropdown Ionic

No comments
Directive

app.directive('ionSelect', function ($rootScope) {
    'use strict';
    return {
        restrict: 'EAC',
        scope: {
            label: '@',
            labelField: '@',
            provider: '=',
            ngModel: '=?',
            ngValue: '=?',
            labelId: '@',
            placeholderValue: '@',
            globalClass: '@',
            placeholderClass: '@',
        },
        require: '?ngModel',
        transclude: false,
        replace: false,
        template: '<div class="item item-input-inset noBorderTop noPadding divSlectText">'
                + '<label class="item-input-wrapper">'
                + '<input id="filtro" class="{{placeholderClass}}" type="search" intype="placeholder" language-seletion key="{{placeholderValue}}"   ng-model="ngModel" ng-value="ngValue" /></label>'
                + '<button class="button button-small button-clear inputOpen"><i class="icon ion-chevron-down"></i>'
                + '</button></div><div class="optionList padding-left padding-right hideSelectText">'
                + '<ion-scroll class="selectScroll"><ul class="list">'
                + '<li class="item  {{globalClass}}" ng-click="selecionar($event,item,labelField,labelId)" ng-repeat="item in provider | filter:ngModel">{{item[labelField]}}</li></ul>'
                + '</ion-scroll></div>',
        link: function (scope, element, attrs, ngModel) {
            scope.ngValue = scope.ngValue !== undefined ? scope.ngValue : 'item';
            scope.selecionar = function ($event,item, name, id) {
               
                ngModel.$setViewValue(item[name]);              
                if (name == 'SpecialityName') {
                    $rootScope.medicalProviderData.SpecialityId = { SpecialityId: item[id] };
                }
                scope.showHide = false;                $event.target.parentElement.parentElement.parentElement.classList.remove("showSelectText");
                $event.target.parentElement.parentElement.parentElement.classList.add("hideSelectText");
            };
            element.bind('click', function () {
                element.find('input').focus();
            });
            element.find('button').bind('click', function () {
                var $this = $(this);
                $('.divSlectText').each(function () {
                    if ($this.parent().parent().find('.optionList').html() != $(this).parent().find('.optionList').html()) {
                        if ($(this).find('button').hasClass('inputOpen')) {
                            $(this).parent().find('.optionList').removeClass('showSelectText');
                            $(this).parent().find('.optionList').addClass('hideSelectText');
                        }
                    }
                });
                if ($this.parent().parent().find('.optionList').hasClass('hideSelectText')) {
                    $this.parent().parent().find('.optionList').removeClass('hideSelectText');
                    $this.parent().parent().find('.optionList').addClass('showSelectText');
                }
                else {
                    $this.parent().parent().find('.optionList').addClass('hideSelectText');
                }
            });
            element.find('input').bind('keydown', function () {              
                var $this = $(this);              
                $this.parent().parent().parent().find('.optionList').addClass('showSelectText')
                $this.parent().parent().parent().find('.optionList').removeClass('hideSelectText')
            });
        },
    };

});

CSS


.showSelectText {
    display:block;
}
.hideSelectText {
    display:none;

}

HTML

  <div>
       <ion-select label="SpecialityName" global-class="{{globalClass}} {{textAlign}}" placeholder-class="{{globalClass}} {{textAlign}}" placeholder-value="Speciality" label-field="SpecialityName" itemname="SpecialityName" label-id="SpecialityId" provider="SpecialityList" ng-model="speciality" />

                    </div>
read more

Tuesday, 30 May 2017

Convert Language From English To Arabic From Directive

No comments
Directive

app.directive('languageSeletion', function (languageData) {
    return {
        restrict: 'EA',
        replace: true,
        scope: {
            key: "@"
        },
        link: function (scope, element, attr) {
           
            var value = languageData.convertData(scope.key);
            debugger
            element.html(value);          
        }
    }
});


Factory


app.factory('languageData', function (xmlTojson,$rootScope) {
    function xmlToString(xmlData) {
        return  (new XMLSerializer()).serializeToString(xmlData);        
    }
    return {
        convertData: function (key) {            
            var result;
            $.ajax({
                url: 'data/arabic.xml',
                dataType: 'xml',
                contentType:'application/xml',
                async: false,
                success: function (data) {                   
                    var jsonData = JSON.parse(xmlTojson.convertXMLToJSON(xmlToString(data))).Resources.key;                    
                    $.each(jsonData, function (index, value) {
                        if (value._value == key) {
                            if ($rootScope.language == 'EN') {
                                result = value.EN;
                            }
                            else {
                                result = value.AE;
                            }
                            return false;
                        }
                    });
                    
                }
            });
            return result;
        }
    }
});

app.factory('xmlTojson', function () {
    var x2js = new X2JS();
    return {
        convertXMLToJSON: function (data) {
            return JSON.stringify(x2js.xml_str2json(data));
        }
    }

});

HTML

<script src="scripts/xml2json.js"></script>
<span class="input-label textAlignCenter colorTheme" language-seletion key="About"></span>
read more

Wednesday, 12 April 2017

Send Push Notification With Cordova And Webapi

No comments
Cordova Plugin

https://github.com/phonegap/phonegap-plugin-push

Push Plugin


var push = PushNotification.init({
           android: {
               senderID: "628523812525"
           },
           browser: {
               pushServiceURL: 'your url'
           },
           ios: {
               alert: "true",
               badge: "true",
               sound: "true"
           },
           windows: {}
       });
       PushNotification.hasPermission(function (permissionResult) {
          if (permissionResult.isEnabled) {           
            push.on('registration'function (data) {
              alert(data.registrationId,data.registrationId);          
            });
 
            push.on('notification'function (data) {
              alert(JSON.stringify(data));
            });
 
            push.on('error'function (e) {      
              alert("e.message: " + e.message);
            });
          }
        });
      

WebAPI

//RegisterId you got from Android Developer.
string deviceId = "APA91bExfJOpM0vmKW8q200RSPs5iSPugD1mKf4PSYaFaz5TyZP2QYwmYUCDVHdNV7";
 
string message = "Demo Notification";
string tickerText = "Patient Registration";
string contentTitle = "Titlesss";
string postData =
"{ \"registration_ids\": [ \"" + deviceId + "\" ], " +
  "\"data\": {\"tickerText\":\"" + tickerText + "\", " +
             "\"contentTitle\":\"" + contentTitle + "\", " +
             "\"message\": \"" + message + "\"}}";
 
//  
//  MESSAGE CONTENT  
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
 
//  
//  CREATE REQUEST  
HttpWebRequest Requests = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
Requests.Method = "POST";
//  Request.KeepAlive = false;  
 
Requests.ContentType = "application/json";
Requests.Headers.Add(string.Format("Authorization: key={0}""AIzaSyBKz7u6jeat1p09cO1"));
Requests.ContentLength = byteArray.Length;
 
Stream dataStream = Requests.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
 
//  
//  SEND MESSAGE  
 
WebResponse Response = Requests.GetResponse();
 
HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;
if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
{
    var text = "Unauthorized - need new token";
}
else if (!ResponseCode.Equals(HttpStatusCode.OK))
{
    var text = "Response from web service isn't OK";
}
 
StreamReader Reader = new StreamReader(Response.GetResponseStream());
string responseLine = Reader.ReadToEnd();
Reader.Close();
 
 
read more

Wednesday, 22 March 2017

Accordian In Ionic

No comments
Controller


//Accordian Start
    $scope.accordian = [
     { title: "CallList", id: 1 },
     { title: "Schedule", id: 2 },
     { title: "CallHistory", id: 3 },
    ];
 
    $scope.toggleAccordian = function (accordian) {
        if ($scope.isAccordianShown(accordian)) {
            $scope.shownaccordian = null;
        } else {
            $scope.shownaccordian = accordian;
        }
    };
    $scope.isAccordianShown = function (accordian) {
        return $scope.shownaccordian === accordian;
    };
    $scope.toggleAccordian('1');


HTML

<div ng-repeat="(key, value) in accordian| groupBy: 'id'">
                <ion-item class="item-stable" ng-click="toggleAccordian(key)"
                          ng-class="{active: isAccordianShown(key)}">
                    <i class="icon" ng-class="isAccordianShown(key) ? 'ion-minus' : 'ion-plus'"></i>
                    &nbsp;
                    <span style="margin:5px;color#7fa42d;font-weightbold;">{{key=='1'?'Call List':key=='2'?'Next 7 Days Schedule':key=='3'?'Call History':''}}</span>
                </ion-item> 
                <ion-item class="" ng-repeat="items in value" ng-show="isAccordianShown(key)">                   
                    <div class="col-lg-12" ng-repeat="x in xx" ng-show="key=='1'">                      
                    </div>                   
                    <div class="list" ng-repeat="z in zz" ng-show="key=='2'">                       
                    </div>
                    <div class="col list" ng-show="key=='3'">                       
                    </div>                                      
                </ion-item>
            </div>
read more

Friday, 10 March 2017

Required Environment Variables To Setup Cordova Project

No comments
User Variable
------------------

ANDROID_HOME
C:\Program Files (x86)\Android\android-sdk

JAVA_HOME
C:\Program Files\Java\jdk1.8.0_111

PATH:-
C:\Users\vikas\AppData\Roaming\npm\node_modules\cordova\bin
C:\Program Files\Java\jdk1.8.0_111\bin
C:\Users\vikas\AppData\Roaming\npm



system variables
---------------------------
JAVA_HOME
C:\Program Files\Java\jdk1.8.0_111
read more

Thursday, 2 March 2017

make Checkbox to work as radiobutton

No comments
JS


$scope.doctorStatus = [
     { title: "Available", checked: true },
     { title: "Busy", checked: false },
     { title: "NA", checked: false },
    ];
 
    $scope.UpdateSelection = function (position, itens, title) {
        angular.forEach(itens, function (subscription, index) {
            if (position != index)
                subscription.checked = false;
            else
                subscription.checked = true;
        }
        );
    }

HTML


<div class="card" ng-show="!callList.length">           
            <ion-item class="item-checkbox" ng-repeat="item in doctorStatus" style="padding:0 !important">
                <ion-checkbox ng-model="item.checked" ng-click="UpdateSelection($index, doctorStatus, item.title);">{{item.title}}</ion-checkbox>
            </ion-item>
 
        </div>
read more

Wednesday, 1 March 2017

Show Default Load Image Till Image Is Fully Loaded From Server

No comments
src is default image

<img load-image="{{item.ImageURL}}" src="img/rolling.gif" />

Directive

app.directive('loadImage'function () {
    return {
        restrict: 'A',
        scope: { loadImage: '@' },
        link: function (scope, element, attrs) {
            element.one('load'function () {
                element.attr('src', scope.loadImage);
            });
        }
    };
}); 
read more

Focus On Next Input On Enter

No comments
Directive


//move to next input when enter
app.directive('focus'function () {
    return {
        restrict: 'A',
        link: function ($scope, elem, attrs) {
            elem.bind('keydown'function (e) {
                var code = e.keyCode || e.which;
                if (code === 13) {
                    e.preventDefault();
                    //          elem.next().focus();
 
                    if (elem.attr('id') == "registerEmail") {
                        $(':input:eq(' + ($(':input').index(this) + 1) + ')').on('focus'function () {
                            $(this).attr('type''date');
                        });
                        $(':input:eq(' + ($(':input').index(this) + 1) + ')').focus().click();
                    }
                    else {
                        $(':input:eq(' + ($(':input').index(this) + 1) + ')').focus();
                    }
                }
            });
        }
    }
});

HTML

<label>
  <input id="email" focus type="email" ng-model="userEmail" required>
/label>
<label>
  <input id="password" focus type="password" ng-model="userPassword" required>
</label> 
read more

Validation In ModalPopUp

No comments

HTML
<script id="templates/changePassword.html" type="text/ng-template">
    <ion-modal-view class="grey_bg">
        <ion-nav-bar class="bar-balanced">
            <ion-nav-title>
                Change Password
            </ion-nav-title>
            <ion-nav-buttons side="right">
                <button class="button button-icon button-clear ion-close-round"
 ng-click="ChangePassword()"></button>
            </ion-nav-buttons>
        </ion-nav-bar>
        <ion-content class="has-header toTransofrm" padding="10">
            <div class="list">
                <form class="register-form" name="formRegister">
                    <label class="item item-input" 
ng-class="{ 'has-errors' : formRegister.oldPassword.$invalid && 
!formRegister.oldPassword.$pristine, 'no-errors' : formRegister.oldPassword.$valid}">
                        <input focus type="password" placeholder="Current Password" 
id="oldPassword" name="oldPassword" ng-model="oldPassword" required />
                    </label>
                    <label class="item item-input" 
ng-class="{ 'has-errors' : formRegister.userPassword.$invalid 
&& !formRegister.userPassword.$pristine, 'no-errors' : formRegister.userPassword.$valid}">
                        <input focus type="password" placeholder="New Password" 
id="userPassword" name="userPassword" ng-model="userPassword" required />
                    </label>
                    <label class="item item-input" 
ng-class="{ 'has-errors' : formRegister.confirmPassword.$invalid && 
!formRegister.confirmPassword.$pristine, 'no-errors' : formRegister.confirmPassword.$valid}">
                        <input focus type="password" id="confirmPassword" 
name="confirmPassword" placeholder="Confirm New Password" 
ng-model="confirmPassword" required compare-to="userPassword">
                    </label>
                    <div class="msg-block ng-invalid" ng-show="formRegister.$error">
                        <span class="msg-error ng-invalid" 
ng-show="formRegister.confirmPassword.$error.pwmatch">
                            Password doesn't match.
                        </span>
                    </div>
                    <div class="button-bar bar-balanced">
                        <a class="button" ng-click="openPasswordModal()" 
ng-disabled="formRegister.$invalid" style="font-size:25px">Change Password</a>
                    </div>
                </form>
 
            </div>
 
        </ion-content>
    </ion-modal-view>
</script>

JS

//open popup model
   $scope.openPasswordModal = function (animation) {
       $ionicModal.fromTemplateUrl('templates/changePassword.html', {
           scope: $scope,
           animation: animation
       }).then(function (modal) {
           $scope.passwordModal = modal;
           $scope.passwordModal.show();
       });
   };
   //close popup model
   $scope.closePasswordModal = function () {
       $scope.passwordModal.hide();
   };

Directive

//password compare
app.directive('compareTo', [function () {
    return {
        require: "ngModel",
        scope: {
            otherModelValue: "=compareTo"
        },
        link: function (scope, element, attributes, ngModel) {
            var firstPassword = '#' + attributes.compareTo;
            element.on('keyup'function () {
                scope.$apply(function () {
                    var v = element.val() === $(firstPassword).val();
                    ngModel.$setValidity('pwmatch', v);
                });
            });
        }
    };
}]);
read more

Wednesday, 25 January 2017

Paypal integration in ionic without plugin

1 comment
WebApi Code
-------------------------------------------------------------------------------------------------------------------------

PayPalMethods.CS

public static class PayPalMethods
{

    //private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
 
    /*
*   Purpose: Gets the access token from PayPal
*   Inputs:     n/a
*   Returns:    access token
*
*/
    public static string getAccessToken()
    {
        string serviceUrl = getServiceUrl("/v1/oauth2/token");

        string clientId = getClientId();
        string clientSecret = getClientSecret();

        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);

        httpWebRequest.Accept = "application/json";
        httpWebRequest.Headers["Authorization"] = "Basic " + System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(clientId + ":" + clientSecret));
        httpWebRequest.Headers["AcceptLanguage"] = "en_US";
        httpWebRequest.Headers["PayPal-Partner-Attribution-Id"] = System.Configuration.ConfigurationManager.AppSettings.Get("SBN_CODE");
        httpWebRequest.Method = "POST";

        string post = "grant_type=client_credentials";

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            streamWriter.Write(post);
            streamWriter.Flush();
            streamWriter.Close();
        }

        var result = "";
        string accessToken = "";

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            result = streamReader.ReadToEnd();
        }

        string jsonResponse = JValue.Parse(result).ToString(Formatting.Indented);

        //log4net.Config.XmlConfigurator.Configure();
        //log.Info(
        //    "Service URL: " + serviceUrl + Environment.NewLine +
        //    "Request: " + post + Environment.NewLine +
        //    "Response: " + Environment.NewLine + jsonResponse
        //);

        JObject o = JObject.Parse(result);
        accessToken = (string)o["access_token"];

        return accessToken;
    }


    /*
*   Purpose: Gets the PayPal approval URL to redirect the user to.
    *
*   Inputs:     access_token (The access token received from PayPal)
*   Returns:    approval URL
*/
    public static string getApprovalUrl(string accessToken, string jsonRequest)
    {
        string serviceUrl = getServiceUrl("/v1/payments/payment");

        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
     
        httpWebRequest.Accept = "application/json";
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Headers["Authorization"] = "Bearer " + accessToken;
        httpWebRequest.Headers["PayPal-Partner-Attribution-Id"] = System.Configuration.ConfigurationManager.AppSettings.Get("SBN_CODE");
        httpWebRequest.Method = "POST";

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            streamWriter.Write(jsonRequest);
            streamWriter.Flush();
            streamWriter.Close();
        }

        var result = "";
        var approvalUrl = "";

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            result = streamReader.ReadToEnd();
            JObject o = JObject.Parse(result);

            // parse out the approval_url link
            foreach (var link in o["links"])
            {
                if ((string)link["rel"] == "approval_url")
                {
                    approvalUrl = (string)link["href"];
                }
            }
        }

        string jsonResponse = JValue.Parse(result).ToString(Formatting.Indented);

        //log4net.Config.XmlConfigurator.Configure();
        //log.Info(
        //    "Service URL: " + serviceUrl + Environment.NewLine +
        //    "Request: " + jsonRequest + Environment.NewLine +
        //    "Response: " + Environment.NewLine + jsonResponse
        //);

        return approvalUrl;
    }


    /*
    *   Purpose: Executes the previously created payment for a given paymentID for a specific user's payer id.
    *
    *   Inputs:     paymentID (The id of the previously created PayPal payment)
    *               payerID (The id of the user received from PayPal)
    *               transactionAmountArray (amount array if updating the payment amount)
    *   Returns:    Tuple (pair) containing
    *                  - http statuscode (int)
    *                  - json response object of the executed payment (JObject)
    */                
    public static Tuple<int, JObject> doPayment(string accessToken, string paymentID, string payerID, string jsonUpdate = null)
    {
        string serviceUrl = getServiceUrl("/v1/payments/payment/" + paymentID + "/execute");

        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);

        httpWebRequest.Accept = "application/json";
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Headers["Authorization"] = "Bearer " + accessToken;
        httpWebRequest.Headers["PayPal-Partner-Attribution-Id"] = System.Configuration.ConfigurationManager.AppSettings.Get("SBN_CODE");
        httpWebRequest.Method = "POST";

        string jsonRequest = "";

        JObject requestObject = null;
     
        if (string.IsNullOrEmpty(jsonUpdate) == true)
        {
            requestObject = new JObject(
                new JProperty(
                    "payer_id", payerID
                )
            );

            jsonRequest = requestObject.ToString();
        }
        // update shipping: include "transactions" object that only contains "amount" object
        else
        {
            JObject updateObject = JObject.Parse(jsonUpdate);

            requestObject = new JObject(
                new JProperty(
                    "payer_id", payerID
                ),
                new JProperty(
                    "transactions", new JArray(
                        new JObject(
                            new JProperty(
                                "amount", updateObject
                            )
                        )
                    )
                )
            );

            jsonRequest = requestObject.ToString();
        }

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            streamWriter.Write(jsonRequest);
            streamWriter.Flush();
            streamWriter.Close();
        }

        string result = "";
        int httpStatusCode = 0;

        try
        {
            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            httpStatusCode = (int)httpResponse.StatusCode;

            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                result = streamReader.ReadToEnd();
            }
        }
        catch (WebException ex)
        {
            if (ex.Response is HttpWebResponse)
            {
                HttpStatusCode statusCode = ((HttpWebResponse)ex.Response).StatusCode;
                httpStatusCode = (int)statusCode;

                //log.Info("Server returned HTTP " + (int)statusCode + " (" + statusCode.ToString() + ")");

                using (WebResponse wResponse = (HttpWebResponse)ex.Response)
                {
                    using (Stream data = wResponse.GetResponseStream())
                    {
                        result = new StreamReader(data).ReadToEnd();
                    }
                }
            }
        }
        catch (Exception ex)
        {
            //log.Info(
            //    "Error: " + ex
            //);
        }

        string jsonResponse = JValue.Parse(result).ToString(Formatting.Indented);

        //log4net.Config.XmlConfigurator.Configure();
        //log.Info(
        //    "Service URL: " + serviceUrl + Environment.NewLine +
        //    "Request: " + jsonRequest + Environment.NewLine +
        //    "Response: " + Environment.NewLine + jsonResponse
        //);

        JObject o = JObject.Parse(result);

        Tuple<int, JObject> resultPair = new Tuple<int, JObject>(httpStatusCode, o);
        return resultPair;
    }


    /*
    *   Purpose: Look up a payment resource, to get details about payments that have not yet been completed
    *
    *   Inputs:     paymentID (The id of the created payment)
    *   Returns:    json response object
    */
    public static JObject lookUpPaymentDetails(string accessToken, string paymentID)
    {
        string serviceUrl = getServiceUrl("/v1/payments/payment/" + paymentID);

        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);

        httpWebRequest.Accept = "application/json";
        httpWebRequest.Headers["Authorization"] = "Bearer " + accessToken;
        httpWebRequest.Headers["PayPal-Partner-Attribution-Id"] = System.Configuration.ConfigurationManager.AppSettings.Get("SBN_CODE");
        httpWebRequest.Method = "GET";

        //Get Response
        HttpWebResponse myHttpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();

        var result = "";

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            result = streamReader.ReadToEnd();
        }

        string jsonResponse = JValue.Parse(result).ToString(Formatting.Indented);

        //log4net.Config.XmlConfigurator.Configure();
        //log.Info(
        //    "Service URL: " + serviceUrl + Environment.NewLine +
        //    "Response: " + Environment.NewLine + jsonResponse
        //);

        JObject o = JObject.Parse(result);

        return o;
    }


    /*
    *   Purpose: Create a csrf token used for better security
    *   Inputs:     n/a
    *   Returns:    csrf token (for use in forms and session)
    *
    */
    public static string getCsrfToken()
    {
        Random rnd = new Random();
        Byte[] b = new Byte[32];
        rnd.NextBytes(b);
        string csrfToken = BitConverter.ToString(b);
        csrfToken = csrfToken.Replace("-", "");
        return csrfToken;
    }

    public static string getServiceUrl(string pathService)
    {
        bool sandboxFlag = Boolean.Parse(ConfigurationManager.AppSettings.Get("SANDBOX_FLAG"));

        string serviceUrl = sandboxFlag ?
            System.Configuration.ConfigurationManager.AppSettings.Get("SANDBOX_ENDPOINT") + pathService :
            System.Configuration.ConfigurationManager.AppSettings.Get("LIVE_ENDPOINT") + pathService;

        return  serviceUrl;
    }
 
    public static string getClientId()
    {
        bool sandboxFlag = Boolean.Parse(System.Configuration.ConfigurationManager.AppSettings.Get("SANDBOX_FLAG"));

        string clientId = sandboxFlag ?
                System.Configuration.ConfigurationManager.AppSettings.Get("SANDBOX_CLIENT_ID") :
                System.Configuration.ConfigurationManager.AppSettings.Get("LIVE_CLIENT_ID");

        return  clientId;
    }

    public static string getClientSecret()
    {
        bool sandboxFlag = Boolean.Parse(System.Configuration.ConfigurationManager.AppSettings.Get("SANDBOX_FLAG"));

        string clientSecret = sandboxFlag ?
                System.Configuration.ConfigurationManager.AppSettings.Get("SANDBOX_CLIENT_SECRET") :
                System.Configuration.ConfigurationManager.AppSettings.Get("LIVE_CLIENT_SECRET");

        return  clientSecret;
    }


}

-------------------------------------------------------------------------------------------------------------------------

PayPalObjects.CS



    public class PayPalApi
    {
        public string name{ get; set; }
        public string message { get; set; }
        public string link{ get; set; }

        public string addressLines { get; set; }
        public string paymentID { get; set; }
        public string paymentState { get; set; }
        public string finalAmount { get; set; }
        public string currency { get; set; }
        public string transactionID { get; set; }
        public string payerFirstName { get; set; }
        public string payerLastName { get; set; }
        public string recipientName { get; set; }
        public string addressLine1 { get; set; }
        public string addressLine2 { get; set; }
        public string city { get; set; }
        public string state { get; set; }
        public string postalCode { get; set; }
        public string countryCode { get; set; }
    }

   public class PayPalObjects
    {

        public class Details
        {
            public string shipping { get; set; }
            public string subtotal { get; set; }
            public string tax { get; set; }
            public string insurance { get; set; }
            public string handling_fee { get; set; }
            public string shipping_discount { get; set; }
        }

        public class Amount
        {
            public string currency { get; set; }
            public string total { get; set; }
            public Details details { get; set; }
        }

        public class Item
        {
            public string name { get; set; }
            public string quantity { get; set; }
            public string price { get; set; }
            public string sku { get; set; }
            public string currency { get; set; }
        }

        public class ItemList
        {
            public IList<Item> items { get; set; }
        }

        public class ShippingAddress
        {
            public string recipient_name { get; set; }
            public string line1 { get; set; }
            public string line2 { get; set; }
            public string city { get; set; }
            public string state { get; set; }
            //public string phone { get; set; }
            public string postal_code { get; set; }
            public string country_code { get; set; }
        }

        public class ItemListWithShipping
        {
            public IList<Item> items { get; set; }
            public ShippingAddress shipping_address { get; set; }
        }

        public class Transaction
        {
            public Amount amount { get; set; }
            public string description { get; set; }
            public ItemList item_list { get; set; }
        }

        public class TransactionWithShipping
        {
            public Amount amount { get; set; }
            public string description { get; set; }
            public string custom { get; set; }
            public ItemListWithShipping item_list { get; set; }
        }

        public class Payer
        {
            public string payment_method { get; set; }
        }

        public class RedirectUrls
        {
            public string cancel_url { get; set; }
            public string return_url { get; set; }
        }



        // two root classes

        public class ExpressCheckoutPaymentData
        {
            public IList<Transaction> transactions { get; set; }
            public Payer payer { get; set; }
            public string intent { get; set; }
            public RedirectUrls redirect_urls { get; set; }

            public ExpressCheckoutPaymentData(string cancelUrl, string placeOrderUrl)
            {
                intent = "sale";

                payer = new PayPalObjects.Payer
                {
                    payment_method = "paypal"
                };

                redirect_urls = new PayPalObjects.RedirectUrls
                {
                    cancel_url = cancelUrl,
                    return_url = placeOrderUrl
                };

                transactions = new List<PayPalObjects.Transaction>
            {
                new PayPalObjects.Transaction
                {
                    amount = new PayPalObjects.Amount
                    {
                        currency = "USD",
                        total = "0",
                        details = new PayPalObjects.Details
                        {
                            shipping = "0",
                            subtotal = "0",
                            tax = "0",
                            insurance = "0",
                            handling_fee = "0",
                            shipping_discount = "0"
                        }
                    },
                    description = "creating a payment",
                    item_list = new PayPalObjects.ItemList
                    {
                        items = new List<PayPalObjects.Item>
                        {
                            new PayPalObjects.Item
                            {
                                name = "Camera",
                                quantity = "1",
                                price = "0",
                                sku = "1",
                                currency = "USD"
                            }
                        }
                    }
                }
            };
            }
        }

        public class ExpressCheckoutShippingPaymentData
        {
            public IList<TransactionWithShipping> transactions { get; set; }
            public Payer payer { get; set; }
            public string intent { get; set; }
            public RedirectUrls redirect_urls { get; set; }

            // constructor
            public ExpressCheckoutShippingPaymentData(string cancelUrl, string payUrl)
            {

                intent = "sale";

                payer = new PayPalObjects.Payer
                {
                    payment_method = "paypal"
                };

                redirect_urls = new PayPalObjects.RedirectUrls
                {
                    cancel_url = cancelUrl,
                    return_url = payUrl
                };

                transactions = new List<PayPalObjects.TransactionWithShipping>
            {
                new PayPalObjects.TransactionWithShipping
                {
                    amount = new PayPalObjects.Amount
                    {
                        currency = "USD",
                        total = "0",
                        details = new PayPalObjects.Details
                        {
                            shipping = "0",
                            subtotal = "0",
                            tax = "0",
                            insurance = "0",
                            handling_fee = "0",
                            shipping_discount = "0"
                        }
                    },
                    description = "Creating a payment",
                    custom = "",
                    item_list = new PayPalObjects.ItemListWithShipping
                    {
                        items = new List<PayPalObjects.Item>
                        {
                            new PayPalObjects.Item
                            {
                                name = "Camera",
                                quantity = "1",
                                price = "0",
                                sku = "1",
                                currency = "USD"
                            }
                        },
                        shipping_address = new PayPalObjects.ShippingAddress {
                            recipient_name = "",
                            line1 = "",
                            line2 = "",
                            city = "",
                            state = "",
                            postal_code = "",
                            country_code = ""
                        }
                    }
                }
            };
            }
        }

    }
------------------------------------------------------------------------------------------------------------------------
HomeController

public class HomeController : Controller
    {
        UnitOfWork uow = new UnitOfWork();
        protected string accessToken;
        protected string approvalUrl;
        protected string requestCsrf;
        protected string shippingFlowFlag;
        protected JObject jsonResponse;

        protected string paymentID;
        protected string paymentState;
        protected string finalAmount;
        protected string currency;
        protected string transactionID;
        protected string payerFirstName;
        protected string payerLastName;
        protected string recipientName;
        protected string addressLine1;
        protected string addressLine2;
        protected string city;
        protected string state;
        protected string postalCode;
        protected string countryCode;
        protected string addressLines;

        public ActionResult PayPal(string total, int UserId)
        {
            AbleContext.Current.UserId = UserId;
            var usersRepository = uow.Repository<UsersRepository>();
            var userData = usersRepository.GetUserById(UserId);

            var user = UserDataSource.LoadForUserName(userData.UserName);

            var address = user.Addresses.Where(x => x.IsBilling == true).FirstOrDefault();

            accessToken = PayPalMethods.getAccessToken();
            Session["accessToken"] = accessToken;          
            Session["UserData"] = new CardModel { userId = UserId, Amount = Convert.ToDecimal(total) };
         

            var hostName = Request.ServerVariables["HTTP_HOST"];
            var appName = String.IsNullOrEmpty(Request.ServerVariables["REQUEST_URI"].Split('/')[0]) ? "" : Request.ServerVariables["REQUEST_URI"].Split('/')[0] + "/";

            var cancelUrl = "http://" + hostName + "/Home/PaymentClose";
            var payUrl = "http://" + hostName + "/Home/Pay";
            var placeOrderUrl = "http://" + hostName + "/Home/PaymentError";

            // JSON data for REST API calls.

            // Session["expressCheckoutPaymentData"] is used in the PayPal Check Out flow
            PayPalObjects.ExpressCheckoutPaymentData expressCheckoutPaymentData = new PayPalObjects.ExpressCheckoutPaymentData(cancelUrl, placeOrderUrl);
            string expressCheckoutPaymentDataJson = JsonConvert.SerializeObject(expressCheckoutPaymentData, Formatting.Indented);
            Session["expressCheckoutPaymentData"] = expressCheckoutPaymentDataJson;

            // Session["expressCheckoutShippingPaymentData"] is used for the Proceed to Checkout flow
            PayPalObjects.ExpressCheckoutShippingPaymentData expressCheckoutShippingPaymentData = new PayPalObjects.ExpressCheckoutShippingPaymentData(cancelUrl, payUrl);
            string expressCheckoutShippingPaymentDataJson = JsonConvert.SerializeObject(expressCheckoutShippingPaymentData, Formatting.Indented);
            Session["expressCheckoutShippingPaymentData"] = expressCheckoutShippingPaymentDataJson;


            // session jason string converted to ExpressCheckoutShippingPaymentData object
            PayPalObjects.ExpressCheckoutShippingPaymentData deserializedEcShipping = JsonConvert.DeserializeObject<PayPalObjects.ExpressCheckoutShippingPaymentData>(Session["expressCheckoutShippingPaymentData"].ToString());

            // update fields based on form selections
            deserializedEcShipping.transactions[0].amount.total = total;
            deserializedEcShipping.transactions[0].amount.details.shipping = "0";
            deserializedEcShipping.transactions[0].item_list.items[0].price = total;
            deserializedEcShipping.transactions[0].amount.details.subtotal = total;

            deserializedEcShipping.transactions[0].item_list.shipping_address.recipient_name = address.FirstName + " " + address.LastName;
            deserializedEcShipping.transactions[0].item_list.shipping_address.line1 = address.Address1;
            deserializedEcShipping.transactions[0].item_list.shipping_address.line2 = address.Address2;
            deserializedEcShipping.transactions[0].item_list.shipping_address.city = address.City;
            deserializedEcShipping.transactions[0].item_list.shipping_address.country_code = address.CountryCode;
            deserializedEcShipping.transactions[0].item_list.shipping_address.postal_code = address.PostalCode;
            deserializedEcShipping.transactions[0].item_list.shipping_address.state = address.Province;

            // convert the modified Object back to JSON
            string expressCheckoutFlowPaymentDataJson = JsonConvert.SerializeObject(deserializedEcShipping, Formatting.Indented);
            Session["expressCheckoutFlowPaymentData"] = expressCheckoutFlowPaymentDataJson;

            approvalUrl = PayPalMethods.getApprovalUrl(accessToken, expressCheckoutFlowPaymentDataJson) + "&useraction=commit"; // "Pay Now" button label
            Session["approvalUrl"] = approvalUrl;
            //return View();
            return Redirect(approvalUrl);
        }



        public ActionResult Pay()
        {
            // Proceed to Checkout flow
            if (Request.QueryString["paymentId"] != null && Request.QueryString["PayerID"] != null)
            {
                var doPaymentResponse = PayPalMethods.doPayment(Session["accessToken"].ToString(), Request.QueryString["paymentId"], Request.QueryString["PayerID"]);

                int httpStatusCode = doPaymentResponse.Item1;
                jsonResponse = doPaymentResponse.Item2;

                // error
                if (httpStatusCode != 200)
                {
                    Session["error"] = jsonResponse;
                    return View("PaymentError");
                }
            }
            // Express checkout flow
            else
            {

                // session JSON string converted to ExpressCheckoutPaymentData object
                PayPalObjects.ExpressCheckoutPaymentData deserializedEC = JsonConvert.DeserializeObject<PayPalObjects.ExpressCheckoutPaymentData>(Session["expressCheckoutPaymentData"].ToString());

                // update object fields based on form selections
                deserializedEC.transactions[0].amount.total = deserializedEC.transactions[0].amount.total.ToString();

                deserializedEC.transactions[0].amount.details.shipping = Request.Form["shipping_method"].ToString();

                string expressCheckoutPaymentUpdateDataJson = JsonConvert.SerializeObject(deserializedEC.transactions[0].amount, Formatting.Indented);

                var doPaymentResponse = PayPalMethods.doPayment(Session["accessToken"].ToString(), Session["paymentId"].ToString(), Session["PayerID"].ToString(), expressCheckoutPaymentUpdateDataJson);

                int httpStatusCode = doPaymentResponse.Item1;
                jsonResponse = doPaymentResponse.Item2;

                // error
                if (httpStatusCode != 200)
                {
                    Session["error"] = jsonResponse;
                    return View("PaymentError");

                }
            }
            PayPalApi payPalApi = new PayPalApi();

            payPalApi.paymentID = jsonResponse["id"].ToString();
            payPalApi.paymentState = jsonResponse["state"].ToString();
            payPalApi.finalAmount = jsonResponse["transactions"][0]["amount"]["total"].ToString();
            payPalApi.currency = jsonResponse["transactions"][0]["amount"]["currency"].ToString();
            payPalApi.transactionID = jsonResponse["transactions"][0]["related_resources"][0]["sale"]["id"].ToString();
            payPalApi.payerFirstName = jsonResponse["payer"]["payer_info"]["first_name"].ToString();
            payPalApi.payerLastName = jsonResponse["payer"]["payer_info"]["last_name"].ToString();
            payPalApi.recipientName = jsonResponse["payer"]["payer_info"]["shipping_address"]["recipient_name"].ToString();
            payPalApi.addressLine1 = jsonResponse["payer"]["payer_info"]["shipping_address"]["line1"].ToString();
            payPalApi.addressLine2 = (jsonResponse["payer"]["payer_info"]["shipping_address"]["line2"] != null) ? jsonResponse["payer"]["payer_info"]["shipping_address"]["line2"].ToString() : "";
            payPalApi.city = jsonResponse["payer"]["payer_info"]["shipping_address"]["city"].ToString();
            payPalApi.state = jsonResponse["payer"]["payer_info"]["shipping_address"]["state"].ToString();
            payPalApi.postalCode = jsonResponse["payer"]["payer_info"]["shipping_address"]["postal_code"].ToString();
            payPalApi.countryCode = jsonResponse["payer"]["payer_info"]["shipping_address"]["country_code"].ToString();

            // format address lines so no blank line
            List<string> addr = new List<string>();

            if (addressLine1 != "")
                addr.Add(addressLine1);
            if (addressLine2 != "")
                addr.Add(addressLine2);

            addressLines = string.Join("<br />", addr);
            Session.Abandon();

            return View(payPalApi);
        }
        [HttpGet]
        public ActionResult PaymentError()
        {
            PayPalApi payPalApi = new PayPalApi();
            JObject o = JObject.Parse(Session["error"].ToString());
            if (o["name"] != null)
            {
                payPalApi.name = o["name"].ToString();
            }

            if (o["message"] != null)
            {
                payPalApi.message = o["message"].ToString();
            }
            if (o["information_link"] != null)
            {
                payPalApi.link = o["information_link"].ToString();
            }
            return View();
        }

        [HttpGet]
        public ActionResult PaymentClose()
        {
            return View();
        }


        [HttpGet]
        public ActionResult PaymentSuccess(CardModel cardModel)
        {            
            //Your logic to save data in database        
            var result = new DataController().PayWithPayPal(cardModel);
            return View();
        }

    }

------------------------------------------------------------------------------------------------------------------------

Views

PayPal.cshtml - default blank

Pay.cshtml -

@model Entity.PayPalApi
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <link href="~/Content/bootstrap.css" rel="stylesheet" />
    <title>Pay</title>
</head>
<body>
    <div class="container-fluid">
        <div class="well" style="width:100% !important">
            <h2 class="text-center">Payment Successfull</h2>
        </div>
     
        <div class="row">
            <div class="col-md-4"></div>
            <div class="col-md-4" style="text-align:center !important">
                <h3>
                    @Model.payerFirstName @Model.payerLastName , thank you for your Order!
                </h3>
                <br /><br />
                <h4>
                    Shipping Address:
                </h4>
                <strong>
                    @Model.recipientName
                </strong><br />
                @Model.addressLines <br />
                @Model.city @Model.state @Model.postalCode <br />
                @Model.countryCode

                <br />
                <br />
                <h4>Payment ID: <small>@Model.paymentID </small></h4>
                <h4>Transaction ID: <small>@Model.transactionID </small></h4>
                <h4>State: <small>@Model.paymentState </small></h4>
                <h4>Total Amount: <small>@Model.finalAmount @Model.currency </small></h4>
                <br />
                <br />
             
                @Html.ActionLink("Close", "PaymentSuccess", "Home", (Entity.CardModel)Session["UserData"] , null)
            </div>
            <div class="col-md-4"></div>
        </div>
        <!----- footer below ---->
    </div>
</body>

</html>


PaymentError.cshtml - 

@model Entity.PayPalApi
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <link href="~/Content/bootstrap.css" rel="stylesheet" />
    <title>Error</title>
</head>
<body>
    <div class="container-fluid">
        <div class="well">
            <h2 class="text-center">Error</h2>
        </div>
        <!----- header above ---->
        <div class="row">
            <div class="col-sm-3"></div>
            <div class="col-sm-6">
                <div class="alert alert-danger" role="alert">
                    <p class="text-center"><strong>The payment could not be completed.</strong></p>
                </div>
                <br />
                <strong>Reason: </strong> @Model.name <br />
                <br />
                <strong>Message: </strong> @Model.message <br />

                <br />
                <br />

                @Html.ActionLink("Close", "PaymentClose", "Home", null, null)
            </div>
            <div class="col-sm-3"></div>
        </div>
        <!----- footer below ---->
    </div>
</body>
</html>


PaymentClose.cshtml - Default
PaymentSuccess.cshtml - Default

--------------------------------------------------------------------------------------------------------------------------

Web.Config -

<appSettings>

 <!-- Whether Sandbox environment is being used, Keep it true for testing -->
    <add key="SANDBOX_FLAG" value="true" />

    <!-- PayPal REST API endpoints -->
    <add key="SANDBOX_ENDPOINT" value="https://api.sandbox.paypal.com" />
    <add key="LIVE_ENDPOINT" value="https://api.paypal.com" />

    <!-- Merchant ID -->
    <add key="MERCHANT_ID" value="E9GCL5FX4TU2C" />


    <!-- PayPal REST App SANDBOX Client Id and Client Secret -->
    <add key="SANDBOX_CLIENT_ID" value="AZ8zBvPlgv_eqrYmOwHbjpevGrjY0ok8mPfrJ1Jhh2nuMN9awOZCpai9-yTWO2XEIpHTuyfoPWY_eTd5" />
    <add key="SANDBOX_CLIENT_SECRET" value="EDi020P7EBhlJo_sv80jPcKIN0k-HSCEX07Eac37h-B9thGVpK7d_qFusYVVu9DNl3emGk2EgO_wYOkR" />


    <!-- Environments -Sandbox and Production/Live -->
    <add key="SANDBOX_ENV" value="sandbox" />
    <add key="LIVE_ENV" value="production" />

    <!-- PayPal REST App SANDBOX Client Id and Client Secret -->
    <add key="LIVE_CLIENT_ID" value="your id" />
    <add key="LIVE_CLIENT_SECRET" value="your secret" />

    <!-- ButtonSource Tracker Code -->
    <add key="SBN_CODE" value="PP-DemoPortal-EC-IC-csharp-REST" />

  </appSettings>




Javascript

-------------------------------------------------------------------------------------------------------------------------

  $scope.openInAppBrowserBlank = function (url) {

            $ionicLoading.show();
            var defaultOptions = {
                location: 'no',
                clearcache: 'no',
                toolbar: 'no'
            };
            $cordovaInAppBrowser.open(url, '_blank', defaultOptions);
            $rootScope.$on('$cordovaInAppBrowser:loadstart', function (e, event) {
             
                var urlSuccessPage = HealthCareCommon.LocalHost() + "Home/PaymentSuccess";
                var urlCancelPage = HealthCareCommon.LocalHost() + "Home/PaymentClose";
                if (event.url.contains(urlSuccessPage)) {
                    $cordovaInAppBrowser.close();
                    $scope.ResetHome();
                    $state.go('app.orderComplete', { completeId: 3 });
                }
                else if (event.url.contains(urlCancelPage)) {
                    $cordovaInAppBrowser.close();
                }
            });
            $rootScope.$on('$cordovaInAppBrowser:loadstop', function (e, event) {
           
            });
            $timeout(function () { $ionicLoading.hide() }, 2000);
        }
read more