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/).
            }
        }
        /// <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);
            }
        }
Ejemplo n.º 3
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"));
        }