/* * This method shows use of optional payment details and item list. */ private PayPalPayment getStuffToBuy(string paymentIntent) { //--- include an item list, payment amount details PayPalItem[] items = { new PayPalItem("sample item #1", new Java.Lang.Integer(2), new BigDecimal("87.50"), "USD", "sku-12345678"), new PayPalItem("free sample item #2", new Java.Lang.Integer(1), new BigDecimal("0.00"), "USD", "sku-zero-price"), new PayPalItem("sample item #3 with a longer name", new Java.Lang.Integer(6), new BigDecimal("37.99"), "USD", "sku-33333") }; BigDecimal subtotal = PayPalItem.GetItemTotal(items); BigDecimal shipping = new BigDecimal("7.21"); BigDecimal tax = new BigDecimal("4.67"); PayPalPaymentDetails paymentDetails = new PayPalPaymentDetails(shipping, subtotal, tax); BigDecimal amount = subtotal.Add(shipping).Add(tax); PayPalPayment payment = new PayPalPayment(amount, "USD", "sample item", paymentIntent); payment.Items(items).PaymentDetails(paymentDetails); //--- set other optional fields like invoice_number, custom field, and soft_descriptor payment.Custom("This is text that will be associated with the payment that the app can use."); return(payment); }
public void BuyItem( PayPal.Forms.Abstractions.PayPalItem item, Decimal xftax, Action onCancelled, Action <string> onSuccess, Action <string> onError, PayPal.Forms.Abstractions.ShippingAddress address ) { OnCancelled = onCancelled; OnSuccess = onSuccess; OnError = onError; var subTotal = new NSDecimalNumber(RoundNumber((double)item.Price)); NSDecimalNumber amount = subTotal.Add(new NSDecimalNumber(RoundNumber((double)xftax))); var paymentDetails = PayPalPaymentDetails.PaymentDetailsWithSubtotal(subTotal, new NSDecimalNumber(0), new NSDecimalNumber(RoundNumber((double)xftax))); var payment = PayPalPayment.PaymentWithAmount(amount, item.Currency, item.Name, PayPalPaymentIntent.Sale); payment.PaymentDetails = paymentDetails; payment.Items = new NSObject[] { PayPalItem.ItemWithName( item.Name, 1, new NSDecimalNumber(RoundNumber((double)item.Price)), item.Currency, item.SKU ) }; if (address != null) { payment.ShippingAddress = PayPalShippingAddress.ShippingAddressWithRecipientName( address.RecipientName, address.Line1, address.Line2, address.City, address.State, address.PostalCode, address.CountryCode ); } if (payment.Processable) { var paymentViewController = new PayPalPaymentViewController(payment, _payPalConfig, this); var top = GetTopViewController(UIApplication.SharedApplication.KeyWindow); top.PresentViewController(paymentViewController, true, null); } else { OnError?.Invoke("This particular payment will always be processable. If, for example, the amount was negative or the shortDescription was empty, this payment wouldn't be processable, and you'd want to handle that here."); OnError = null; Debug.WriteLine("Payment not processalbe:" + payment.Items); } }
public Task <PaymentResult> Buy(PayPalItem item, Decimal tax, ShippingAddress address = null) { if (buyTcs != null) { buyTcs.TrySetCanceled(); buyTcs.TrySetResult(null); } buyTcs = new TaskCompletionSource <PaymentResult> (); Manager.BuyItem(item, tax, SendOnPayPalPaymentDidCancel, SendOnPayPalPaymentCompleted, SendOnPayPalPaymentError, address); return(buyTcs.Task); }
public override void ViewDidLoad() { base.ViewDidLoad(); var config = new PayPalConfiguration() { AcceptCreditCards = true, LanguageOrLocale = "en", MerchantName = "Merchant", MerchantPrivacyPolicyURL = new NSUrl("https://www.paypal.com/webapps/mpp/ua/privacy-full"), MerchantUserAgreementURL = new NSUrl("https://www.paypal.com/webapps/mpp/ua/useragreement-full") }; var item1 = new PayPalItem() { Name = "DoofesDing", Price = new NSDecimalNumber("10.00"), Currency = "EUR", Quantity = 1, Sku = "FOO-29376" }; var item2 = new PayPalItem() { Name = "DoofesDing2", Price = new NSDecimalNumber("15.00"), Currency = "EUR", Quantity = 1, Sku = "FOO-23476" }; var items = new PayPalItem[] { item1, item2 }; var payment = new PayPalPayment() { Amount = new NSDecimalNumber("25.00"), CurrencyCode = "EUR", ShortDescription = "Stuffz", Items = items }; myDelegate = new PPDelegate(this); paypalVC = new PayPalPaymentViewController(payment, config, myDelegate); var payBtn = new UIButton(new RectangleF(60, 100, 200, 60)); payBtn.SetTitle("Pay", UIControlState.Normal); payBtn.BackgroundColor = UIColor.Blue; payBtn.TouchUpInside += (object sender, EventArgs e) => { this.PresentViewController(paypalVC, true, null); }; Add(payBtn); }
public void BuySomething() { // Remove our last completed payment, just for demo purposes. ResultText = ""; // Note: For purposes of illustration, this example shows a payment that includes // both payment details (subtotal, shipping, tax) and multiple items. // You would only specify these if appropriate to your situation. // Otherwise, you can leave payment.items and/or payment.paymentDetails nil, // and simply set payment.amount to your total charge. // Optional: include multiple items var item1 = PayPalItem.ItemWithName("Old jeans with holes", 2, new NSDecimalNumber("84.99"), "USD", "Hip-0037"); var item2 = PayPalItem.ItemWithName("Free rainbow patch", 1, new NSDecimalNumber("0.00"), "USD", "Hip-00066"); var item3 = PayPalItem.ItemWithName("Long-sleeve plaid shirt (mustache not included)", 1, new NSDecimalNumber("37.99"), "USD", "Hip-00291"); var items = new PayPalItem[] { item1, item2, item3 }; var subtotal = PayPalItem.TotalPriceForItems(items); // Optional: include payment details var shipping = new NSDecimalNumber("5.99"); var tax = new NSDecimalNumber("2.50"); var paymentDetails = PayPalPaymentDetails.PaymentDetailsWithSubtotal(subtotal, shipping, tax); var total = subtotal.Add(shipping).Add(tax); var payment = PayPalPayment.PaymentWithAmount(total, "USD", "Hipster Clothing", PayPalPaymentIntent.Sale); payment.Items = items; payment.PaymentDetails = paymentDetails; if (payment.Processable) { var paymentViewController = new PayPalPaymentViewController(payment, _payPalConfig, this); var top = GetTopViewController(UIApplication.SharedApplication.KeyWindow); top.PresentViewController(paymentViewController, true, null); } else { // This particular payment will always be processable. If, for // example, the amount was negative or the shortDescription was // empty, this payment wouldn't be processable, and you'd want // to handle that here. Debug.WriteLine("Payment not processalbe:" + payment.Items); } }
public void BuySomething() { // Remove our last completed payment, just for demo purposes. ResultText = ""; // Note: For purposes of illustration, this example shows a payment that includes // both payment details (subtotal, shipping, tax) and multiple items. // You would only specify these if appropriate to your situation. // Otherwise, you can leave payment.items and/or payment.paymentDetails nil, // and simply set payment.amount to your total charge. // Optional: include multiple items var item1 = PayPalItem.ItemWithName("Old jeans with holes", 2, new NSDecimalNumber("84.99"), "USD", "Hip-0037"); var item2 = PayPalItem.ItemWithName ("Free rainbow patch", 1, new NSDecimalNumber ("0.00"), "USD", "Hip-00066"); var item3 = PayPalItem.ItemWithName ("Long-sleeve plaid shirt (mustache not included)", 1, new NSDecimalNumber ("37.99"), "USD", "Hip-00291"); var items = new PayPalItem[] { item1, item2, item3 }; var subtotal = PayPalItem.TotalPriceForItems (items); // Optional: include payment details var shipping = new NSDecimalNumber("5.99"); var tax = new NSDecimalNumber ("2.50"); var paymentDetails = PayPalPaymentDetails.PaymentDetailsWithSubtotal (subtotal, shipping, tax); var total = subtotal.Add (shipping).Add (tax); var payment = PayPalPayment.PaymentWithAmount (total, "USD", "Hipster Clothing", PayPalPaymentIntent.Sale); payment.Items = items; payment.PaymentDetails = paymentDetails; if (payment.Processable) { var paymentViewController = new PayPalPaymentViewController(payment, _payPalConfig, this); var top = GetTopViewController (UIApplication.SharedApplication.KeyWindow); top.PresentViewController (paymentViewController, true, null); }else { // This particular payment will always be processable. If, for // example, the amount was negative or the shortDescription was // empty, this payment wouldn't be processable, and you'd want // to handle that here. Debug.WriteLine("Payment not processalbe:"+payment.Items); } }
public void BuyItems( PayPal.Forms.Abstractions.PayPalItem[] items, Decimal xfshipping, Decimal xftax, Action onCancelled, Action <string> onSuccess, Action <string> onError, PayPal.Forms.Abstractions.ShippingAddress address ) { OnCancelled = onCancelled; OnSuccess = onSuccess; OnError = onError; List <PayPalItem> nativeItems = new List <PayPalItem>(); foreach (var product in items) { nativeItems.Add(PayPalItem.ItemWithName( product.Name, (nuint)product.Quantity, new NSDecimalNumber(RoundNumber((double)product.Price)), product.Currency, product.SKU) ); } var subtotal = PayPalItem.TotalPriceForItems(nativeItems.ToArray()); var shipping = new NSDecimalNumber(RoundNumber((double)xfshipping)); var tax = new NSDecimalNumber(RoundNumber((double)xftax)); var paymentDetails = PayPalPaymentDetails.PaymentDetailsWithSubtotal(subtotal, shipping, tax); var total = subtotal.Add(shipping).Add(tax); var payment = PayPalPayment.PaymentWithAmount(total, nativeItems.FirstOrDefault().Currency, "Multiple items", PayPalPaymentIntent.Sale); payment.Items = nativeItems.ToArray(); payment.PaymentDetails = paymentDetails; if (address != null) { payment.ShippingAddress = PayPalShippingAddress.ShippingAddressWithRecipientName( address.RecipientName, address.Line1, address.Line2, address.City, address.State, address.PostalCode, address.CountryCode ); } if (payment.Processable) { var paymentViewController = new PayPalPaymentViewController(payment, _payPalConfig, this); var top = GetTopViewController(UIApplication.SharedApplication.KeyWindow); top.PresentViewController(paymentViewController, true, null); } else { OnError?.Invoke("This particular payment will always be processable. If, for example, the amount was negative or the shortDescription was empty, this payment wouldn't be processable, and you'd want to handle that here."); Debug.WriteLine("Payment not processalbe:" + payment.Items); } }
public void BuyItems( PayPal.Forms.Abstractions.PayPalItem[] items, Decimal xfshipping, Decimal xftax, PaymentIntent xfintent, Action onCancelled, Action <string> onSuccess, Action <string> onError, PayPal.Forms.Abstractions.ShippingAddress address ) { OnCancelled = onCancelled; OnSuccess = onSuccess; OnError = onError; List <PayPalItem> nativeItems = new List <PayPalItem> (); foreach (var product in items) { nativeItems.Add(new PayPalItem( product.Name, new Java.Lang.Integer((int)product.Quantity), new BigDecimal(RoundNumber((double)product.Price)), product.Currency, product.SKU) ); } BigDecimal subtotal = PayPalItem.GetItemTotal(nativeItems.ToArray()); BigDecimal shipping = new BigDecimal(RoundNumber((double)xfshipping)); BigDecimal tax = new BigDecimal(RoundNumber((double)xftax)); PayPalPaymentDetails paymentDetails = new PayPalPaymentDetails(shipping, subtotal, tax); BigDecimal amount = subtotal.Add(shipping).Add(tax); string paymentIntent; switch (xfintent) { case PaymentIntent.Authorize: paymentIntent = PayPalPayment.PaymentIntentAuthorize; break; case PaymentIntent.Order: paymentIntent = PayPalPayment.PaymentIntentOrder; break; default: case PaymentIntent.Sale: paymentIntent = PayPalPayment.PaymentIntentSale; break; } PayPalPayment payment = new PayPalPayment(amount, nativeItems.FirstOrDefault().Currency, "Multiple items", paymentIntent); payment = payment.Items(nativeItems.ToArray()).PaymentDetails(paymentDetails); if (address != null) { ShippingAddress shippingAddress = new ShippingAddress() .RecipientName(address.RecipientName) .Line1(address.Line1) .Line2(address.Line2) .City(address.City) .State(address.State) .PostalCode(address.PostalCode) .CountryCode(address.CountryCode); payment = payment.InvokeProvidedShippingAddress(shippingAddress); } switch (_xfconfig.ShippingAddressOption) { case Abstractions.Enum.ShippingAddressOption.Both: case Abstractions.Enum.ShippingAddressOption.PayPal: payment = payment.EnablePayPalShippingAddressesRetrieval(true); break; default: payment = payment.EnablePayPalShippingAddressesRetrieval(false); break; } Intent intent = new Intent(Context, typeof(PaymentActivity)); intent.PutExtra(PayPalService.ExtraPaypalConfiguration, config); intent.PutExtra(PaymentActivity.ExtraPayment, payment); (Context as Activity).StartActivityForResult(intent, REQUEST_CODE_PAYMENT); }
async void realizarPago_Clicked(object sender, System.EventArgs e) { if (Application.Current.Properties.ContainsKey("idPedido")) { Device.BeginInvokeOnMainThread(async() => { if (string.IsNullOrEmpty(txtCalle.Text)) { await DisplayAlert("Información", "Ingrese su calle", "Aceptar"); txtCalle.Focus(); return; } if (string.IsNullOrEmpty(txtColonia.Text)) { await DisplayAlert("Información", "Ingrese su colonia", "Aceptar"); txtColonia.Focus(); return; } if (string.IsNullOrEmpty(txtCiudad.Text)) { await DisplayAlert("Información", "Ingrese su ciudad", "Aceptar"); txtCiudad.Focus(); return; } if (string.IsNullOrEmpty(txtEstado.Text)) { await DisplayAlert("Información", "Ingrese su estado", "Aceptar"); txtEstado.Focus(); return; } if (string.IsNullOrEmpty(txtCP.Text)) { await DisplayAlert("Información", "Ingrese su código postal", "Aceptar"); txtCP.Focus(); return; } waitActivityIndicador.IsRunning = true; //Pone el de cargando btnContinuarPago.IsEnabled = false; //Deshabilita el boton RestClient cliente = new RestClient(); var pedidos = await cliente.GetPedidos <Pedidos>("http://148.240.202.160:88/TiendaUAQWebservice/api/tbldetallespedidos/pedido/usuario/" + Application.Current.Properties["idUsuarioTienda"].ToString()); if (pedidos != null) { if (pedidos.idPedido != 0) { Application.Current.Properties["idPedido"] = pedidos.idPedido; int totalItems = pedidos.detalle.Count; int costoEnvio = 0; int iva = 0; var i = 0; double total = 0; var procedePago = true; string mensajeError = ""; PayPalItem[] items = new PayPalItem[totalItems]; string cuerpoCorreo = "<html><body style='font-family: Arial, Helvetica, sans-serif;'><h2 style='color:#EC7063;'>Tienda UAQ</h2><p>Detalles de la compra: </p><table border='1' bordercolor='gray' style='border-collapse: collapse;' cellpadding='5'><thead><th style='color:#EC7063;'>Producto</th><th style='color:#EC7063;'>Precio</th></thead><tbody>"; foreach (var producto in pedidos.detalle) { if (producto.existencias == 0) {//Si ya no hay productos procedePago = false; mensajeError = "Existen productos agotados, verifique el carrito e intente nuevamente."; } else if (producto.cantidad > producto.existencias) {//Si la cantidad de productos en el carrito es mayor al de existencias procedePago = false; mensajeError = "Existen productos que no se cubre el total de pedidos al de existencias, verifique el carrito e intente nuevamente."; } else { total = total + producto.precio; //items[i] = new PayPalItem(producto.nombre, (uint)producto.cantidad, new Decimal(0.01), "MXN", producto.idProducto.ToString()); items[i] = new PayPalItem(producto.nombre, (uint)producto.cantidad, new Decimal(producto.precioUnitario), "MXN", producto.idProducto.ToString()); cuerpoCorreo += "<tr><td>" + producto.nombre + " (Cant. " + producto.cantidad + ")</td><td style='text-align:right'>$" + producto.precio + "</td></tr>"; } i++; } if (procedePago)//si el pago procede { var result = await CrossPayPalManager.Current.Buy( items, new Decimal(costoEnvio), //costo del envio new Decimal(iva), //impuesto o iva new ShippingAddress("Dirección de envío", txtCalle.Text + ", " + txtColonia.Text, "", txtCiudad.Text, txtEstado.Text, txtCP.Text, "MX") //Nombre, direccion 1, direccion 2, ciudad, estado, codigo postal, codigo del pais ); if (result.Status == PayPalStatus.Cancelled) { Debug.WriteLine("Cancelled"); await Navigation.PushAsync(new Carrito()); } else if (result.Status == PayPalStatus.Error) { Debug.WriteLine(result.ErrorMessage); btnContinuarPago.IsEnabled = true; //Habilita el boton waitActivityIndicador.IsRunning = false; //Quita el de cargando await DisplayAlert("Error", "Ocurrió un error al realizar el pago. " + result.ErrorMessage, "Aceptar"); } else if (result.Status == PayPalStatus.Successful) { string direccionCompletaEnvio = txtCalle.Text + ", " + txtColonia.Text + ", " + txtCiudad.Text + ", " + txtEstado.Text + ", C.P.: " + txtCP.Text; string referencia = result.ServerResponse.Response.Id; if (referencia != "") { try { var formContent = new FormUrlEncodedContent(new[] { new KeyValuePair <string, string>("idPedido", pedidos.idPedido.ToString()), new KeyValuePair <string, string>("direccion", direccionCompletaEnvio), new KeyValuePair <string, string>("referencia", referencia), new KeyValuePair <string, string>("importe", total.ToString()) }); var myHttpClient = new HttpClient(); var authData = string.Format("{0}:{1}", "tiendaUAQ", "t13nd4U4q"); var authHeaderValue = Convert.ToBase64String(Encoding.UTF8.GetBytes(authData)); myHttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authHeaderValue); var response = await myHttpClient.PostAsync("http://148.240.202.160:88/TiendaUAQWebService/api/tblpedidos/compra", formContent); var json = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { if (Application.Current.Properties.ContainsKey("idPedido")) { Application.Current.Properties.Remove("idPedido");//Primero lo debe eliminar en caso de que existe para que en la validacion si existe pedido lo agregue } cuerpoCorreo += "</tbody><tr><td style='color:#EC7063;'>Importe</td><td style='text-align:right'><b>$" + total + " MXN</b></td></tr></table><br><p>Dirección de envío:</p><p style='color:#EC7063;'>" + direccionCompletaEnvio + "</p><br><p style='color:gray;font-size:11px;'> *Este es un correo automático, no es necesario responder.</p></html>"; Debug.WriteLine(cuerpoCorreo); string nombreUsuario = Application.Current.Properties["nombre"] + " " + Application.Current.Properties["paterno"] + " " + Application.Current.Properties["materno"]; string correoUsuarioX = Application.Current.Properties["usuario"].ToString(); string respuestaCorreo = enviarCorreoCompra(correoUsuarioX, nombreUsuario, cuerpoCorreo); await DisplayAlert("Correcto", "Se realizó el pago correctamente. " + respuestaCorreo, "Aceptar"); //Se debe de actualizar el pedido y cada uno de los artículos se debe disminuir el número de existencias await Navigation.PushAsync(new Carrito()); } else { await DisplayAlert("Error", "No se realizó el pago correctamente el pago, sin embargo se realizó el cobro. Verifique con el administradors", "Aceptar"); } } catch (Exception ex) { Debug.WriteLine("\n Tryyyyyy "); Debug.WriteLine(ex.ToString()); } } else { await DisplayAlert("Error", "No se recibió referencia de pago.", "Aceptar"); } } } else { btnContinuarPago.IsEnabled = true; //Habilita el boton waitActivityIndicador.IsRunning = false; //Quita el de cargando await DisplayAlert("Error", mensajeError, "Aceptar"); } } else { btnContinuarPago.IsEnabled = true; //Habilita el boton waitActivityIndicador.IsRunning = false; //Quita el de cargando await DisplayAlert("Error", "El carrito esta vacío.", "Aceptar"); } } else { await DisplayAlert("Error", "Error de conexión.", "Aceptar"); } }); } else { await DisplayAlert("Error", "No existe pedido en la BD.", "Aceptar"); } }
private string WritePayPalPane(Address BillingAddress) { StringBuilder s = new StringBuilder(""); Customer ThisCustomer = ((AspDotNetStorefrontPrincipal)Context.User).ThisCustomer; s.Append("<body onload='javascript:document.forms.PayPalForm.submit();' >"); if (AppLogic.AppConfigBool("UseLiveTransactions")) { s.Append("<form target='_top' action='" + AppLogic.AppConfig("PayPal.LiveServer") + "' method='post' name='PayPalForm' id='PayPalForm' onsubmit='return (validateForm(this) && PayPalForm_Validator(this))'>\n"); } else { s.Append("<form target='_top' action='" + AppLogic.AppConfig("PayPal.TestServer") + "' method='post' name='PayPalForm' id='PayPalForm' onsubmit='return (validateForm(this) && PayPalForm_Validator(this))'>\n"); } s.Append("<input type='hidden' name='return' value='" + AppLogic.GetStoreHTTPLocation(true) + AppLogic.AppConfig("PayPal.ReturnOKURL") + "'>\n"); s.Append("<input type='hidden' name='cancel_return' value='" + AppLogic.GetStoreHTTPLocation(true) + AppLogic.AppConfig("PayPal.ReturnCancelURL") + "'>\n"); if (AppLogic.AppConfigBool("PayPal.UseInstantNotification")) { s.Append("<input type='hidden' name='notify_url' value='" + AppLogic.GetStoreHTTPLocation(true) + AppLogic.AppConfig("PayPal.NotificationURL") + "?CID=" + ThisCustomer.CustomerID.ToString() + "'>\n"); } s.Append("<input type='hidden' name='cmd' value='_cart'>\n"); s.Append("<input type='hidden' name='upload' value='1'>\n"); s.Append("<input type='hidden' name='bn' value='" + AspDotNetStorefrontGateways.Processors.PayPal.BN + "'>\n"); bool bEBay = AspDotNetStorefrontGateways.Processors.PayPalController.GetFirstAuctionSite(cart.CartItems).Equals("EBAY", StringComparison.InvariantCultureIgnoreCase); bool bAuthOnly = true; if (bEBay || AppLogic.TransactionModeIsAuthCapture() || AppLogic.AppConfigBool("PayPal.ForceCapture")) { bAuthOnly = false; } if (bAuthOnly) { s.Append("<input type='hidden' name='paymentaction' value='authorization'>\n"); } s.Append("<input type='hidden' name='redirect_cmd' value='_xclick'>\n"); s.Append("<input type='hidden' name='business' value='" + AppLogic.AppConfig("PayPal.BusinessID") + "'>\n"); StringBuilder cartItemList = new StringBuilder(""); try { StringBuilder innerBuilder = new StringBuilder(); decimal SubTotalWODiscount = cart.SubTotal(false, false, true, true); decimal SubTotalWDiscount = cart.SubTotal(true, false, true, true); decimal dSavings = SubTotalWODiscount - SubTotalWDiscount; bool hasDiscountAmount = (NetTotal <cart.Total(false) || dSavings> 0.0M); PayPalItemList ppCart = new PayPalItemList(cart, false); for (int i = 0; i < ppCart.Count; i++) { PayPalItem ppItem = ppCart.Item(i); if (!String.IsNullOrEmpty(ppItem.Site)) { innerBuilder.Append("<input type='hidden' name='site_" + (i + 1).ToString() + "' value='" + ppItem.Site + "'>\n"); } if (!String.IsNullOrEmpty(ppItem.ItemNumber)) { innerBuilder.Append("<input type='hidden' name='ai_" + (i + 1).ToString() + "' value='" + ppItem.ItemNumber + "'>\n"); } if (!String.IsNullOrEmpty(ppItem.TransactionID)) { innerBuilder.Append("<input type='hidden' name='at_" + (i + 1).ToString() + "' value='" + ppItem.TransactionID + "'>\n"); } if (!String.IsNullOrEmpty(ppItem.BuyerID)) { innerBuilder.Append("<input type='hidden' name='ab_" + (i + 1).ToString() + "' value='" + ppItem.BuyerID + "'>\n"); } innerBuilder.Append("<input type='hidden' name='item_name_" + (i + 1).ToString() + "' value='" + ppItem.Name + "'>\n"); innerBuilder.Append("<input type='hidden' name='amount_" + (i + 1).ToString() + "' value='" + Localization.CurrencyStringForGatewayWithoutExchangeRate(CommonLogic.IIF(hasDiscountAmount, 0.0M, ppItem.Amount)) + "'>\n"); innerBuilder.Append("<input type='hidden' name='quantity_" + (i + 1).ToString() + "' value='" + ppItem.Quantity.ToString() + "'>\n"); } if (hasDiscountAmount) { innerBuilder.Append("<input type='hidden' name='item_name_" + (ppCart.Count + 1).ToString() + "' value='" + AppLogic.AppConfig("StoreName") + " Purchase'>\n"); innerBuilder.Append("<input type='hidden' name='amount_" + (ppCart.Count + 1).ToString() + "' value='" + Localization.CurrencyStringForGatewayWithoutExchangeRate(NetTotal) + "'>\n"); innerBuilder.Append("<input type='hidden' name='quantity_" + (ppCart.Count + 1).ToString() + "' value='1'>\n"); } else { innerBuilder.Append("<input type='hidden' name='shipping_" + (ppCart.Count).ToString() + "' value='" + Localization.CurrencyStringForGatewayWithoutExchangeRate(ppCart.ShippingAmount) + "'>\n"); innerBuilder.Append("<input type='hidden' name='tax_cart' value='" + Localization.CurrencyStringForGatewayWithoutExchangeRate(ppCart.TaxAmount) + "'>\n"); } cartItemList.Append(innerBuilder.ToString()); innerBuilder = null; } catch { cartItemList.Append("<input type='hidden' name='item_name_1' value='" + AppLogic.AppConfig("StoreName") + " Purchase'>\n"); cartItemList.Append("<input type='hidden' name='amount_1' value='" + Localization.CurrencyStringForGatewayWithoutExchangeRate(NetTotal) + "'>\n"); cartItemList.Append("<input type='hidden' name='quantity_1' value='1'>\n"); } s.Append(cartItemList.ToString()); Address shipto = new Address(); if (ThisCustomer.PrimaryShippingAddressID > 0) { shipto.LoadByCustomer(ThisCustomer.CustomerID, ThisCustomer.PrimaryShippingAddressID, AddressTypes.Shipping); } else { shipto = BillingAddress; } s.Append("<input type='hidden' name='rm' value='2'>\n"); s.Append("<input type='hidden' name='no_note' value='1'>\n"); s.Append("<input type='hidden' name='cs' value='1'>\n"); s.Append("<input type='hidden' name='custom' value='" + ThisCustomer.CustomerID.ToString() + "'>\n"); s.Append("<input type='hidden' name='currency_code' value='" + Localization.StoreCurrency() + "'>\n"); s.Append("<input type='hidden' name='lc' value='" + AppLogic.AppConfig("PayPal.DefaultLocaleCode") + "'>\n"); s.Append("<input type='hidden' name='country' value='" + AppLogic.GetCountryTwoLetterISOCode(shipto.Country) + "'>\n"); if (!AppLogic.AppConfigBool("PayPal.RequireConfirmedAddress")) { s.Append("<input type='hidden' name='address_override' value='1'>\n"); s.Append("<input type='hidden' name='first_name' value='" + shipto.FirstName + "'>\n"); s.Append("<input type='hidden' name='last_name' value='" + shipto.LastName + "'>\n"); s.Append("<input type='hidden' name='address1' value='" + shipto.Address1 + "'>\n"); s.Append("<input type='hidden' name='address2' value='" + shipto.Address2 + "'>\n"); s.Append("<input type='hidden' name='city' value='" + shipto.City + "'>\n"); s.Append("<input type='hidden' name='state' value='" + shipto.State + "'>\n"); s.Append("<input type='hidden' name='zip' value='" + shipto.Zip + "'>\n"); } try { String ph = AppLogic.MakeProperPhoneFormat(shipto.Phone); Match m = Regex.Match(ph, @"^(?:(?:[\+]?(?<CountryCode>[\d]{1,3})(?:[ ]+|[\-.]))?[(]?(?<AreaCode>[\d]{3})[\-/)]?(?:[ ]+)?)?(?<Exchange>[a-zA-Z2-9]{3,})[ ]*[ \-.](?<Number>[a-zA-Z0-9]{4,})(?:(?:[ ]+|[xX]|(i:ext[\.]?)){1,2}(?<Ext>[\d]{1,5}))?$", RegexOptions.Compiled); string sCountry = m.Groups["ContryCode"].Value.Trim(); string sArea = m.Groups["AreaCode"].Value.Trim(); string sExchange = m.Groups["Exchange"].Value.Trim(); string sNumber = m.Groups["Number"].Value.Trim(); int cc = 0; if (sArea.Length > 0 && sExchange.Length > 0 && sNumber.Length > 0) { if (sCountry.Length > 0) { cc = int.Parse(sCountry); } if (cc != 0) { s.Append("<input type='hidden' name='night_phone_a' value='" + sCountry + "'>\n"); s.Append("<input type='hidden' name='night_phone_b' value='" + sArea + sExchange + sNumber + "'>\n"); s.Append("<input type='hidden' name='day_phone_a' value='" + sCountry + "'>\n"); s.Append("<input type='hidden' name='day_phone_b' value='" + sArea + sExchange + sNumber + "'>\n"); } else { s.Append("<input type='hidden' name='night_phone_a' value='" + sArea + "'>\n"); s.Append("<input type='hidden' name='night_phone_b' value='" + sExchange + "'>\n"); s.Append("<input type='hidden' name='night_phone_c' value='" + sNumber + "'>\n"); s.Append("<input type='hidden' name='day_phone_a' value='" + sArea + "'>\n"); s.Append("<input type='hidden' name='day_phone_b' value='" + sExchange + "'>\n"); s.Append("<input type='hidden' name='day_phone_c' value='" + sNumber + "'>\n"); } } } catch { } s.Append("</form>"); s.Append("</body>"); return(s.ToString()); }
//public string localHostUrl = "http://192.168.0.174:8080/PSM2017/"; public ScanPage() { zxings = new ZXingScannerView { HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, AutomationId = "zxingScannerView", IsScanning = true }; zxings.OnScanResult += (result) => Device.BeginInvokeOnMainThread(async() => { zxings.IsAnalyzing = false; string barcode = result.Text; if (App.Database.GetProducts().Count < 10) { string data = ""; string postData = "barcode=" + barcode; string url = localHostUrl + "dbGetProduct.php"; WebService searchProduct = new WebService(); data = searchProduct.postService(postData, url); if (data.Contains("{")) { Product product = JsonConvert.DeserializeObject <Product>(data); //Product product = products.Find(x => x.barcode == Int32.Parse(barcode)); App.Database.AddProduct(product); await DisplayAlert("Item Added", product.name + " added into list.", "OK"); } else { XFToast.LongMessage(data); } } else { await DisplayAlert("Alert!", "Your cart has 10 items. The cart could only hold up to 10 items. " + "Please pay for the item(s) or delete item!!!", "OK"); } // Stop analysis until we navigate away so we don't keep reading barcodes zxings.IsAnalyzing = true; // Show an alert //await DisplayAlert("Scanned Barcode", result.Text, "OK"); // Navigate away //await Navigation.PopAsync(); }); var scanOverlay = new RelativeLayout { HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand }; Xamarin.Forms.Label text = new Xamarin.Forms.Label { Text = "Hold your phone up to the barcode", VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center, TextColor = Color.White }; Xamarin.Forms.Label text2 = new Xamarin.Forms.Label { Text = "Scanning will happen automatically", VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center, TextColor = Color.White }; BoxView redLine = new BoxView { BackgroundColor = Color.Red, Opacity = 0.6 }; BoxView boxView = new BoxView { BackgroundColor = Color.Black, Opacity = 0.7 }; BoxView boxView2 = new BoxView { BackgroundColor = Color.Black, Opacity = 0.7 }; BoxView boxView3 = new BoxView { BackgroundColor = Color.Black, Opacity = 0.7 }; BoxView boxView4 = new BoxView { BackgroundColor = Color.Black, Opacity = 0.7 }; scanOverlay.Children.Add(boxView, Constraint.RelativeToParent((parent) => { return(parent.X); }), Constraint.RelativeToParent((parent) => { return(parent.Y); }), Constraint.RelativeToParent((parent) => { return(parent.Width * 0.1); }), Constraint.RelativeToParent((parent) => { return(parent.Height); }) ); scanOverlay.Children.Add(boxView2, Constraint.RelativeToParent((parent) => { return(parent.Width * 0.9); }), Constraint.RelativeToParent((parent) => { return(parent.Y); }), Constraint.RelativeToParent((parent) => { return(parent.Width * 0.1); }), Constraint.RelativeToParent((parent) => { return(parent.Height); }) ); scanOverlay.Children.Add(boxView3, Constraint.RelativeToParent((parent) => { return(parent.Width * 0.1); }), Constraint.RelativeToParent((parent) => { return(parent.Y); }), Constraint.RelativeToParent((parent) => { return(parent.Width * 0.8); }), Constraint.RelativeToParent((parent) => { return(parent.Height * 0.2); }) ); scanOverlay.Children.Add(boxView4, Constraint.RelativeToParent((parent) => { return(parent.Width * 0.1); }), Constraint.RelativeToParent((parent) => { return(parent.Height * 0.6); }), Constraint.RelativeToParent((parent) => { return(parent.Width * 0.8); }), Constraint.RelativeToParent((parent) => { return(parent.Height * 0.4); }) ); scanOverlay.Children.Add(redLine, Constraint.RelativeToParent((parent) => { return(parent.Width * 0.1); }), Constraint.RelativeToParent((parent) => { return(parent.Height * 0.4); }), Constraint.RelativeToParent((parent) => { return(parent.Width * 0.8); }), Constraint.RelativeToParent((parent) => { return(3); }) ); scanOverlay.Children.Add(text, Constraint.RelativeToParent((parent) => { return(parent.Width * 0.2); }), Constraint.RelativeToParent((parent) => { return(parent.Height * 0.1); }) ); scanOverlay.Children.Add(text2, Constraint.RelativeToParent((parent) => { return(parent.Width * 0.2); }), Constraint.RelativeToParent((parent) => { return(parent.Height * 0.8); }) ); defaultOverlay = new ZXingDefaultOverlay { TopText = "Hold your phone up to the barcode", BottomText = "Scanning will happen automatically", //ShowFlashButton = true, AutomationId = "zxingDefaultOverlay", }; defaultOverlay.BindingContext = defaultOverlay; var customOverlay = new RelativeLayout { HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand }; var torchFAB = new FAB.Forms.FloatingActionButton(); torchFAB.Source = "flashlight_icon.png"; torchFAB.NormalColor = Color.FromHex("FFE066"); torchFAB.Size = FAB.Forms.FabSize.Normal; torchFAB.Clicked += (sender, args) => { zxings.ToggleTorch(); }; var listFAB = new FAB.Forms.FloatingActionButton(); listFAB.Source = "shoping_cart.png"; listFAB.NormalColor = Color.FromHex("FFE066"); listFAB.Size = FAB.Forms.FabSize.Normal; listFAB.Clicked += async(sender, args) => { //zxing.IsAnalyzing = false; //XFToast.LongMessage("Hello"); await Navigation.PushAsync(new ListViewProduct()); }; var addFAB = new FAB.Forms.FloatingActionButton(); addFAB.Source = "plus_black_symbol.png"; addFAB.NormalColor = Color.FromHex("FFE066"); addFAB.Size = FAB.Forms.FabSize.Normal; addFAB.Clicked += async(sender, args) => { if (App.Database.GetProducts().Count < 10) { var config = new PromptConfig(); config.Title = "Manual enter product barcode"; config.InputType = InputType.Number; config.OnAction = async(result) => { if (result.Ok) { string barcode = result.Text; string postData = "barcode=" + barcode; string url = localHostUrl + "dbGetProduct.php"; WebService searchProduct = new WebService(); string data = searchProduct.postService(postData, url); if (data.Contains("{")) { Product product = JsonConvert.DeserializeObject <Product>(data); //Product product = products.Find(x => x.barcode == Int32.Parse(barcode)); App.Database.AddProduct(product); await DisplayAlert("Item Added", product.name + " added into list.", "OK"); } else { XFToast.LongMessage(data); } } zxings.IsAnalyzing = true; }; await Task.Run(() => { Device.BeginInvokeOnMainThread(() => { zxings.IsAnalyzing = false; UserDialogs.Instance.Prompt(config); }); }); } else { await DisplayAlert("Alert!", "Your cart has 10 items.The cart could only hold up to 10 items. " + "Please pay for the item(s) or delete item!!!", "OK"); } //App.Database.AddProduct(new Product {Name = "Milo", Price = 20.587, Barcode = 00001 }); }; var checkOutFAB = new FAB.Forms.FloatingActionButton(); checkOutFAB.Source = "cash_register_machine.png"; checkOutFAB.NormalColor = Color.FromHex("FFE066"); checkOutFAB.Size = FAB.Forms.FabSize.Normal; checkOutFAB.Clicked += (sender, args) => { //XFToast.LongMessage("Check out"); var products = App.Database.GetProducts(); if (products.Count > 0) { Task.Run(async() => { PayPalItem[] paypalItems = new PayPalItem[products.Count]; int i = 0; foreach (Product product in products) { PayPalItem paypalItem = new PayPalItem(product.name, 1, Convert.ToDecimal(product.price), "MYR" , product.barcode); paypalItems[i] = paypalItem; i++; } var result = await CrossPayPalManager.Current.Buy(paypalItems, new Decimal(0.0), new Decimal(0.00)); if (result.Status == PayPalStatus.Cancelled) { Debug.WriteLine("Cancelled"); } else if (result.Status == PayPalStatus.Error) { Debug.WriteLine(result.ErrorMessage); } else if (result.Status == PayPalStatus.Successful) { Debug.WriteLine(result.ServerResponse.Response.Id); var jsonArray = JsonConvert.SerializeObject(products); string jsnArray = jsonArray.ToString(); string postData = "receipt=" + jsnArray; string url = localHostUrl + "genReceipt.php"; WebService searchProduct = new WebService(); string data = searchProduct.postService(postData, url); if (data.ToLower().Contains(".pdf")) { Device.BeginInvokeOnMainThread(async() => { await DisplayAlert("Payment Success", "The payment is success!!", "OK"); App.Database.ClearList(); downloadPDF(data); await DisplayAlert("Download Success", "Receipt downloaded", "OK"); }); } } }); } else { DisplayAlert("Alert!", "There are no item in the cart list.", "OK"); } }; var receiptFAB = new FAB.Forms.FloatingActionButton(); receiptFAB.Source = "receiptIcon"; receiptFAB.NormalColor = Color.FromHex("FFE066"); receiptFAB.Size = FAB.Forms.FabSize.Normal; receiptFAB.Clicked += async(sender, args) => { await Navigation.PushAsync(new ListPDF()); }; /* * customOverlay.Children.Add( * torchFAB, * xConstraint: Constraint.RelativeToParent((parent) => { return parent.Width - 48; }), * yConstraint: Constraint.RelativeToParent((parent) => { return 8; }) * ); * * customOverlay.Children.Add( * listFAB, * Constraint.RelativeToView(torchFAB, (Parent, sibling) => { return sibling.X; }), * Constraint.RelativeToView(torchFAB, (Parent, sibling) => { return sibling.Y + 48; }) * ); * customOverlay.Children.Add( * addFAB, * Constraint.RelativeToView(listFAB, (Parent, sibling) => { return sibling.X; }), * Constraint.RelativeToView(listFAB, (Parent, sibling) => { return sibling.Y + 48; }) * ); * customOverlay.Children.Add( * checkOutFAB, * Constraint.RelativeToView(addFAB, (Parent, sibling) => { return sibling.X; }), * Constraint.RelativeToView(addFAB, (Parent, sibling) => { return sibling.Y + 48; }) * ); * customOverlay.Children.Add( * receiptFAB, * Constraint.RelativeToView(checkOutFAB, (Parent, sibling) => { return sibling.X; }), * Constraint.RelativeToView(checkOutFAB, (Parent, sibling) => { return sibling.Y + 48; }) * ); */ customOverlay.Children.Add( torchFAB, xConstraint: Constraint.RelativeToParent((parent) => { return(parent.X + 6); }), yConstraint: Constraint.RelativeToParent((parent) => { return(parent.Height * 0.6 + 24); }) ); customOverlay.Children.Add( listFAB, Constraint.RelativeToView(torchFAB, (Parent, sibling) => { return(sibling.X + 72); }), Constraint.RelativeToView(torchFAB, (Parent, sibling) => { return(sibling.Y); }) ); customOverlay.Children.Add( addFAB, Constraint.RelativeToView(listFAB, (Parent, sibling) => { return(sibling.X + 72); }), Constraint.RelativeToView(listFAB, (Parent, sibling) => { return(sibling.Y); }) ); customOverlay.Children.Add( checkOutFAB, Constraint.RelativeToView(addFAB, (Parent, sibling) => { return(sibling.X + 72); }), Constraint.RelativeToView(addFAB, (Parent, sibling) => { return(sibling.Y); }) ); customOverlay.Children.Add( receiptFAB, Constraint.RelativeToView(checkOutFAB, (Parent, sibling) => { return(sibling.X + 72); }), Constraint.RelativeToView(checkOutFAB, (Parent, sibling) => { return(sibling.Y); }) ); var grid = new Grid { VerticalOptions = LayoutOptions.FillAndExpand, HorizontalOptions = LayoutOptions.FillAndExpand, }; grid.Children.Add(zxings); //grid.Children.Add(defaultOverlay); grid.Children.Add(scanOverlay); grid.Children.Add(customOverlay); Content = grid; }