Как отправить платеж в Custom Payee в PayPal, используя c# asp. net? - PullRequest
1 голос
/ 23 апреля 2020

Я создаю приложение электронной коммерции c# mvc Asp. net, в котором я хочу, чтобы плательщик мог платить на разных счетах, у которых он / она приобрел товар.

Я хочу отправить платеж от плательщика пользовательскому получателю. Я использовал paypal.api sdk. Я добавил получателя в него, но он выдает ошибку, то есть «деталь исключения: {» name »:« MALFORMED_REQUEST »,« message »:« Входящий запрос JSON не отображается to API "

//// Pyapal.api sdk use
    public PaypalHelper CreatePayment(CreatePaymentHelper helper)
        {
            var apiContext = GetApiContext();

            string ProfileId = GetWebProfile(apiContext, helper.ExperienceProfileName).id;
            //ItemList itemList = new ItemList();
            //foreach (var i in helper.Items)
            //{
            //    Item item = new Item()
            //    {
            //        description = i.Description,
            //        currency = i.Currency,
            //        quantity = i.Quantity.ToString(),
            //        price = i.Price.ToString(), /// decimal strng
            //    };
            //    itemList.items.Add(item);
            //}
            var payment = new Payment()
            {
                experience_profile_id = ProfileId,
                intent = "order",
                payer = new Payer()
                {
                    payment_method = "paypal"
                },
                transactions = new List<Transaction>()
                {
                    new Transaction()
                    {
                        description = helper.TransactionDescription,
                        amount = new Amount()
                        {
                            currency = helper.CurrencyName,
                            total = helper.TransactionAmount.ToString()/// decimal and must be string
                        },

                       // item_list = itemList,
                        item_list = new ItemList()
                        {
                            items = helper.Items.Select(x=> new Item()
                            {
                                description = x.Description,
                                currency = x.Currency,
                                quantity = x.Quantity.ToString(),
                                price = x.Price.ToString()
                            }).ToList()
                        },

                    },

                },
                redirect_urls = new RedirectUrls()
                {
                    return_url = helper.ReturnUrl.ToString(),
                    cancel_url = helper.CancelUrl.ToString()
                    //Url.Action("action", "controller", "routeVaslues", Request.Url.Scheme);
                },
                payee = new Payee { email = "RecieverEmail"}
            };

            /// send payment to paypal
            var createdPayment = payment.Create(apiContext);


            ///get approval url where we need to send our user
            var ApprovalUrl = createdPayment.links.FirstOrDefault(x => x.rel.Equals("approval_url", StringComparison.OrdinalIgnoreCase));

            return new PaypalHelper
            {
                CreatedPaymentId = createdPayment.id,
                RedirectUrl = ApprovalUrl.href
            };
        }

Затем я попробовал метод Chained, но не смог его получить! Запрос как-то был выполнен, но не удалось получить платеж и авторизовать плательщика!

   public void AdaptiveChainedMethod()
        {

            ReceiverList receivers = new ReceiverList();
            Receiver receiver = new Receiver();
            receiver.email = "ReCIEVEREMAIL";
            receiver.amount = Convert.ToDecimal(22.00);
            receivers.receiver.Add(receiver);

            ReceiverList receiverList = new ReceiverList(receivers.receiver);

            PayRequest payRequest = new PayRequest();
            payRequest.actionType = "CREATE";
            payRequest.receiverList = receiverList;
            payRequest.currencyCode = "USD";
            payRequest.cancelUrl = "http://localhost:44382/cont/Act";
            payRequest.returnUrl= "http://localhost:44382/cont/Act";
            payRequest.requestEnvelope = new RequestEnvelope("en_US");

            APIContext apiContext = GetApiContext();

            Dictionary<string, string> config = new Dictionary<string, string>();
            config.Add("mode", "sandbox");
            config.Add("clientId", "id");
            config.Add("clientSecret", "seceret");
            config.Add("account1.apiUsername", "username");
            config.Add("account1.apiPassword", "pass");
            config.Add("account1.apiSignature", "signature");
            config.Add("account1.applicationId", "APP-80W284485P519543T"); // static account id

            AdaptivePaymentsService service = new AdaptivePaymentsService(config);
            PayResponse response = service.Pay(payRequest);

        }

Затем я попытался PayPalCheckoutSdk.Core PayPalCheckoutSdk.Orders sdk, но его запрос API зависал каждый раз, когда я нажимал на него, и никогда не отвечал!

         public async static Task<string> test()
        {
            OrderRequest orderRequest = new OrderRequest()
            {

                CheckoutPaymentIntent = "CAPTURE",

                ApplicationContext = new ApplicationContext
                {
                    ReturnUrl = "http://localhost:44382/cont/act",
                    CancelUrl = "http://localhost:44382/cont/act"
                },
                PurchaseUnits = new List<PurchaseUnitRequest>
                 {
                 new PurchaseUnitRequest {

        AmountWithBreakdown = new AmountWithBreakdown
        {
          CurrencyCode = "USD",
          Value = "220.00"
        },
        Payee = new Payee
        {
          Email = "RecieverEmail"
        }
      }
    }
            };
            var request = new OrdersCreateRequest();
          //  request.Prefer("return=representation");
            request.RequestBody(orderRequest);
           HttpResponse response = await client().Execute(request);
            var statusCode = response.StatusCode;
            Order result = response.Result<Order>();
            return "string";
        }



        public static PayPalHttpClient client()
        {
            string clientId = "clientid";
            string clientSecret = "secret";

            // Creating a sandbox environment
            PayPalEnvironment environment = new SandboxEnvironment(clientId, clientSecret);

            // Creating a client for the environment
            PayPalHttpClient client = new PayPalHttpClient(environment);
            return client;
        }
...