Exemple #1
0
        /// <summary>
        /// Create payment
        /// </summary>
        /// <param name="hostingDomain"></param>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public async Task <ResponsePaypal> CreatePaymentAsync(string hostingDomain, Guid?orderId)
        {
            var orderRequest = await _orderProductService.GetOrderByIdAsync(orderId);

            if (!orderRequest.IsSuccess)
            {
                return(new ResponsePaypal
                {
                    Message = "Order not Found",
                    IsSuccess = false
                });
            }

            var isPayedRequest = await _paymentService.IsOrderPayedAsync(orderId);

            if (isPayedRequest.IsSuccess)
            {
                return(new ResponsePaypal
                {
                    Message = "Order was payed before, Check your orders",
                    IsSuccess = false
                });
            }

            var order          = orderRequest.Result;
            var addressRequest = await _userAddressService.GetAddressByIdAsync(order.BillingAddress);

            var address = addressRequest.IsSuccess ? addressRequest.Result : new Address();
            var user    = await _userManager.UserManager.FindByIdAsync(order.UserId.ToString());

            var accessToken = await GetAccessTokenAsync();

            if (string.IsNullOrEmpty(accessToken))
            {
                return(new ResponsePaypal {
                    Message = "No access token", IsSuccess = false
                });
            }

            var fullName = user?.FirstName != null && user.LastName != null
                ? $"{user.FirstName} {user.LastName}"
                : user?.UserName;

            var shippingAddress = new ShippingAddress
            {
                City          = address.StateOrProvince?.Name,
                CountryCode   = address.Country?.Id?.ToUpper(),
                Phone         = address.Phone,
                Line1         = address.AddressLine1,
                Line2         = address.AddressLine2,
                PostalCode    = address.ZipCode,
                RecipientName = fullName
            };

            var items = new List <Item>();

            foreach (var item in order.ProductOrders)
            {
                items.Add(new Item
                {
                    Name        = item.Product.Name,
                    Currency    = order.Currency?.Code,
                    Price       = item.Product.PriceWithoutDiscount.ToString("N2"),
                    Description = item.Product.Description?.StripHtml(),
                    Quantity    = item.Amount.ToString(),
                    Sku         = "1",
                    Tax         = "0"
                });
            }

            using (var httpClient = new HttpClient())
            {
                var experienceProfileId = await CreateExperienceProfileAsync(accessToken);

                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                var paypalAcceptedNumericFormatCulture = CultureInfo.CreateSpecificCulture("en-US");
                //TODO: Apply payment fee
                var unused = CalculatePaymentFee(order.Total);
                var paymentCreateRequest = new PaymentCreateRequest
                {
                    ExperienceProfileId = experienceProfileId,
                    Intent = "sale",
                    Payer  = new Payer
                    {
                        PaymentMethod = "paypal",
                        PayerInfo     = new PayerInfo
                        {
                            Email = user?.Email
                        }
                    },
                    Transactions = new[]
                    {
                        new Transaction
                        {
                            Amount = new Amount
                            {
                                Total    = (order.Total + CalculatePaymentFee(order.Total)).ToString("N2", paypalAcceptedNumericFormatCulture),
                                Currency = order.Currency?.Code,
                                Details  = new Details
                                {
                                    Subtotal    = order.Total.ToString("N2", paypalAcceptedNumericFormatCulture),
                                    Tax         = "0",
                                    HandlingFee = CalculatePaymentFee(order.Total).ToString("N2", paypalAcceptedNumericFormatCulture)
                                }
                            },
                            Items = new ItemList
                            {
                                Items = items.ToArray(),
                                //ShippingAddress = shippingAddress
                            }
                        }
                    },
                    RedirectUrls = new RedirectUrls
                    {
                        CancelUrl = $"{hostingDomain}/Paypal/Cancel",
                        ReturnUrl = $"{hostingDomain}/Paypal/Success"
                    },
                    Notes = order.Notes
                };
                var serializedData = paymentCreateRequest.SerializeAsJson();
                var content        = new StringContent(serializedData, Encoding.UTF8, "application/json");
                var response       = await httpClient.PostAsync(
                    $"https://api{_payPalOptions.Value.EnvironmentUrlPart}.paypal.com/v1/payments/payment", content);

                var responseBody = await response.Content.ReadAsStringAsync();

                dynamic payment = JObject.Parse(responseBody);
                if (response.IsSuccessStatusCode)
                {
                    await _orderProductService.ChangeOrderStateAsync(orderId, OrderState.PendingPayment);

                    string paymentId = payment.id;
                    return(new ResponsePaypal {
                        Message = paymentId, IsSuccess = true
                    });
                }
                await _orderProductService.ChangeOrderStateAsync(orderId, OrderState.PaymentFailed);

                return(new ResponsePaypal {
                    Message = responseBody, IsSuccess = false
                });
            }
        }