Example #1
0
        public static Plan CreateBillingPlan(string name, string description, string baseUrl)
        {
            var returnUrl = baseUrl + "/Home/SubscribeSuccess";
            var cancelUrl = baseUrl + "/Home/SubscribeCancel";

            // Plan Details
            var plan = CreatePlanObject("Test Plan", "Plan for Tuts+", returnUrl, cancelUrl,
                                        PlanInterval.Month, 1, (decimal)19.90, trial: true, trialLength: 1, trialPrice: 0);

            // PayPal Authentication tokens
            var apiContext = PayPalConfiguration.GetAPIContext();

            // Create plan
            plan = plan.Create(apiContext);

            // Activate the plan
            var patchRequest = new PatchRequest()
            {
                new Patch()
                {
                    op    = "replace",
                    path  = "/",
                    value = new Plan()
                    {
                        state = "ACTIVE"
                    }
                }
            };

            plan.Update(apiContext, patchRequest);

            return(plan);
        }
Example #2
0
        public static Payment CreatePayment(string baseUrl, string intent)
        {
            // ### Api Context
            // Pass in a `APIContext` object to authenticate
            // the call and to send a unique request id
            // (that ensures idempotency). The SDK generates
            // a request id if you do not pass one explicitly.
            var apiContext = PayPalConfiguration.GetAPIContext();

            // Payment Resource
            var payment = new Payment()
            {
                intent = intent,        // `sale` or `authorize`
                payer  = new Payer()
                {
                    payment_method = "paypal"
                },
                transactions  = GetTransactionsList(),
                redirect_urls = GetReturnUrls(baseUrl, intent)
            };

            // Create a payment using a valid APIContext
            var createdPayment = payment.Create(apiContext);

            return(createdPayment);
        }
Example #3
0
        public static Agreement CreateBillingAgreement(string planId, ShippingAddress shippingAddress,
                                                       string name, string description, DateTime startDate)
        {
            // PayPal Authentication tokens
            var apiContext = PayPalConfiguration.GetAPIContext();

            var agreement = new Agreement()
            {
                name        = name,
                description = description,
                start_date  = startDate.ToString("yyyy-MM-ddTHH:mm:ss") + "Z",
                payer       = new Payer()
                {
                    payment_method = "paypal"
                },
                plan = new Plan()
                {
                    id = planId
                },
                shipping_address = shippingAddress
            };

            var createdAgreement = agreement.Create(apiContext);

            return(createdAgreement);
        }
Example #4
0
        public string GetPayerId(string guid, string paymentId, string token, string PayerID)
        {
            APIContext apiContext     = PayPalConfiguration.GetAPIContext();
            var        executePayment = ExecutePayment(apiContext, PayerID, paymentId);

            return(PayerID);
        }
Example #5
0
		public PayPalManager (Context context, PayPal.Forms.Abstractions.PayPalConfiguration xfconfig)
		{
			Context = context;

			switch (xfconfig.Environment) {
			case PayPal.Forms.Abstractions.Enum.Environment.NoNetwork:
				CONFIG_ENVIRONMENT = PayPalConfiguration.EnvironmentNoNetwork;
				break;
			case PayPal.Forms.Abstractions.Enum.Environment.Production:
				CONFIG_ENVIRONMENT = PayPalConfiguration.EnvironmentProduction;
				break;
			case PayPal.Forms.Abstractions.Enum.Environment.Sandbox:
				CONFIG_ENVIRONMENT = PayPalConfiguration.EnvironmentSandbox;
				break;
			}

			CONFIG_CLIENT_ID = xfconfig.PayPalKey;

			config = new PayPalConfiguration ()
				.Environment (CONFIG_ENVIRONMENT)
				.ClientId (CONFIG_CLIENT_ID)
				.AcceptCreditCards (xfconfig.AcceptCreditCards)
			// The following are only used in PayPalFuturePaymentActivity.
				.MerchantName (xfconfig.MerchantName)
				.MerchantPrivacyPolicyUri (global::Android.Net.Uri.Parse (xfconfig.MerchantPrivacyPolicyUri))
				.MerchantUserAgreementUri (global::Android.Net.Uri.Parse (xfconfig.MerchantUserAgreementUri));

			Intent intent = new Intent (Context, typeof(PayPalService));
			intent.PutExtra (PayPalService.ExtraPaypalConfiguration, config);
			Context.StartService (intent);
		}
        protected override void OnCreate(Bundle bundle)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource   = Resource.Layout.Toolbar;

            base.OnCreate(bundle);

            global::Xamarin.Forms.Forms.Init(this, bundle);


            var config = new PayPalConfiguration(PayPalEnvironment.Sandbox, "AUSqNHjhcdaugdDElFFQHr0GxqWLPgKnfb_TZ-sQhVrS3OaPdOkdax6Pbs22QQKugw3eZtmpSJEgd3yE")
            {
                //If you want to accept credit cards
                AcceptCreditCards = true,
                //Your business name
                MerchantName = "BidOnTask.com",
                //Your privacy policy Url
                MerchantPrivacyPolicyUri = "https://www.example.com/privacy",
                //Your user agreement Url
                MerchantUserAgreementUri = "https://www.example.com/legal",
                // OPTIONAL - ShippingAddressOption (Both, None, PayPal, Provided)
                ShippingAddressOption = ShippingAddressOption.None,
                // OPTIONAL - Language: Default languege for PayPal Plug-In
                Language = "en",
                // OPTIONAL - PhoneCountryCode: Default phone country code for PayPal Plug-In
                PhoneCountryCode = "1",
            };


            Plugin.CurrentActivity.CrossCurrentActivity.Current.Init(this, bundle);
            CrossPayPalManager.Init(config, this);
            Xamarin.FormsMaps.Init(this, bundle);
            LoadApplication(new App(new AndroidInitializer()));
        }
Example #7
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource   = Resource.Layout.Toolbar;

            initFontScale();

            base.OnCreate(savedInstanceState);


            ///For Performance
            Forms.SetFlags("FastRenderers_Experimental");

            AndroidEnvironment.UnhandledExceptionRaiser -= StoreLogger;
            AndroidEnvironment.UnhandledExceptionRaiser += StoreLogger;
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            var config = new PayPalConfiguration(PayPalEnvironment.NoNetwork, "XamPaypalID")
            {
                AcceptCreditCards        = true,
                MerchantName             = "XamPaypal",
                MerchantPrivacyPolicyUri = "https://www.XamPaypal.com/privacy",
                MerchantUserAgreementUri = "https://www.XamPaypal.com/legal",
                ShippingAddressOption    = ShippingAddressOption.Both,
                Language         = "es",
                PhoneCountryCode = "52",
            };

            CrossPayPalManager.Init(config, this);
            LoadApplication(new App(new AndroidInitializer()));
        }
Example #8
0
        public void OnFuturePaymentPurchasePressed(object sender, EventArgs e)
        {
            // Get the Application Correlation ID from the SDK
            var correlationId = PayPalConfiguration.GetApplicationCorrelationId(this);

            Toast.MakeText(ApplicationContext, string.Format("App Correlation ID received from SDK: {0}", correlationId), ToastLength.Long).Show();
        }
Example #9
0
        static PPHelper()
        {
            NSMutableDictionary dict = null;

            //if (AppData.Instance.PaypalConfig.Environment.Contains("live"))
            //{
            //    dict = new NSMutableDictionary
            //    {
            //        {Xamarin.PayPal.iOS.Constants.PayPalEnvironmentProduction, new NSString("clientId")}
            //    };
            //}
            //else
            //{
            dict = new NSMutableDictionary
            {
                {
                    Constants.PayPalEnvironmentSandbox, new NSString("ASI_ZzQqUEU_v5QFwOeMxb2d03doX0qOLxCmtYNbxuNfmpFn_cZaHdJpVP_jiJ_ZAUsEK_jgjr6kIcnL")
                }
            };
            //}

            PayPalMobile.InitializeWithClientIdsForEnvironments(dict);


            Config = new PayPalConfiguration
            {
                AcceptCreditCards           = true,
                MerchantName                = "Stadium",
                MerchantPrivacyPolicyURL    = new NSUrl("https://www.example.com/privacy"),
                MerchantUserAgreementURL    = new NSUrl("https://www.example.com/legal"),
                LanguageOrLocale            = NSLocale.PreferredLanguages[0],
                PayPalShippingAddressOption = PayPalShippingAddressOption.Provided
            };
        }
Example #10
0
        public void CreateAndExecutePayment()
        {
            AppSettingsReader appSettingsReader = new AppSettingsReader();
            string            clientId          = (string)appSettingsReader.GetValue("clientId", typeof(string));
            string            clientSecret      = (string)appSettingsReader.GetValue("clientSecret", typeof(string));
            var apicontext = PayPalConfiguration.GetAPIContext(clientId, clientSecret);

            PaymentController controller = new PaymentController();
            var          guid            = Convert.ToString((new Random()).Next(100000));
            string       baseURI         = "http://localhost:37256/Paypal/PayWithPayPal?guid=" + guid;
            BouquetOrder bouquet         = new BouquetOrder(1, 1, new Bouquet(6, "gardenia", 2.00, 0));
            var          payment         = controller.CreatePayment(apicontext, baseURI, bouquet);

            var context = new Mock.MockHttpContext();

            context.m_request.m_queryString.Add("PayerID", guid);
            context.m_request.m_queryString.Add("guid", guid);
            context.Session.Add(guid, payment.id);

            controller.ControllerContext = new ControllerContext {
                HttpContext = context, RouteData = new RouteData()
            };
            var result = controller.ExecutePayment(apicontext, guid, payment.id);

            Assert.IsNotNull(apicontext, "PayPal API context is null");
            Assert.IsNotNull(payment.id, "Fail to create payment");
            //must be failed because the data are fake.
            Assert.IsTrue(result.state.ToLower() != "approved", result.state.ToLower());
        }
Example #11
0
        public ActionResult PaymentWithPayPal()
        {
            if (System.Web.HttpContext.Current.Request.Cookies["UserEMail"] != null)
            {
                APIContext apiContext = PayPalConfiguration.GetAPIContext();
                try
                {
                    //string payerId = Request.Cookies["UserID"].Value;
                    string payerId = Request.Params["PayerID"];
                    if (string.IsNullOrEmpty(payerId))
                    {
                        string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/Store/PaymentWithPayPal?";
                        //string baseURI = "http://localhost:5696/Store/ShoppingCart/PaymentWithPayPal?";
                        var guid           = Convert.ToString((new Random()).Next(100000));
                        var createdPayment = CreatePayment(apiContext, baseURI + "guid=" + guid);

                        var    links             = createdPayment.links.GetEnumerator();
                        string paypalRedirectUrl = string.Empty;

                        while (links.MoveNext())
                        {
                            Links link = links.Current;
                            if (link.rel.ToLower().Trim().Equals("approval_url"))
                            {
                                paypalRedirectUrl = link.href;
                            }
                        }
                        Session.Add(guid, createdPayment.id);
                        return(Redirect(paypalRedirectUrl));
                    }
                    else
                    {
                        var guid            = Request.Params["guid"];
                        var executedPayment = ExecutePayment(apiContext, payerId, Session[guid] as string);
                        if (executedPayment.state.ToLower() != "approved")
                        {
                            return(View("Failure"));
                        }
                    }
                }
                catch (Exception)
                {
                    return(View("Failure"));
                }


                CreateOrder();

                Session["cart"]  = null;
                Session["count"] = null;


                return(View("Success"));
            }

            ViewBag.Message = "U moet ingelogd zijn om de producten te kunnen afrekenen.";
            return(View("ShoppingCart"));
        }
Example #12
0
 static PPHelper()
 {
     Config = new PayPalConfiguration()
              .Environment("sandbox")
              .ClientId("ASI_ZzQqUEU_v5QFwOeMxb2d03doX0qOLxCmtYNbxuNfmpFn_cZaHdJpVP_jiJ_ZAUsEK_jgjr6kIcnL")
              .AcceptCreditCards(true)
              .MerchantName("Stadium")
              .MerchantPrivacyPolicyUri(Android.Net.Uri.Parse("https://www.example.com/privacy"))
              .MerchantUserAgreementUri(Android.Net.Uri.Parse("https://www.example.com/legal"));
 }
Example #13
0
        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);
        }
Example #14
0
        public static void ExecuteBillingAgreement(string token)
        {
            // PayPal Authentication tokens
            var apiContext = PayPalConfiguration.GetAPIContext();

            var agreement = new Agreement()
            {
                token = token
            };
            var executedAgreement = agreement.Execute(apiContext);
        }
Example #15
0
        public virtual ActionResult ProcessPayPalPayment(CheckoutPage currentPage)
        {
            var currentCart = _orderRepository.LoadCart <ICart>(PrincipalInfo.CurrentPrincipal.GetContactId(), _cartService.DefaultCartName);

            if (!currentCart.Forms.Any() || !currentCart.GetFirstForm().Payments.Any())
            {
                throw new PaymentException(PaymentException.ErrorType.ProviderError, "", Utilities.Translate("GenericError"));
            }

            var paymentConfiguration = new PayPalConfiguration();
            var payment = currentCart.Forms.SelectMany(f => f.Payments).FirstOrDefault(c => c.PaymentMethodId.Equals(paymentConfiguration.PaymentMethodId));

            if (payment == null)
            {
                throw new PaymentException(PaymentException.ErrorType.ProviderError, "", Utilities.Translate("PaymentNotSpecified"));
            }


            var orderNumber = payment.Properties[PayPalPaymentGateway.PayPalOrderNumberPropertyName] as string;

            if (string.IsNullOrEmpty(orderNumber))
            {
                throw new PaymentException(PaymentException.ErrorType.ProviderError, "", Utilities.Translate("PaymentNotSpecified"));
            }



            var currentPageUrl = _urlResolver.GetUrl(currentPage.ContentLink);

            // Redirect customer to receipt page
            var cancelUrl = currentPageUrl;// get link to Checkout page

            cancelUrl = UriSupport.AddQueryString(cancelUrl, "success", "false");
            cancelUrl = UriSupport.AddQueryString(cancelUrl, "paymentmethod", "paypal");

            var gateway     = new PayPalPaymentGateway();
            var redirectUrl = cancelUrl;

            if (string.Equals(Request.QueryString["accept"], "true") && Utilities.GetAcceptUrlHashValue(orderNumber) == Request.QueryString["hash"])
            {
                // Try to load purchase order and return redirect based on viewmodel and purchaseorder.
                // this is not working with serializeable cart, since properties for OrderNumber is not persisted from gateway. Properties are empty for IPayment when getting here.
                var acceptUrl = currentPageUrl + "/FinishPaypalTransaction";
                redirectUrl = gateway.ProcessSuccessfulTransaction(currentCart, payment, acceptUrl, cancelUrl);
            }
            else if (string.Equals(Request.QueryString["accept"], "false") && Utilities.GetCancelUrlHashValue(orderNumber) == Request.QueryString["hash"])
            {
                TempData["Message"] = Utilities.Translate("CancelMessage");
                redirectUrl         = gateway.ProcessUnsuccessfulTransaction(cancelUrl, Utilities.Translate("CancelMessage"));
            }

            return(Redirect(redirectUrl));
        }
Example #16
0
        private bool InitPayPal(string price)
        {
            try
            {
                //PayerID
                string currency      = "USD";
                string paypalClintId = "";
                var    option        = ListUtils.SettingsSiteList;
                if (option != null)
                {
                    currency      = option.PaypalCurrency ?? "USD";
                    paypalClintId = option.PaypalId;
                }

                if (string.IsNullOrEmpty(paypalClintId))
                {
                    return(false);
                }

                PayPalConfig = new PayPalConfiguration()
                               .ClientId(paypalClintId)
                               .LanguageOrLocale(AppSettings.Lang)
                               .MerchantName(AppSettings.ApplicationName)
                               .MerchantPrivacyPolicyUri(Android.Net.Uri.Parse(Client.WebsiteUrl + "/terms/privacy-policy"));

                switch (ListUtils.SettingsSiteList?.PaypalMode)
                {
                case "sandbox":
                    PayPalConfig.Environment(PayPalConfiguration.EnvironmentSandbox);
                    break;

                case "live":
                    PayPalConfig.Environment(PayPalConfiguration.EnvironmentProduction);
                    break;

                default:
                    PayPalConfig.Environment(PayPalConfiguration.EnvironmentProduction);
                    break;
                }

                PayPalPayment = new PayPalPayment(new BigDecimal(price), currency, "Pay the card", PayPalPayment.PaymentIntentSale);

                IntentService = new Intent(ActivityContext, typeof(PayPalService));
                IntentService.PutExtra(PayPalService.ExtraPaypalConfiguration, PayPalConfig);
                ActivityContext.StartService(IntentService);
                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(false);
            }
        }
Example #17
0
        // GET: Payment
        public ActionResult PaymantWithPayPal()
        {
            APIContext apiContext = PayPalConfiguration.GetAPIContext();

            try
            {
                string payerId = Request.Params["PayerID"];

                if (string.IsNullOrEmpty(payerId))
                {
                    string baseUri = Request.Url.Scheme + "://" + Request.Url.Authority +
                                     "/Payment/PaymentAndOrderInfo?";
                    var guid = Convert.ToString((new Random().Next(1000000)));
                    //var GUID = Guid.NewGuid();
                    var createPayment = this.CreatePayment(apiContext, baseUri + "guid=" + guid);
                    var links         = createPayment.links.GetEnumerator();

                    string payPalRedirectUrl = null;

                    while (links.MoveNext())
                    {
                        Links lnk = links.Current;
                        if (lnk.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            payPalRedirectUrl = lnk.href;
                        }
                    }

                    // saving the paymentID in the key guid
                    Session.Add(guid, createPayment.id);
                    return(Redirect(payPalRedirectUrl));
                }

                else
                {
                    var guid          = Request.Params["guid"];
                    var excutePayment = ExecutePayment(apiContext, payerId, Session[guid] as string);

                    if (excutePayment.ToString().ToLower() != "approved")
                    {
                        return(View("FalureView"));
                    }
                }
            }
            catch (Exception)
            {
                return(View("FalureView"));
            }


            return(View("SuccessView"));
        }
Example #18
0
        public void FuturePaymentPurchase()
        {
            // Get the Client Metadata ID from the SDK
            String metadataId = PayPalConfiguration.GetClientMetadataId(Context);

            System.Diagnostics.Debug.WriteLine("Client Metadata ID: " + metadataId);

            // TODO: Send metadataId and transaction details to your server for processing with
            // PayPal...
            Toast.MakeText(
                Context.ApplicationContext, "Client Metadata Id received from SDK", ToastLength.Long)
            .Show();
        }
        private void InitPayPal(string price, string payType, string credits, string id)
        {
            try
            {
                Price = price; PayType = payType; Credits = credits; Id = id;

                //PayerID
                string currency      = "USD";
                string paypalClintId = "";
                var    option        = ListUtils.SettingsSiteList.FirstOrDefault();
                if (option != null)
                {
                    currency      = option?.Currency ?? "USD";
                    paypalClintId = option?.PaypalId;
                }

                PayPalConfig = new PayPalConfiguration()
                               .ClientId(paypalClintId)
                               .LanguageOrLocale(AppSettings.Lang)
                               .MerchantName(AppSettings.ApplicationName)
                               .MerchantPrivacyPolicyUri(Android.Net.Uri.Parse(Client.WebsiteUrl + "/terms/privacy-policy"));

                if (option != null)
                {
                    switch (option.PaypalMode)
                    {
                    case "sandbox":
                        PayPalConfig.Environment(PayPalConfiguration.EnvironmentSandbox);
                        break;

                    case "live":
                        PayPalConfig.Environment(PayPalConfiguration.EnvironmentProduction);
                        break;

                    default:
                        PayPalConfig.Environment(PayPalConfiguration.EnvironmentProduction);
                        break;
                    }
                }

                PayPalPayment = new PayPalPayment(new BigDecimal(price), currency, "Pay the card", PayPalPayment.PaymentIntentSale);

                IntentService = new Intent(ActivityContext, typeof(PayPalService));
                IntentService.PutExtra(PayPalService.ExtraPaypalConfiguration, PayPalConfig);
                ActivityContext.StartService(IntentService);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Example #20
0
        public static void CancelBillingAgreement(string agreementId)
        {
            var apiContext = PayPalConfiguration.GetAPIContext();

            var agreement = new Agreement()
            {
                id = agreementId
            };

            agreement.Cancel(apiContext, new AgreementStateDescriptor()
            {
                note = "Cancelling the agreement"
            });
        }
Example #21
0
        public static void ReactivateBillingAgreement(string agreementId)
        {
            var apiContext = PayPalConfiguration.GetAPIContext();

            var agreement = new Agreement()
            {
                id = agreementId
            };

            agreement.ReActivate(apiContext, new AgreementStateDescriptor()
            {
                note = "Reactivating the agreement"
            });
        }
Example #22
0
        /// <summary>
        /// Setup the PayPal API caller service, use the profile setting with pre-configured parameters.
        /// </summary>
        /// <param name="payPalConfiguration">The PayPal payment configuration.</param>
        public static PayPalAPIInterfaceServiceService GetPayPalApiCallerServices(PayPalConfiguration payPalConfiguration)
        {
            var configMap = new Dictionary <string, string>
            {
                { "mode", payPalConfiguration.SandBox == "1" ? "sandbox" : "live" },
                { "account1.apiUsername", payPalConfiguration.User },
                { "account1.apiPassword", payPalConfiguration.Password },
                { "account1.apiSignature", payPalConfiguration.ApiSignature }
            };

            // Signature Credential

            return(new PayPalAPIInterfaceServiceService(configMap));
        }
Example #23
0
        /// <summary>
        /// Buy a product
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        /// <param name="price"></param>
        /// <param name="shipping"></param>
        /// <param name="tax"></param>
        /// <returns></returns>
        public ActionResult CreateOrder(int id, string name, double price, double shipping, double tax)
        {
            var        bouquet    = new Bouquet(id, name, price, shipping);
            var        order      = new BouquetOrder(1, tax, bouquet);
            APIContext apiContext = PayPalConfiguration.GetAPIContext();

            if (apiContext == null)
            {
                var error = new ErrorMessage();
                error.Message = "Configuration error";
                return(View("FailureView", error));
            }
            return(Payment(apiContext, order));
        }
Example #24
0
        //GET: Payment
        public ActionResult PaymentWithPaypal()
        {
            APIContext ApiContext = PayPalConfiguration.GetAPIContext();

            try
            {
                string PayerId = Request.Params["PayerID"];
                if (string.IsNullOrEmpty(PayerId))
                {
                    string baseUri = Request.Url.Scheme + "://" + Request.Url.Authority +
                                     "/Payment/PaymentWithPaypal?";
                    var    guid              = Convert.ToString((new Random()).Next(100000000));
                    var    createPayment     = CreatePayment(ApiContext, baseUri + "guid=" + guid);
                    var    links             = createPayment.links.GetEnumerator();
                    string paypalRedirectUrl = null;

                    while (links.MoveNext())
                    {
                        Links lnk = links.Current;
                        if (lnk.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            paypalRedirectUrl = lnk.href;
                        }
                    }
                    Session.Add(guid, createPayment.id);
                    return(Redirect(paypalRedirectUrl));
                }
                else
                {
                    var guid           = Request.Params["guid"];
                    var executePayment = ExecutePayment(ApiContext, PayerId, Session[guid] as string);

                    if (executePayment.state.ToLower() != "approved")
                    {
                        Session.Remove("Cart");
                        return(View("failureView"));
                    }
                }
            }
            //for better debugging exception sending directly to failure View
            catch (Exception e)
            {
                Session.Remove("Cart");
                return(View("failureView", e));
            }

            Session.Remove("Cart");
            return(View("successView"));
        }
        public ActionResult PaymentWithPayPal(string Cancel = null)
        {
            APIContext apiContext = PayPalConfiguration.GetAPIContext();

            try
            {
                string payerID = Request.Params["PayerID"];

                if (string.IsNullOrEmpty(payerID))
                {
                    string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/Payment/PaymentWithPayPal?";
                    var    guid    = Convert.ToString((new Random()).Next(100000));
                    Console.WriteLine(baseURI);
                    Console.WriteLine(guid);
                    var    createdPayment    = this.CreatePayment(apiContext, baseURI + "guid=" + guid);
                    var    links             = createdPayment.links.GetEnumerator();
                    string paypalRedirectURL = null;

                    while (links.MoveNext())
                    {
                        Links link = links.Current;

                        if (link.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            paypalRedirectURL = link.href;
                        }
                    }
                    Session.Add(guid, createdPayment.id);
                    return(Redirect(paypalRedirectURL));
                }
                else
                {
                    var guid            = Request.Params["guid"];
                    var executedPayment = ExecutePayment(apiContext, payerID, Session[guid] as string);
                    if (executedPayment.state.ToLower() != "approved")
                    {
                        return(View("Failure"));
                    }
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine("Exception: ", exception);
                return(View("Failure"));
            }

            Session.Clear();
            return(View("Success"));
        }
Example #26
0
        // GET: Payment
        public ActionResult PaymentWithPaypal()
        {
            APIContext apicontext = PayPalConfiguration.GetAPIContext();

            try
            {
                string PayerID = Request.Params["PayerID"];

                if (string.IsNullOrEmpty(PayerID))
                {
                    string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "PaymentWithPaypal/PaymentWithPaypal?";

                    var Guid = Convert.ToString((new Random()).Next(100000000));

                    var createPayment = this.CreatePayment(apicontext, baseURI + "guid=" + Guid);

                    var links = createPayment.links.GetEnumerator();

                    string paypalRedirect = null;

                    while (links.MoveNext())
                    {
                        Links ink = links.Current;

                        if (ink.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            paypalRedirect = ink.href;
                        }
                    }
                }
                else
                {
                    var guid = Request.Params["guid"];

                    var exectePayment = ExecutePayment(apicontext, PayerID, Session[guid] as string);

                    if (exectePayment.ToString().ToLower() != "approved")
                    {
                        return(View("FailureView"));
                    }
                }
            }
            catch (Exception)
            {
                return(View("FailureView"));
            }

            return(View("SuccessView"));
        }
Example #27
0
        // GET: Payment
        public ActionResult PaymentWithPaypal(string Cancel = null)
        {
            APIContext aPIContext = PayPalConfiguration.GetAPIContext();

            try
            {
                string payerId = Request.Params["PayerId"];
                if (string.IsNullOrEmpty(payerId) && payerId != null)
                {
                    string baseUri = Request.Url.Scheme + "://" + Request.Url.Authority +
                                     "PaymentWithPaypal/PaymentWithPaypal?";

                    var guid          = Convert.ToString((new Random()).Next(1000000000));
                    var createPayment = this.CreatePayment(aPIContext, baseUri + "guid=" + guid);

                    var links = createPayment.links.GetEnumerator();

                    string paypalRedirectURL = null;

                    while (links.MoveNext())
                    {
                        Links link = links.Current;

                        if (link.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            paypalRedirectURL = link.href;
                        }
                    }
                }
                else
                {
                    var guid = Request.Params["guid"];

                    var excecutedPayment = ExecutePayment(aPIContext, payerId, Session[guid] as string);

                    if (excecutedPayment.ToString().ToLower() != "approved")
                    {
                        return(View("PaymentFailurView"));
                    }
                }
            }
            catch (Exception)
            {
                return(View("PaymentFailurView"));
                //throw;
            }

            return(View("PaymentSuccessView"));
        }
Example #28
0
        public PaymentHistory GetPaymentHistory(PayPalObjectInfo objPayPalobject)
        {
            var apiContext     = PayPalConfiguration.GetAPIContext();
            var paymentHistory = new PaymentHistory();

            try
            {
                paymentHistory = Payment.List(apiContext, objPayPalobject.Count, objPayPalobject.StartID, objPayPalobject.StartIndex, objPayPalobject.StartTime, objPayPalobject.EndTime, objPayPalobject.StartDate, objPayPalobject.EndTime, objPayPalobject.PayeeEmail, objPayPalobject.PayeeID, objPayPalobject.SortBy, objPayPalobject.SortOrder);
            }
            catch (PaymentsException ex)
            {
                throw new Exception("Sorry there is an error getting the payment history. " + ex.Response);
            }
            return(paymentHistory);
        }
        protected override void OnElementChanged(ElementChangedEventArgs<Page> e)
        {
            base.OnElementChanged (e);

            if (e.OldElement != null) {
                homePage = e.NewElement as HomePage;
                homePage.BuyAnItem.Clicked -= OnBuyAnItem;
            }
            if (e.NewElement is HomePage) {
                homePage = e.NewElement as HomePage;
                homePage.BuyAnItem.Clicked += OnBuyAnItem;
                config = new PayPalConfiguration ();
                config.ClientId (AppConfig.kPayPalClientId);
            }
        }
Example #30
0
 public void StopPayPalService()
 {
     try
     {
         if (PayPalConfig != null)
         {
             ActivityContext.StopService(new Intent(ActivityContext, typeof(PayPalService)));
             PayPalConfig = null;
         }
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
     }
 }
Example #31
0
		public PayPalManager (Context context)
		{
			Context = context;
			config = new PayPalConfiguration ()
				.Environment (CONFIG_ENVIRONMENT)
				.ClientId (CONFIG_CLIENT_ID)
			// The following are only used in PayPalFuturePaymentActivity.
				.MerchantName ("Example Merchant")
				.MerchantPrivacyPolicyUri (Android.Net.Uri.Parse ("https://www.example.com/privacy"))
				.MerchantUserAgreementUri (Android.Net.Uri.Parse ("https://www.example.com/legal"));

			Intent intent = new Intent (Context, typeof(PayPalService));
			intent.PutExtra (PayPalService.ExtraPaypalConfiguration, config);
			Context.StartService (intent);
		}
Example #32
0
 public void StopPayPalService()
 {
     try
     {
         if (PayPalConfig != null)
         {
             ActivityContext.StopService(new Intent(ActivityContext, typeof(PayPalService)));
             PayPalConfig = null !;
         }
     }
     catch (Exception e)
     {
         Methods.DisplayReportResultTrack(e);
     }
 }
Example #33
0
        public PayPalManager(Context context)
        {
            Context = context;
            config  = new PayPalConfiguration()
                      .Environment(CONFIG_ENVIRONMENT)
                      .ClientId(CONFIG_CLIENT_ID)
                      // The following are only used in PayPalFuturePaymentActivity.
                      .MerchantName("Example Merchant")
                      .MerchantPrivacyPolicyUri(Android.Net.Uri.Parse("https://www.example.com/privacy"))
                      .MerchantUserAgreementUri(Android.Net.Uri.Parse("https://www.example.com/legal"));

            Intent intent = new Intent(Context, typeof(PayPalService));

            intent.PutExtra(PayPalService.ExtraPaypalConfiguration, config);
            Context.StartService(intent);
        }
Example #34
0
		public PayPalManager(PayPal.Forms.Abstractions.PayPalConfiguration xfconfig)
		{
			NSString key = null;
			NSString value = new NSString (xfconfig.PayPalKey);
			string env = string.Empty;
			switch (xfconfig.Environment) {
			case PayPal.Forms.Abstractions.Enum.Environment.NoNetwork:
				key = Constants.PayPalEnvironmentNoNetwork;
				env = Constants.PayPalEnvironmentNoNetwork.ToString ();
				break;
				case PayPal.Forms.Abstractions.Enum.Environment.Production:
				key = Constants.PayPalEnvironmentProduction;
				env = Constants.PayPalEnvironmentProduction.ToString ();
				break;
				case PayPal.Forms.Abstractions.Enum.Environment.Sandbox:
				key = Constants.PayPalEnvironmentSandbox;
				env = Constants.PayPalEnvironmentSandbox.ToString ();
				break;
			}

			PayPalMobile.InitializeWithClientIdsForEnvironments (NSDictionary.FromObjectsAndKeys (
				new NSObject[] {
					value,
					value,
					value
				}, new NSObject[] {
					key,
					Constants.PayPalEnvironmentProduction,
					Constants.PayPalEnvironmentSandbox
				}
			));

			Environment = env;

			_payPalConfig = new PayPalConfiguration ();
			AcceptCreditCards = xfconfig.AcceptCreditCards;

			// Set up payPalConfig
			_payPalConfig.MerchantName = xfconfig.MerchantName;
			_payPalConfig.MerchantPrivacyPolicyURL = new NSUrl (xfconfig.MerchantPrivacyPolicyUri);
			_payPalConfig.MerchantUserAgreementURL = new NSUrl (xfconfig.MerchantUserAgreementUri);
			_payPalConfig.LanguageOrLocale = NSLocale.PreferredLanguages [0];
			_payPalConfig.PayPalShippingAddressOption = PayPalShippingAddressOption.PayPal;

			Debug.WriteLine ("PayPal iOS SDK Version: " + PayPalMobile.LibraryVersion);
		}
		public DetailViewController (Part selectedPart)
		{
			part = selectedPart;
			partString = string.Format ("{0} {1} {2}", part.Year, part.Make, part.Model);

			Title = "Part Details";

			paymentDelegate = new PaymentDelegate (part);
			paymentConfiguration = new PayPalConfiguration () {
				AcceptCreditCards = false,
				LanguageOrLocale = "en",
				MerchantName = "Willie's Cycles",
				MerchantUserAgreementURL = new NSUrl (Path.Combine (NSBundle.MainBundle.BundlePath, "Licensure.html"), false),
				MerchantPrivacyPolicyURL = NSUrl.FromString ("https://www.google.com"),
				PayPalShippingAddressOption = PayPalShippingAddressOption.PayPal
			} ;
		}
        public override void ViewDidLoad()
        {
            base.ViewDidLoad ();

            Title = "PayPal iOS Library Demo";

            // Initialize PayPal
            PayPalMobile.WithClientIds(_productionPayPalClientId, _sandboxPayPalClientId);

            _payPalConfig = new PayPalConfiguration
                                    {
                                        AcceptCreditCards = AcceptCreditCards,
                                        LanguageOrLocale = "en",
                                        MerchantName = @"Awesome Shirts, Inc.",
                                        MerchantPrivacyPolicyURL = new NSUrl(@"https://www.paypal.com/webapps/mpp/ua/privacy-full"),
                                        MerchantUserAgreementURL = new NSUrl(@"https://www.paypal.com/webapps/mpp/ua/useragreement-full")
                                    };

            successView.Hidden = true;

            Environment = _environment;
            Debug.WriteLine ("PayPal iOS SDK version: {0}", PayPalMobile.LibraryVersion);
        }
Example #37
0
		/*public void PayPalPaymentDidCancel (PayPalPaymentViewController paymentViewController)
		{
			throw new NotImplementedException ();
		}
		public void PayPalPaymentViewController (PayPalPaymentViewController paymentViewController, PayPalPayment completedPayment)
		{
			throw new NotImplementedException ();
		}*/

		#endregion

		public PayPalManager(string environmentProduction, string environmentSandbox)
		{
			PayPalMobile.InitializeWithClientIdsForEnvironments (NSDictionary.FromObjectsAndKeys (
				new NSObject[] {
					new NSString (environmentProduction),
					new NSString (environmentSandbox)
				}, new NSObject[] {
					Constants.PayPalEnvironmentProduction,
					Constants.PayPalEnvironmentSandbox
				}
			));
			Environment = Constants.PayPalEnvironmentNoNetwork.ToString();
			_payPalConfig = new PayPalConfiguration ();
			AcceptCreditCards = true;
			// Set up payPalConfig
			_payPalConfig.MerchantName = "Awesome Shirts, Inc.";
			_payPalConfig.MerchantPrivacyPolicyURL = new NSUrl ("https://www.paypal.com/webapps/mpp/ua/privacy-full");
			_payPalConfig.MerchantUserAgreementURL = new NSUrl ("https://www.paypal.com/webapps/mpp/ua/useragreement-full");
			_payPalConfig.LanguageOrLocale = NSLocale.PreferredLanguages [0];
			_payPalConfig.PayPalShippingAddressOption = PayPalShippingAddressOption.PayPal;

			Debug.WriteLine ("PayPal iOS SDK Version: " + PayPalMobile.LibraryVersion);
		}