Ejemplo n.º 1
0
        public static string webexperience(string name, string company, string logo)
        {
            var apiContext = PaypalConfiguration.GetAPIContext();
            var profile    = new WebProfile()
            {
                name         = name,
                presentation = new Presentation()
                {
                    brand_name = company,
                    logo_image = logo != null?logo.Replace("http:", "https:") : null
                },
                input_fields = new InputFields()
                {
                    address_override = 1,
                    no_shipping      = 1
                },
                flow_config = new FlowConfig()
                {
                    landing_page_type = "Login",
                    user_action       = "commit"
                },
                temporary = false
            };
            var response = profile.Create(apiContext);

            return(response.id);
        }
        protected override void RunSample()
        {
            // ### 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.
            // See [Configuration.cs](/Source/Configuration.html) to know more about APIContext.
            var apiContext = Configuration.GetAPIContext();

            // Setup the profile we want to create
            var profile = new WebProfile()
            {
                name         = Guid.NewGuid().ToString(),
                presentation = new Presentation()
                {
                    brand_name           = "Sample brand",
                    locale_code          = "US",
                    logo_image           = "https://www.paypal.com/",
                    note_to_seller_label = "Thx",
                    return_url_label     = "Retreat!"
                },
                input_fields = new InputFields()
                {
                    address_override = 1,
                    allow_note       = true,
                    no_shipping      = 0
                },
                flow_config = new FlowConfig()
                {
                    bank_txn_pending_url   = "https://www.paypal.com/",
                    landing_page_type      = "billing",
                    user_action            = "commit",
                    return_uri_http_method = "GET"
                },
                temporary = true
            };

            #region Track Workflow
            //--------------------
            this.flow.AddNewRequest("Create profile", profile);
            //--------------------
            #endregion

            // Create the profile
            var response = profile.Create(apiContext);

            #region Track Workflow
            //--------------------
            this.flow.RecordResponse(response);
            //--------------------
            #endregion

            #region Cleanup
            // Cleanup by deleting the newly-created profile
            var retrievedProfile = WebProfile.Get(apiContext, response.id);
            retrievedProfile.Delete(apiContext);
            #endregion
        }
Ejemplo n.º 3
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var CurrContext  = HttpContext.Current;
            var profile      = new WebProfile();
            var patchRequest = new PatchRequest();

            try
            {
                var apiContext = Configuration.GetAPIContext();

                // Setup the profile we want to create
                profile.name                             = Guid.NewGuid().ToString();
                profile.presentation                     = new Presentation();
                profile.presentation.brand_name          = "Sample brand";
                profile.presentation.locale_code         = "US";
                profile.presentation.logo_image          = "https://www.paypal.com/";
                profile.input_fields                     = new InputFields();
                profile.input_fields.address_override    = 1;
                profile.input_fields.allow_note          = true;
                profile.input_fields.no_shipping         = 0;
                profile.flow_config                      = new FlowConfig();
                profile.flow_config.bank_txn_pending_url = "https://www.paypal.com/";
                profile.flow_config.landing_page_type    = "billing";

                // Create the profile
                var response = profile.Create(apiContext);

                // Create a patch and add it to the PatchRequest object used to
                // perform the partial update on the profile.
                var patch1 = new Patch();
                patch1.op    = "add";
                patch1.path  = "/presentation/brand_name";
                patch1.value = "New brand name";
                patchRequest.Add(patch1);

                var patch2 = new Patch();
                patch2.op   = "remove";
                patch2.path = "/flow_config/landing_page_type";
                patchRequest.Add(patch1);

                // Get the profile object and partially update the profile.
                var retrievedProfile = WebProfile.Get(apiContext, response.id);
                retrievedProfile.PartialUpdate(apiContext, patchRequest);

                CurrContext.Items.Add("ResponseJson", "Experience profile successfully updated.");

                // Delete the newly-created profile
                retrievedProfile.Delete(apiContext);
            }
            catch (Exception ex)
            {
                CurrContext.Items.Add("Error", ex.Message);
            }

            CurrContext.Items.Add("RequestJson", patchRequest.ConvertToJson());

            Server.Transfer("~/Response.aspx");
        }
        /// <summary>
        /// Create the default web experience profiles for this example website
        /// </summary>
        private void SeedWebProfiles(APIContext apiContext)
        {
            var digitalGoods = new WebProfile()
            {
                name         = "DigitalGoods",
                input_fields = new InputFields()
                {
                    no_shipping = 1
                }
            };

            WebProfile.Create(apiContext, digitalGoods);
        }
Ejemplo n.º 5
0
        private void SeedWebProfile(APIContext apiContext)
        {
            var BigGods = new WebProfile()
            {
                name         = "Ninja",
                input_fields = new InputFields()
                {
                    no_shipping = 1
                }
            };

            WebProfile.Create(apiContext, BigGods);
        }
Ejemplo n.º 6
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var CurrContext = HttpContext.Current;
            var profile     = new WebProfile();

            try
            {
                var apiContext = Configuration.GetAPIContext();

                // Setup the profile we want to create
                profile.name                             = Guid.NewGuid().ToString();
                profile.presentation                     = new Presentation();
                profile.presentation.brand_name          = "Sample brand";
                profile.presentation.locale_code         = "US";
                profile.presentation.logo_image          = "https://www.paypal.com/";
                profile.input_fields                     = new InputFields();
                profile.input_fields.address_override    = 1;
                profile.input_fields.allow_note          = true;
                profile.input_fields.no_shipping         = 0;
                profile.flow_config                      = new FlowConfig();
                profile.flow_config.bank_txn_pending_url = "https://www.paypal.com/";
                profile.flow_config.landing_page_type    = "billing";

                // Create the profile
                var response = profile.Create(apiContext);

                // Get the profile using the ID returned from the previous Create() call.
                var retrievedProfile = WebProfile.Get(apiContext, response.id);

                CurrContext.Items.Add("ResponseJson", JObject.Parse(retrievedProfile.ConvertToJson()).ToString(Formatting.Indented));

                // Delete the newly-created profile
                retrievedProfile.Delete(apiContext);
            }
            catch (Exception ex)
            {
                CurrContext.Items.Add("Error", ex.Message);
            }

            Server.Transfer("~/Response.aspx");
        }
        /// <summary>
        /// Creates Web Experience profile using portal branding and payment configuration.
        /// </summary>
        /// <param name="paymentConfig">The Payment configuration.</param>
        /// <param name="brandConfig">The branding configuration.</param>
        /// <param name="countryIso2Code">The locale code used by the web experience profile. Example-US.</param>
        /// <returns>The created web experience profile id.</returns>
        public static string CreateWebExperienceProfile(PaymentConfiguration paymentConfig, BrandingConfiguration brandConfig, string countryIso2Code)
        {
            try
            {
                Dictionary <string, string> configMap = new Dictionary <string, string>();
                configMap.Add("clientId", paymentConfig.ClientId);
                configMap.Add("clientSecret", paymentConfig.ClientSecret);
                configMap.Add("mode", paymentConfig.AccountType);
                configMap.Add("connectionTimeout", "120000");

                string accessToken = new OAuthTokenCredential(configMap).GetAccessToken();
                var    apiContext  = new APIContext(accessToken);
                apiContext.Config = configMap;

                // Pickup logo & brand name from branding configuration.
                // create the web experience profile.
                var profile = new WebProfile
                {
                    name         = Guid.NewGuid().ToString(),
                    presentation = new Presentation
                    {
                        brand_name  = brandConfig.OrganizationName,
                        logo_image  = brandConfig.HeaderImage?.ToString(),
                        locale_code = countryIso2Code
                    },
                    input_fields = new InputFields()
                    {
                        address_override = 1,
                        allow_note       = false,
                        no_shipping      = 1
                    },
                    flow_config = new FlowConfig()
                    {
                        landing_page_type = "billing"
                    }
                };

                var createdProfile = profile.Create(apiContext);

                // Now that new experience profile is created hence delete the older one.
                if (!string.IsNullOrWhiteSpace(paymentConfig.WebExperienceProfileId))
                {
                    try
                    {
                        WebProfile existingWebProfile = WebProfile.Get(apiContext, paymentConfig.WebExperienceProfileId);
                        existingWebProfile.Delete(apiContext);
                    }
                    catch
                    {
                    }
                }

                return(createdProfile.id);
            }
            catch (PayPalException paypalException)
            {
                if (paypalException is IdentityException)
                {
                    // thrown when API Context couldn't be setup.
                    IdentityException identityFailure = paypalException as IdentityException;
                    IdentityError     failureDetails  = identityFailure.Details;
                    if (failureDetails != null && failureDetails.error.ToLower() == "invalid_client")
                    {
                        throw new PartnerDomainException(ErrorCode.PaymentGatewayIdentityFailureDuringConfiguration).AddDetail("ErrorMessage", Resources.PaymentGatewayIdentityFailureDuringConfiguration);
                    }
                }

                // if this is not an identity exception rather some other issue.
                throw new PartnerDomainException(ErrorCode.PaymentGatewayFailure).AddDetail("ErrorMessage", paypalException.Message);
            }
        }
        protected override void RunSample()
        {
            // ### 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.
            // See [Configuration.cs](/Source/Configuration.html) to know more about APIContext.
            var apiContext = Configuration.GetAPIContext();

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

            if (string.IsNullOrEmpty(payerId))
            {
                // Create the web experience profile
                var profile = new WebProfile
                {
                    name         = Guid.NewGuid().ToString(),
                    presentation = new Presentation
                    {
                        brand_name  = "PayPal .NET SDK",
                        locale_code = "US",
                        logo_image  = "https://raw.githubusercontent.com/wiki/paypal/PayPal-NET-SDK/images/homepage.jpg"
                    },
                    input_fields = new InputFields
                    {
                        no_shipping = 1
                    }
                };


                // ^ Ignore workflow code segment
                #region Track Workflow
                this.flow.AddNewRequest("Create new web experience profile (NOTE: This only needs to be done once)", profile);
                #endregion

                var createdProfile = profile.Create(apiContext);


                // ^ Ignore workflow code segment
                #region Track Workflow
                this.flow.RecordResponse(createdProfile);
                #endregion

                // Setup the redirect URI to use. The guid value is used to keep the flow information.
                var baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/PaymentWithPayPal.aspx?";
                var guid    = Convert.ToString((new Random()).Next(100000));
                baseURI += "guid=" + guid + "&webProfileId=" + createdProfile.id;

                // Create the payment
                var payment = new Payment
                {
                    intent = "sale",
                    experience_profile_id = createdProfile.id,
                    payer = new Payer
                    {
                        payment_method = "paypal"
                    },
                    transactions = new List <Transaction>
                    {
                        new Transaction
                        {
                            description = "Ticket information.",
                            item_list   = new ItemList
                            {
                                items = new List <Item>
                                {
                                    new Item
                                    {
                                        name     = "Concert ticket",
                                        currency = "USD",
                                        price    = "20.00",
                                        quantity = "2",
                                        sku      = "ticket_sku"
                                    }
                                }
                            },
                            amount = new Amount
                            {
                                currency = "USD",
                                total    = "45.00",
                                details  = new Details
                                {
                                    tax      = "5.00",
                                    subtotal = "40.00"
                                }
                            }
                        }
                    },
                    redirect_urls = new RedirectUrls
                    {
                        return_url = baseURI + "&return=true",
                        cancel_url = baseURI + "&cancel=true"
                    }
                };


                // ^ Ignore workflow code segment
                #region Track Workflow
                this.flow.AddNewRequest("Create PayPal payment", payment);
                #endregion

                var createdPayment = payment.Create(apiContext);


                // ^ Ignore workflow code segment
                #region Track Workflow
                this.flow.RecordResponse(createdPayment);
                #endregion

                // Use the returned payment's approval URL to redirect the buyer to PayPal and approve the payment.
                var approvalUrl = createdPayment.GetApprovalUrl();

                this.flow.RecordRedirectUrl("Redirect to PayPal to approve the payment...", approvalUrl);
                Session.Add(guid, createdPayment.id);
                Session.Add("flow-" + guid, this.flow);
            }
            else
            {
                var guid         = Request.Params["guid"];
                var webProfileId = Request.Params["webProfileId"];
                var isReturnSet  = Request.Params["return"];

                // ^ Ignore workflow code segment
                #region Track Workflow
                this.flow = Session["flow-" + guid] as RequestFlow;
                this.RegisterSampleRequestFlow();
                this.flow.RecordApproval("PayPal payment approved successfully.");
                #endregion

                if (string.IsNullOrEmpty(isReturnSet))
                {
                    // ^ Ignore workflow code segment
                    #region Track Workflow
                    this.flow.RecordApproval("PayPal payment canceled by buyer.");
                    #endregion
                }
                else
                {
                    // ^ Ignore workflow code segment
                    #region Track Workflow
                    this.flow.RecordApproval("PayPal payment approved successfully.");
                    #endregion

                    // Using the information from the redirect, setup the payment to execute.
                    var paymentId        = Session[guid] as string;
                    var paymentExecution = new PaymentExecution()
                    {
                        payer_id = payerId
                    };
                    var payment = new Payment()
                    {
                        id = paymentId
                    };

                    // ^ Ignore workflow code segment
                    #region Track Workflow
                    this.flow.AddNewRequest("Execute PayPal payment", payment);
                    #endregion

                    // Execute the payment.
                    var executedPayment = payment.Execute(apiContext, paymentExecution);
                    // ^ Ignore workflow code segment
                    #region Track Workflow
                    this.flow.RecordResponse(executedPayment);
                    #endregion
                }

                // Cleanup - Because there's a limit to the number of experience profile IDs you can create,
                // we'll delete the one that was created for this sample.
                WebProfile.Delete(apiContext, webProfileId);

                // For more information, please visit [PayPal Developer REST API Reference](https://developer.paypal.com/docs/api/).
            }
        }
Ejemplo n.º 9
0
        public InitializePayPalCheckoutResponse InitializeWebPayment(Guid accountId, Guid orderId, string baseUri, double?estimatedFare, decimal bookingFees, string clientLanguageCode)
        {
            if (!estimatedFare.HasValue)
            {
                return(new InitializePayPalCheckoutResponse
                {
                    IsSuccessful = false,
                    Message = _resources.Get("CannotCreateOrder_PrepaidNoEstimate", clientLanguageCode)
                });
            }

            var regionName     = _serverSettings.ServerData.PayPalRegionInfoOverride;
            var conversionRate = _serverSettings.ServerData.PayPalConversionRate;

            _logger.LogMessage("PayPal Conversion Rate: {0}", conversionRate);

            // Fare amount
            var fareAmount = Math.Round(Convert.ToDecimal(estimatedFare.Value) * conversionRate, 2);
            var currency   = conversionRate != 1
                ? CurrencyCodes.Main.UnitedStatesDollar
                : _resources.GetCurrencyCode();

            // Need the fare object because tip amount should be calculated on the fare excluding taxes
            var fareObject = FareHelper.GetFareFromAmountInclTax(Convert.ToDouble(fareAmount),
                                                                 _serverSettings.ServerData.VATIsEnabled
                            ? _serverSettings.ServerData.VATPercentage
                            : 0);

            // Tip amount (on fare amount excl. taxes)
            var defaultTipPercentage = _accountDao.FindById(accountId).DefaultTipPercent;
            var tipPercentage        = defaultTipPercentage ?? _serverSettings.ServerData.DefaultTipPercentage;
            var tipAmount            = FareHelper.CalculateTipAmount(fareObject.AmountInclTax, tipPercentage);

            // Booking Fees with conversion rate if necessary
            var bookingFeesAmount = Math.Round(bookingFees * conversionRate, 2);

            // Fare amount with tip and booking fee
            var totalAmount = fareAmount + tipAmount + bookingFeesAmount;

            var redirectUrl = baseUri + string.Format("/{0}/proceed", orderId);

            _logger.LogMessage("PayPal Web redirect URL: {0}", redirectUrl);

            var redirUrls = new RedirectUrls
            {
                cancel_url = redirectUrl + "?cancel=true",
                return_url = redirectUrl
            };

            // Create transaction
            var transactionList = new List <Transaction>
            {
                new Transaction
                {
                    amount = new Amount
                    {
                        currency = currency,
                        total    = totalAmount.ToString("N", CultureInfo.InvariantCulture)
                    },

                    description = string.Format(
                        _resources.Get("PayPalWebPaymentDescription", regionName.HasValue()
                            ? SupportedLanguages.en.ToString()
                            : clientLanguageCode), totalAmount),

                    item_list = new ItemList
                    {
                        items = new List <Item>
                        {
                            new Item
                            {
                                name = _resources.Get("PayPalWebFareItemDescription", regionName.HasValue()
                                        ? SupportedLanguages.en.ToString()
                                        : clientLanguageCode),
                                currency = currency,
                                price    = fareAmount.ToString("N", CultureInfo.InvariantCulture),
                                quantity = "1"
                            },
                            new Item
                            {
                                name = string.Format(_resources.Get("PayPalWebTipItemDescription", regionName.HasValue()
                                        ? SupportedLanguages.en.ToString()
                                        : clientLanguageCode), tipPercentage),
                                currency = currency,
                                price    = tipAmount.ToString("N", CultureInfo.InvariantCulture),
                                quantity = "1"
                            }
                        }
                    }
                }
            };

            if (bookingFeesAmount > 0)
            {
                transactionList.First().item_list.items.Add(new Item
                {
                    name = _resources.Get("PayPalWebBookingFeeItemDescription", regionName.HasValue()
                                        ? SupportedLanguages.en.ToString()
                                        : clientLanguageCode),
                    currency = currency,
                    price    = bookingFeesAmount.ToString("N", CultureInfo.InvariantCulture),
                    quantity = "1"
                });
            }

            // Create web experience profile
            var profile = new WebProfile
            {
                name        = Guid.NewGuid().ToString(),
                flow_config = new FlowConfig
                {
                    landing_page_type = _serverPaymentSettings.PayPalServerSettings.LandingPageType.ToString()
                }
            };

            try
            {
                var webExperienceProfile = profile.Create(GetAPIContext(GetAccessToken()));

                // Create payment
                var payment = new Payment
                {
                    intent = Intents.Sale,
                    payer  = new Payer
                    {
                        payment_method = "paypal"
                    },
                    transactions          = transactionList,
                    redirect_urls         = redirUrls,
                    experience_profile_id = webExperienceProfile.id
                };

                var createdPayment = payment.Create(GetAPIContext(GetAccessToken()));
                var links          = createdPayment.links.GetEnumerator();

                while (links.MoveNext())
                {
                    var link = links.Current;
                    if (link.rel.ToLower().Trim().Equals("approval_url"))
                    {
                        return(new InitializePayPalCheckoutResponse
                        {
                            IsSuccessful = true,
                            PaymentId = createdPayment.id,
                            PayPalCheckoutUrl = link.href       // Links that give the user the option to redirect to PayPal to approve the payment
                        });
                    }
                }

                _logger.LogMessage("Error when creating PayPal Web payment: no approval_urls found");

                // No approval_url found
                return(new InitializePayPalCheckoutResponse
                {
                    IsSuccessful = false,
                    Message = "No approval_url found"
                });
            }
            catch (Exception ex)
            {
                var exceptionMessage = ex.Message;

                var paymentException = ex as PaymentsException;
                if (paymentException != null && paymentException.Details != null)
                {
                    exceptionMessage = paymentException.Details.message;
                }

                _logger.LogMessage("Initialization of PayPal Web Store failed: {0}", exceptionMessage);

                return(new InitializePayPalCheckoutResponse
                {
                    IsSuccessful = false,
                    Message = exceptionMessage
                });
            }
        }
Ejemplo n.º 10
0
        private Payment CreatePayment(APIContext apiContext, List <Product> products, ShippingAddress shippingAddress, string redirectUrl)
        {
            List <ShoppingCartProduct> shoppingCartProducts = new List <ShoppingCartProduct>();

            // If we are a guest on the site use cookies for the shopping cart
            if (!UserService.IsUserConnected(System.Web.HttpContext.Current.User))
            {
                // Get products using the CookieService
                shoppingCartProducts = CookieService.GetShoppingCartProducts(Request.Cookies);

                // Reverse the list so the most recent products are first
                shoppingCartProducts.Reverse();
            }
            else
            {
                ShoppingCart shoppingCart = new ShoppingCartManager().GetShoppingCartByUser(User.Identity.GetUserId());

                shoppingCartProducts = new ShoppingCartProductManager().GetShoppingCartProductByShoppingCartId(shoppingCart.ShoppingCartId);
            }



            //shippingAddress.country_code = "US";
            shippingAddress.country_code = "CA";
            string currency = CookieService.GetCurrency(Request.Cookies);
            //shippingAddress.country_code = CookieService.GetCountryCode(Request.Cookies);

            var items = new ItemList()
            {
                items = new List <Item>(),
                //shipping_address = new ShippingAddress()
                //{
                //    recipient_name = "john ros",
                //    line1 = "111 First Street",
                //    city = "Saratoga",
                //    state = "US",
                //    postal_code = "95070",
                //    country_code = "US",
                //    phone = "819 4443333"
                //}
                shipping_address = shippingAddress
            };

            foreach (ShoppingCartProduct scp in shoppingCartProducts)
            {
                items.items.Add(new Item()
                {
                    name     = scp.Product.Name,
                    currency = currency,//"CAD",
                    //price = "0",
                    price    = PriceService.GetPrice(scp, currency).ToString(),
                    quantity = scp.Quantity.ToString(),
                    sku      = scp.Product.ProductId.ToString() + "S" + scp.Size,
                });
            }
            //items.items.FirstOrDefault().price = "0.60";

            // FOR TESTING
            //items.items.Add(new Item()
            //{
            //    name = "Name-Test",
            //    currency = "CAD",
            //    price = 1.ToString(),
            //    quantity = 1.ToString(),
            //    sku = "sku",
            //});

            var payer = new Payer
            {
                payment_method = "paypal"
            };

            // Do the configuration RedirectURLs here with redirectURLs object
            RedirectUrls redirUrls = new RedirectUrls()
            {
                cancel_url = redirectUrl,
                return_url = redirectUrl
            };


            // clean this
            string postal_code = shippingAddress.postal_code.ToUpper().Replace(" ", "");
            double shipping    = new CanadaPost.CanadaPostRates().GetRates(postal_code, ShippingService.GetShippingTypeByPostalCode(postal_code));
            //double shipping = 0;

            // Create details object
            Details details = new Details()
            {
                //tax = "0",
                shipping = shipping.ToString(),
                //shipping = "1",
                //subtotal = "0.60",
                subtotal = ShoppingCartService.GetSubTotal(shoppingCartProducts, currency).ToString(),
            };

            // Create amount object
            Amount amount = new Amount()
            {
                currency = currency,//"CAD",
                total    = /*(Convert.ToDouble(details.tax) + */ (Convert.ToDouble(details.shipping) + Convert.ToDouble(details.subtotal)).ToString(),
                details  = details
            };

            // Create transaction
            List <Transaction> transactions = new List <Transaction>
            {
                new Transaction()
                {
                    description    = "Auralta Clothing Order",
                    invoice_number = Convert.ToString((new Random()).Next(100000)),
                    amount         = amount,
                    item_list      = items
                }
            };

            // Create the web experience profile
            var profile = new WebProfile()
            {
                name         = Guid.NewGuid().ToString(),
                presentation = new Presentation()
                {
                    brand_name  = "Auralta Clothing",
                    locale_code = CookieService.GetCountryCode(Request.Cookies),//"CA",
                    //logo_image = "https://www.paypal.com/",
                    note_to_seller_label = "Thank you for doing business with Auralta Clothing",
                    return_url_label     = "See you soon"
                },

                input_fields = new InputFields()
                {
                    address_override = 1,
                    allow_note       = true,
                    no_shipping      = 1
                },


                temporary = true
            };

            var createdProfile = profile.Create(apiContext);

            payment = new Payment()
            {
                intent        = "sale",
                payer         = payer,
                transactions  = transactions,
                redirect_urls = redirUrls,

                // TODO: this id is permenant so hard code it
                experience_profile_id = createdProfile.id,
            };

            return(payment.Create(apiContext));
        }
Ejemplo n.º 11
0
        protected override void RunSample()
        {
            // ### 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.
            // See [Configuration.cs](/Source/Configuration.html) to know more about APIContext.
            var apiContext = Configuration.GetAPIContext();

            // Setup the profile we want to create
            var profile = new WebProfile()
            {
                name         = Guid.NewGuid().ToString(),
                presentation = new Presentation()
                {
                    brand_name  = "Sample brand",
                    locale_code = "US",
                    logo_image  = "https://www.paypal.com/"
                },
                input_fields = new InputFields()
                {
                    address_override = 1,
                    allow_note       = true,
                    no_shipping      = 0
                },
                flow_config = new FlowConfig()
                {
                    bank_txn_pending_url = "https://www.paypal.com/",
                    landing_page_type    = "billing"
                }
            };

            #region Track Workflow
            //--------------------
            this.flow.AddNewRequest("Create profile", profile);
            //--------------------
            #endregion

            // Create the profile
            var response = profile.Create(apiContext);

            #region Track Workflow
            //--------------------
            this.flow.RecordResponse(response);
            //--------------------
            #endregion

            // Create a patch and add it to the PatchRequest object used to
            // perform the partial update on the profile.
            var patchRequest = new PatchRequest()
            {
                new Patch()
                {
                    op    = "add",
                    path  = "/presentation/brand_name",
                    value = "New brand name"
                },
                new Patch()
                {
                    op   = "remove",
                    path = "/flow_config/landing_page_type"
                }
            };

            #region Track Workflow
            //--------------------
            this.flow.AddNewRequest("Retrieve profile details", description: "ID: " + response.id);
            //--------------------
            #endregion

            // Get the profile object and partially update the profile.
            var retrievedProfile = WebProfile.Get(apiContext, response.id);

            #region Track Workflow
            //--------------------
            this.flow.RecordResponse(retrievedProfile);
            this.flow.AddNewRequest("Partially update profile", patchRequest);
            //--------------------
            #endregion

            retrievedProfile.PartialUpdate(apiContext, patchRequest);

            #region Track Workflow
            //--------------------
            this.flow.RecordActionSuccess("Profile updated successfully");
            //--------------------
            #endregion

            #region Cleanup
            // Cleanup by deleting the newly-created profile
            retrievedProfile.Delete(apiContext);
            #endregion
        }
Ejemplo n.º 12
0
        public ActionResult PaymentWithPaypal(Data.Models.Order orderInput)
        {
            APIContext apiContext = Configuration.GetAPIContext();

            try
            {
                string payerId = Request.Params["PayerID"];
                if (String.IsNullOrEmpty(payerId))
                {
                    var profile = new WebProfile
                    {
                        name         = Guid.NewGuid().ToString(),
                        presentation = new Presentation
                        {
                            brand_name  = "ELEX Store",
                            locale_code = "US"
                        },
                        input_fields = new InputFields
                        {
                            no_shipping = 1
                        }
                    };
                    var createdProfile = profile.Create(apiContext);

                    string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority +
                                     "/Paypal/PaymentWithPayPal?";
                    var guid = Convert.ToString((new Random()).Next(100000));
                    baseURI += "guid=" + guid + "&webProfileId=" + createdProfile.id;
                    Session["webProfileId"] = createdProfile.id;
                    var    createdPayment    = this.CreatePayment(apiContext, baseURI + "guid=" + guid, createdProfile);
                    var    links             = createdPayment.links.GetEnumerator();
                    string paypalRedirectUrl = null;

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

                        if (lnk.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            //saving the payapalredirect URL to which user will be redirected for payment
                            paypalRedirectUrl = lnk.href;
                        }
                    }
                    Session.Add(guid, createdPayment.id);
                    Session["OrderInput"] = orderInput;
                    return(Redirect(paypalRedirectUrl));
                }
                else
                {
                    // This section is executed when we have received all the payments parameters

                    // from the previous call to the function Create

                    // Executing a payment

                    var guid                     = Request.Params["guid"];
                    var webProfileId             = Session["webProfileId"].ToString();
                    Data.Models.Order orderModel = (Data.Models.Order)Session["OrderInput"];
                    try
                    {
                        var order = new Data.Models.Order()
                        {
                            CreatedDate     = DateTime.Now,
                            PaymentMethod   = "PayPal",
                            ShipAddress     = orderModel.ShipAddress,
                            ShipEmail       = orderModel.ShipEmail,
                            ShipMobile      = orderModel.ShipMobile,
                            ShipDescription = orderModel.ShipDescription,
                            Status          = 0,
                            ShipName        = orderModel.ShipName
                        };
                        var insert     = new OrdersDao().Insert(order);
                        var detailsDao = new OrderDetailsDao();
                        if (insert)
                        {
                            foreach (var cart in CommonConstants.listCart)
                            {
                                var orderDetail = new OrderDetails
                                {
                                    ProductID = cart.Product.ID,
                                    OrderID   = order.ID,
                                    Price     = cart.Product.Price - cart.Product.Price * cart.Product.Discount / 100,
                                    Quantity  = cart.Quantity
                                };
                                detailsDao.Insert(orderDetail);
                            }
                        }
                        var executedPayment = ExecutePayment(apiContext, payerId, Session[guid] as string);

                        WebProfile.Delete(apiContext, webProfileId);
                        Session.Remove("webProfileId");
                        CommonConstants.listCart.Clear();
                        Session["CartSession"] = CommonConstants.listCart;
                        if (executedPayment.state.ToLower() != "approved")
                        {
                            return(RedirectToAction("Index", "Home"));
                        }
                    }
                    catch (Exception)
                    {
                        return(RedirectToAction("Index", "Cart"));
                    }
                }
            }
            catch (Exception ex)
            {
                return(RedirectToAction("Index", "Home"));
            }


            return(RedirectToAction("Success", "Cart"));
        }