Showing posts with label cordova. Show all posts
Showing posts with label cordova. Show all posts

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

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

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

Thursday, 19 January 2017

Common Search Bar Cordova

No comments
Bower - https://github.com/djett41/ionic-filter-bar





Modified Ionic.filter.bar.js

- RequestData is factory for http call

angular.module('jett.ionic.filter.bar', ['ionic']);
(function (angular, document) {
    'use strict';

    angular.module('jett.ionic.filter.bar')
      .directive('ionFilterBar', [
        '$timeout',
        '$ionicGesture',
        '$ionicPlatform',
        function ($timeout, $ionicGesture, $ionicPlatform) {
            var filterBarTemplate;

            //create platform specific filterBar template using filterConfig items
            if ($ionicPlatform.is('android')) {
                filterBarTemplate =
                  '<div class="filter-bar-wrapper filter-bar-{{::config.theme}} filter-bar-transition-{{::config.transition}}">' +
                    '<div class="bar bar-header bar-balanced item-input-inset">' +
                      '<button class="filter-bar-cancel button button-icon icon {{::config.back}}"></button>' +
                      '<label class="item-input-wrapper">' +
                        '<input type="search" class="filter-bar-search" ng-model="data.filterText" placeholder="{{::config.placeholder}}" />' +
                        '<button class="filter-bar-clear button button-icon icon" ng-class="getClearButtonClass()"></button>' +
                      '</label>' +
                    '</div>' +                                    
                    '<div ng-show="!items" class="item">' +
                    '<p>No Record Found</p></div>' +
                    "<div style='overflow: scroll;height: 600px;'><div class='list' style='overflow:scroll' id='Search_{{key}}' ng-repeat='(key, value) in items| groupBy: \"T_ContentType\"'>" +
                    '<div class="item">'+
                    '<h2 class="post-title title-home">{{key}}</h2></div>'+
                    '<a ng-href="#/app/{{item.T_Type}}/{{item.T_ContentID}}" class="item item-thumbnail-left" ng-repeat="item in value">'+
                    '<img ng-src="{{item.T_ContentImageUrl}}" image-lazy-loader="spiral"></img>'+
                    '<h2 class="headerColor">'+
                    '{{item.T_ContentTitle}}</h2>'+
                    '<div ng-bind-html="item.T_Description |cut:true:30" style="word-wrap: break-word;white-space: normal;">'+
                    '</div></a></div><div></div>';
            } else {
                filterBarTemplate =
                  '<div class="filter-bar-wrapper filter-bar-{{::config.theme}} filter-bar-transition-{{::config.transition}}">' +
                  //'<div class="bar bar-header bar-{{::config.theme}} item-input-inset">' +
                    '<div class="bar bar-header bar-balanced item-input-inset">' +
                      '<label class="item-input-wrapper">' +
                        '<i class="icon {{::config.search}} placeholder-icon"></i>' +
                        '<input type="search" class="filter-bar-search" ng-model="data.filterText" placeholder="{{::config.placeholder}}"/>' +
                        '<button class="filter-bar-clear button button-icon icon" ng-class="getClearButtonClass()"></button>' +
                      '</label>' +
                      '<button class="filter-bar-cancel button button-clear" ng-bind-html="::cancelText"></button>' +
                    '</div>' +
                  '</div>';
            }

            return {
                restrict: 'E',
                scope: true,
                link: function ($scope, $element) {
                    var el = $element[0];
                    var clearEl = el.querySelector('.filter-bar-clear');
                    var cancelEl = el.querySelector('.filter-bar-cancel');
                    var inputEl = el.querySelector('.filter-bar-search');
                    var filterTextTimeout;
                    var swipeGesture;
                    var backdrop;
                    var backdropClick;
                    var filterWatch;
                    var dataWatch;

                    // Action when filter bar is cancelled via backdrop click/swipe or cancel/back buton click.
                    // Invokes cancel function defined in filterBar service
                    var cancelFilterBar = function () {
                        $scope.cancelFilterBar();
                    };

                    // If backdrop is enabled, create and append it to filter, then add click/swipe listeners to cancel filter
                    if ($scope.config.backdrop) {
                        backdrop = angular.element('<div class="filter-bar-backdrop"></div>');
                        $element.append(backdrop);

                        backdropClick = function (e) {
                            if (e.target == backdrop[0]) {
                                cancelFilterBar();
                            }
                        };

                        backdrop.bind('click', backdropClick);
                        swipeGesture = $ionicGesture.on('swipe', backdropClick, backdrop);
                    }

                    //Sure we could have had 1 function that also checked for favoritesEnabled.. but no need to keep checking a var that wont change
                    if ($scope.favoritesEnabled) {
                        $scope.getClearButtonClass = function () {
                            return $scope.data.filterText.length ? $scope.config.clear : $scope.config.favorite;
                        }
                    } else {
                        $scope.getClearButtonClass = function () {
                            return $scope.data.filterText.length ? $scope.config.clear : 'filter-bar-element-hide';
                        }
                    }

                    // When clear button is clicked, clear filterText, hide clear button, show backdrop, and focus the input
                    var clearClick = function () {
                        if (clearEl.classList.contains($scope.config.favorite)) {
                            $scope.showModal();
                        } else {
                            $timeout(function () {
                                $scope.data.filterText = '';
                                ionic.requestAnimationFrame(function () {
                                    $scope.showBackdrop();
                                    $scope.scrollItemsTop();
                                    $scope.focusInput();
                                });
                            });
                        }
                    };

                    // Bind touchstart so we can regain focus of input even while scrolling
                    var inputClick = function () {
                        $scope.scrollItemsTop();
                        $scope.focusInput();
                    };

                    // When a non escape key is pressed, show/hide backdrop/clear button based on filterText length
                    var keyUp = function (e) {
                        if (e.which == 27) {
                            cancelFilterBar();
                        } else if ($scope.data.filterText && $scope.data.filterText.length) {
                            $scope.hideBackdrop();
                        } else {
                            $scope.showBackdrop();
                        }
                    };

                    //Event Listeners
                    cancelEl.addEventListener('click', cancelFilterBar);
                    // Since we are wrapping with label, need to bind touchstart rather than click.
                    // Even if we use div instead of label need to bind touchstart.  Click isn't allowing input to regain focus quickly
                    clearEl.addEventListener('touchstart', clearClick);
                    clearEl.addEventListener('mousedown', clearClick);

                    inputEl.addEventListener('touchstart', inputClick);
                    inputEl.addEventListener('mousedown', inputClick);

                    document.addEventListener('keyup', keyUp);

                    // Calls the services filterItems function with the filterText to filter items
                    var filterItems = function () {
                        $scope.filterItems($scope.data.filterText);
                    };

                    // Clean up when scope is destroyed
                    $scope.$on('$destroy', function () {
                        $element.remove();
                        document.removeEventListener('keyup', keyUp);
                        if (backdrop) {
                            $ionicGesture.off(swipeGesture, 'swipe', backdropClick);
                        }
                        filterWatch();
                        dataWatch();
                    });

                    // Watch for changes on filterText and call filterItems when filterText has changed.
                    // If debounce is enabled, filter items by the specified or default delay.
                    // Prefer timeout debounce over ng-model-options so if filterText is cleared, initial items show up right away with no delay
                    filterWatch = $scope.$watch('data.filterText', function (newFilterText, oldFilterText) {
                        var delay;

                        if (filterTextTimeout) {
                            $timeout.cancel(filterTextTimeout);
                        }

                        if (newFilterText !== oldFilterText) {
                            delay = (newFilterText.length && $scope.debounce) ? $scope.delay : 0;
                            filterTextTimeout = $timeout(filterItems, delay, false);
                        }
                    });
                    dataWatch = $scope.$watch('data.filterData', function (newFilterText, oldFilterText) {
                       
                    });
                },
                template: filterBarTemplate
            };
        }]);

})(angular, document);

/* global angular */
/**
 * This copies the functionality of the ionicConfig provider to allow for platform specific configuration
 */
(function (angular) {
    'use strict';

    angular.module('jett.ionic.filter.bar')
      .provider('$ionicFilterBarConfig', function () {

          var provider = this;
          provider.platform = {};
          var PLATFORM = 'platform';

          var configProperties = {
              theme: PLATFORM,
              clear: PLATFORM,
              add: PLATFORM,
              close: PLATFORM,
              done: PLATFORM,
              remove: PLATFORM,
              reorder: PLATFORM,
              favorite: PLATFORM,
              search: PLATFORM,
              backdrop: PLATFORM,
              transition: PLATFORM,
              platform: {},
              placeholder: PLATFORM
          };

          createConfig(configProperties, provider, '');

          // Default
          // -------------------------
          setPlatformConfig('default', {
              clear: 'ion-ios-close',
              add: 'ion-ios-plus-outline',
              close: 'ion-ios-close-empty',
              done: 'ion-ios-checkmark-empty',
              remove: 'ion-ios-trash-outline',
              reorder: 'ion-drag',
              favorite: 'ion-ios-star',
              search: 'ion-ios-search-strong',
              backdrop: true,
              transition: 'vertical',
              placeholder: 'Search'
          });

          // iOS (it is the default already)
          // -------------------------
          setPlatformConfig('ios', {});

          // Android
          // -------------------------
          setPlatformConfig('android', {
              clear: 'ion-android-close',
              close: 'ion-android-close',
              done: 'ion-android-done',
              remove: 'ion-android-delete',
              favorite: 'ion-android-star',
              search: false,
              backdrop: false,
              transition: 'horizontal'
          });

          provider.setPlatformConfig = setPlatformConfig;

          // private: used to set platform configs
          function setPlatformConfig(platformName, platformConfigs) {
              configProperties.platform[platformName] = platformConfigs;
              provider.platform[platformName] = {};

              addConfig(configProperties, configProperties.platform[platformName]);

              createConfig(configProperties.platform[platformName], provider.platform[platformName], '');
          }

          // private: used to recursively add new platform configs
          function addConfig(configObj, platformObj) {
              for (var n in configObj) {
                  if (n != PLATFORM && configObj.hasOwnProperty(n)) {
                      if (angular.isObject(configObj[n])) {
                          if (!angular.isDefined(platformObj[n])) {
                              platformObj[n] = {};
                          }
                          addConfig(configObj[n], platformObj[n]);

                      } else if (!angular.isDefined(platformObj[n])) {
                          platformObj[n] = null;
                      }
                  }
              }
          }

          // private: create methods for each config to get/set
          function createConfig(configObj, providerObj, platformPath) {
              angular.forEach(configObj, function (value, namespace) {

                  if (angular.isObject(configObj[namespace])) {
                      // recursively drill down the config object so we can create a method for each one
                      providerObj[namespace] = {};
                      createConfig(configObj[namespace], providerObj[namespace], platformPath + '.' + namespace);

                  } else {
                      // create a method for the provider/config methods that will be exposed
                      providerObj[namespace] = function (newValue) {
                          if (arguments.length) {
                              configObj[namespace] = newValue;
                              return providerObj;
                          }
                          if (configObj[namespace] == PLATFORM) {
                              // if the config is set to 'platform', then get this config's platform value
                              var platformConfig = stringObj(configProperties.platform, ionic.Platform.platform() + platformPath + '.' + namespace);
                              if (platformConfig || platformConfig === false) {
                                  return platformConfig;
                              }
                              // didnt find a specific platform config, now try the default
                              return stringObj(configProperties.platform, 'default' + platformPath + '.' + namespace);
                          }
                          return configObj[namespace];
                      };
                  }

              });
          }

          //splits a string by dot operator and accesses the end var.  For example in a.b.c,
          function stringObj(obj, str) {
              str = str.split(".");
              for (var i = 0; i < str.length; i++) {
                  if (obj && angular.isDefined(obj[str[i]])) {
                      obj = obj[str[i]];
                  } else {
                      return null;
                  }
              }
              return obj;
          }

          provider.$get = function () {
              return provider;
          };

      });

})(angular);

/* global angular,ionic */
/**
 * @ngdoc service
 * @name $ionicFilterBar
 * @module ionic
 * @description The Filter Bar is an animated bar that allows a user to search or filter an array of items.
 */
(function (angular, ionic) {
    'use strict';

    var filterBarModalTemplate =
      '<ion-modal-view ng-controller="$ionicFilterBarModalCtrl" class="filter-bar-modal">' +
      '<ion-header-bar class="bar bar-{{::config.theme}} disable-user-behavior">' +
        '<button class="button button-icon {{::config.close}}" ng-click="closeModal()"></button>' +
        '<h1 class="title" ng-bind-html="::favoritesTitle"></h1>' +
        '<button ng-if="searches.length > 1" class="button button-icon" ng-class="displayData.showReorder ? config.done : config.reorder" ng-click="displayData.showReorder = !displayData.showReorder"></button>' +
      '</ion-header-bar>' +
      '<ion-content>' +
        '<ion-list show-reorder="displayData.showReorder" delegate-handle="searches-list">' +
          '<ion-item ng-repeat="item in searches" class="item-remove-animate" ng-class="{reordered: item.reordered}" ng-click="itemClicked(item.text, $event)">' +
            '<span ng-bind-html="item.text"></span>' +
            '<ion-option-button class="button-assertive icon {{::config.remove}}" ng-click="deleteItem(item)"></ion-option-button>' +
            '<ion-reorder-button class="{{::config.reorder}}" on-reorder="moveItem(item, $fromIndex, $toIndex)"></ion-reorder-button>' +
          '</ion-item>' +
          '<div class="item item-input">' +
            '<input type="text" ng-model="newItem.text" placeholder="{{::favoritesAddPlaceholder}}"/>' +
            '<button class="button button-icon icon {{::config.add}}" ng-click="addItem(newItem)"></button>' +
          '</div>' +
        '</ion-list>' +
      '</ion-content> ' +
      '</ion-modal-view>';

    var getNavBarTheme = function ($navBar) {
        var themes = ['light', 'stable', 'positive', 'calm', 'balanced', 'energized', 'assertive', 'royal', 'dark'];
        var classList = $navBar && $navBar.classList;

        if (!classList) {
            return;
        }

        for (var i = 0; i < themes.length; i++) {
            if (classList.contains('bar-' + themes[i])) {
                return themes[i];
            }
        }
    };

    angular.module('jett.ionic.filter.bar')
      .factory('$ionicFilterBar', [
        '$document',
        '$rootScope',
        '$compile',
        '$timeout',
        '$filter',
        '$ionicPlatform',
        '$ionicFilterBarConfig',
        '$ionicConfig',
        '$ionicModal',
        '$ionicScrollDelegate',
        'RequestData',
        function ($document, $rootScope, $compile, $timeout, $filter, $ionicPlatform, $ionicFilterBarConfig, $ionicConfig, $ionicModal, $ionicScrollDelegate,RequestData) {
            var isShown = false;
            var $body = $document[0].body;
            var templateConfig = {
                theme: $ionicFilterBarConfig.theme(),
                transition: $ionicFilterBarConfig.transition(),
                back: $ionicConfig.backButton.icon(),
                clear: $ionicFilterBarConfig.clear(),
                favorite: $ionicFilterBarConfig.favorite(),
                search: $ionicFilterBarConfig.search(),
                backdrop: $ionicFilterBarConfig.backdrop(),
                placeholder: $ionicFilterBarConfig.placeholder(),
                close: $ionicFilterBarConfig.close(),
                done: $ionicFilterBarConfig.done(),
                reorder: $ionicFilterBarConfig.reorder(),
                remove: $ionicFilterBarConfig.remove(),
                add: $ionicFilterBarConfig.add()
            };

            /**
             * @ngdoc method
             * @name $ionicFilterBar#show
             * @description
             * Load and return a new filter bar.
             *
             * A new isolated scope will be created for the filter bar and the new filter bar will be appended to the
             * body, covering the header bar.
             *
             * @returns {function} `hideFilterBar` A function which, when called, hides & cancels the filter bar.
             */
            function filterBar(opts) {
                //if filterBar is already shown return
                if (isShown) {
                    return;
                }

                isShown = true;
                opts = opts || {};

                var scope = $rootScope.$new(true);
                var backdropShown = false;
                var isKeyboardShown = false;

                //if container option is set, determine the container element by querying for the container class
                if (opts.container) {
                    opts.container = $body.querySelector(opts.container);
                }

                //extend scope defaults with supplied options
                angular.extend(scope, {
                    config: templateConfig,
                    $deregisterBackButton: angular.noop,
                    update: angular.noop,
                    cancel: angular.noop,
                    done: angular.noop,
                    scrollDelegate: $ionicScrollDelegate,
                    filter: $filter('filter'),
                    filterProperties: null,
                    expression: null,
                    comparator: null,
                    debounce: true,
                    delay: 300,
                    cancelText: 'Cancel',
                    cancelOnStateChange: true,
                    container: $body,
                    favoritesTitle: 'Favorite Searches',
                    favoritesAddPlaceholder: 'Add a search term',
                    favoritesEnabled: false,
                    favoritesKey: 'ionic_filter_bar_favorites'
                }, opts);

                scope.data = { filterText: '' };

                //if no custom theme was configured, get theme of containers bar-header
                if (!scope.config.theme) {
                    scope.config.theme = getNavBarTheme(scope.container.querySelector('.bar.bar-header'));
                }

                // Compile the template
                var element = scope.element = $compile('<ion-filter-bar class="filter-bar"></ion-filter-bar>')(scope);

                // Grab required jQLite elements
                var filterWrapperEl = element.children().eq(0);
                var input = filterWrapperEl.find('input')[0];
                var backdropEl = element.children().eq(1);

                //get scrollView
                var scrollView = scope.scrollDelegate.getScrollView();
                var canScroll = !!scrollView;

                //get the scroll container if scrolling is available
                var $scrollContainer = canScroll ? scrollView.__container : null;

                var stateChangeListenDone = scope.cancelOnStateChange ?
                  $rootScope.$on('$stateChangeSuccess', function () { scope.cancelFilterBar(); }) :
                  angular.noop;

                // Focus the input which will show the keyboard.
                var showKeyboard = function () {
                    if (!isKeyboardShown) {
                        isKeyboardShown = true;
                        input && input.focus();
                    }
                };

                // Blur the input which will hide the keyboard.
                // Even if we need to bring in ionic.keyboard in the future, blur is preferred so keyboard animates out.
                var hideKeyboard = function () {
                    if (isKeyboardShown) {
                        isKeyboardShown = false;
                        input && input.blur();
                    }
                };

                // When the filtered list is scrolled, we want to hide the keyboard as long as it's not already hidden
                var handleScroll = function () {
                    if (scrollView.__scrollTop > 0) {
                        hideKeyboard();
                    }
                };

                // Scrolls the list of items to the top via the scroll delegate
                scope.scrollItemsTop = function () {
                    if (canScroll && scrollView.__scrollTop > 0 && scope.scrollDelegate.scrollTop) {
                        scope.scrollDelegate.scrollTop();
                    }
                };

                // Set isKeyboardShown to force showing keyboard on search focus.
                scope.focusInput = function () {
                    isKeyboardShown = false;
                    showKeyboard();
                };

                // Hide the filterBar backdrop if in the DOM and not already hidden.
                scope.hideBackdrop = function () {
                    if (backdropEl.length && backdropShown) {
                        backdropShown = false;
                        backdropEl.removeClass('active').css('display', 'none');
                    }
                };

                // Show the filterBar backdrop if in the DOM and not already shown.
                scope.showBackdrop = function () {
                    if (backdropEl.length && !backdropShown) {
                        backdropShown = true;
                        backdropEl.css('display', 'block').addClass('active');
                    }
                };

                scope.showModal = function () {
                    scope.modal = $ionicModal.fromTemplate(filterBarModalTemplate, {
                        scope: scope
                    });
                    scope.modal.show();
                };

                // Filters the supplied list of items via the supplied filterText.
                // How items are filtered depends on the supplied filter object, and expression
                // Filtered items will be sent to update
                scope.filterItems = function (filterText) {
                    var filterExp, filteredItems;
                    debugger
                    // pass back original list if filterText is empty.
                    // Otherwise filter by expression, supplied properties, or filterText.
                    if (!filterText.length) {
                        filteredItems = scope.items;
                    } else {
                        if (scope.expression) {
                            filterExp = angular.bind(this, scope.expression, filterText);
                        } else if (angular.isArray(scope.filterProperties)) {
                            filterExp = {};
                            angular.forEach(scope.filterProperties, function (property) {
                                filterExp[property] = filterText;
                            });
                        } else if (scope.filterProperties) {
                            filterExp = {};
                            filterExp[scope.filterProperties] = filterText;
                        } else {
                            filterExp = filterText;
                        }
                        debugger
                        var promisePost = RequestData.searchItems(filterText);
                        promisePost.then(function (pl) {
                            debugger
                            if (pl.status == HealthCareCommon.GetResponseStatus('Not Found')) {
                                //alert('Something went wrong');
                            }
                            else {
                                scope.items = pl.data;
                                filteredItems = scope.filter(scope.items, filterExp, scope.comparator);
                            }
                        }, function () {
                        });

                        filteredItems = scope.filter(scope.items, filterExp, scope.comparator);
                    }

                    $timeout(function () {
                        scope.update(filteredItems, filterText);
                        scope.scrollItemsTop();
                    });
                };

                // registerBackButtonAction returns a callback to deregister the action
                scope.$deregisterBackButton = $ionicPlatform.registerBackButtonAction(
                  function () {
                      $timeout(scope.cancelFilterBar);
                  }, 300
                );

                // Removes the filterBar from the body and cleans up vars/events.  Once the backdrop is hidden we can invoke done
                scope.removeFilterBar = function (done) {
                    if (scope.removed) return;

                    scope.removed = true;

                    //animate the filterBar out, hide keyboard and backdrop
                    ionic.requestAnimationFrame(function () {
                        filterWrapperEl.removeClass('filter-bar-in');
                        hideKeyboard();
                        scope.hideBackdrop();                      
                        //$('.filter-bar').css('overflow', 'visible');
                        //Wait before cleaning up so element isn't removed before filter bar animates out
                        $timeout(function () {
                            scope.scrollItemsTop();
                            scope.update(scope.items);
                            scope.$destroy();
                            element.remove();
                            scope.cancelFilterBar.$scope = scope.modal = $scrollContainer = scrollView = filterWrapperEl = backdropEl = input = null;
                            isShown = false;
                            (done || angular.noop)();
                        }, 350);
                    });

                    $timeout(function () {
                        // wait to remove this due to a 300ms delay native
                        // click which would trigging whatever was underneath this
                        scope.container.classList.remove('filter-bar-open');
                    }, 400);

                    scope.$deregisterBackButton();
                    stateChangeListenDone();

                    //unbind scroll event
                    if ($scrollContainer) {
                        $scrollContainer.removeEventListener('scroll', handleScroll);
                    }
                };

                // Appends the filterBar to the body.  Once the backdrop is hidden we can invoke done
                scope.showFilterBar = function (done) {
                    if (scope.removed) return;

                    scope.container.appendChild(element[0]);
                    scope.container.classList.add('filter-bar-open');

                    //scroll items to the top before starting the animation
                    scope.scrollItemsTop();

                    //start filterBar animation, show backrop and focus the input
                    ionic.requestAnimationFrame(function () {
                        if (scope.removed) return;

                        $timeout(function () {
                            filterWrapperEl.addClass('filter-bar-in');
                            scope.focusInput();
                            scope.showBackdrop();
                            (done || angular.noop)();
                        }, 20, false);
                    });

                    if ($scrollContainer) {
                        $scrollContainer.addEventListener('scroll', handleScroll);
                    }
                };

                // called when the user presses the backdrop, cancel/back button, changes state
                scope.cancelFilterBar = function () {
                    // after the animation is out, call the cancel callback
                    scope.removeFilterBar(scope.cancel);
                };

                scope.showFilterBar(scope.done);

                // Expose the scope on $ionFilterBar's return value for the sake of testing it.
                scope.cancelFilterBar.$scope = scope;

                return scope.cancelFilterBar;
            }

            return {
                show: filterBar
            };
        }]);


})(angular, ionic);

/* global angular */
(function (angular) {
    'use strict';

    angular.module('jett.ionic.filter.bar')
      .controller('$ionicFilterBarModalCtrl', [
        '$window',
        '$scope',
        '$timeout',
        '$ionicListDelegate',
        function ($window, $scope, $timeout, $ionicListDelegate) {
            var searchesKey = $scope.$parent.favoritesKey;

            $scope.displayData = { showReorder: false };
            $scope.searches = angular.fromJson($window.localStorage.getItem(searchesKey)) || [];
            $scope.newItem = { text: '' };

            $scope.moveItem = function (item, fromIndex, toIndex) {
                item.reordered = true;
                $scope.searches.splice(fromIndex, 1);
                $scope.searches.splice(toIndex, 0, item);

                $timeout(function () {
                    delete item.reordered;
                }, 500);
            };

            $scope.deleteItem = function (item) {
                var index = $scope.searches.indexOf(item);
                $scope.searches.splice(index, 1);
            };

            $scope.addItem = function () {
                if ($scope.newItem.text) {
                    $scope.searches.push({
                        text: $scope.newItem.text
                    });
                    $scope.newItem.text = '';
                }
            };

            $scope.closeModal = function () {
                $window.localStorage.setItem(searchesKey, angular.toJson($scope.searches));
                $scope.$parent.modal.remove();
            };

            $scope.itemClicked = function (filterText, $event) {
                var isOptionButtonsClosed = !!$event.currentTarget.querySelector('.item-options.invisible');

                if (isOptionButtonsClosed) {
                    $scope.closeModal();
                    $scope.$parent.hideBackdrop();
                    $scope.$parent.data.filterText = filterText;
                    $scope.$parent.filterItems(filterText);
                } else {
                    $ionicListDelegate.$getByHandle('searches-list').closeOptionButtons();
                }
            };

        }]);

})(angular);

CSS

filter-bar {
  position: fixed;
  width: 100%;
  height: 100%;
  z-index: 10;  
}

Factory

app.factory('SearchBar', ['$rootScope', '$ionicFilterBar','RequestData',
    function ($rootScope, $ionicFilterBar, RequestData) {
        return {
            SearchFilter: function (data) {
                filterBarInstance = $ionicFilterBar.show({
                    items: data,
                    update: function (filteredItems, filterText) {                       
                        data = filteredItems;
                        if (filterText) {                            
                        }
                    }
                });
            }
        }
    }]);
read more