Ejemplo n.º 1
0
        public static Payment CreateFuturePayment()
        {
            FuturePayment pay = new FuturePayment();

            pay.intent = "sale";
            CreditCard card = CreditCardTest.GetCreditCard();
            List <FundingInstrument> fundingInstruments = new List <FundingInstrument>();
            FundingInstrument        fundingInstrument  = new FundingInstrument();

            fundingInstrument.credit_card = card;
            fundingInstruments.Add(fundingInstrument);
            Payer payer = new Payer();

            payer.payment_method      = "credit_card";
            payer.funding_instruments = fundingInstruments;
            List <Transaction> transactionList = new List <Transaction>();
            Transaction        trans           = new Transaction();

            trans.amount = AmountTest.GetAmount();
            transactionList.Add(trans);
            pay.transactions = transactionList;
            pay.payer        = payer;
            Payment paymnt = pay.Create(UnitTestUtil.GetApiContext());

            return(paymnt);
        }
Ejemplo n.º 2
0
        public PreAuthorizePaymentResponse PreAuthorize(Guid accountId, Guid orderId, string email, decimal amountToPreAuthorize, bool isReAuth = false)
        {
            var message       = string.Empty;
            var transactionId = string.Empty;
            var preAuthAmount = amountToPreAuthorize;

            try
            {
                var isSuccessful = false;

                if (amountToPreAuthorize > 0)
                {
                    var account        = _accountDao.FindById(accountId);
                    var regionName     = _serverSettings.ServerData.PayPalRegionInfoOverride;
                    var conversionRate = _serverSettings.ServerData.PayPalConversionRate;
                    _logger.LogMessage("PayPal Conversion Rate: {0}", conversionRate);

                    var amount = Math.Round(amountToPreAuthorize * conversionRate, 2);
                    preAuthAmount = amount;

                    var futurePayment = new FuturePayment
                    {
                        intent = Intents.Authorize,
                        payer  = new Payer
                        {
                            payment_method = "paypal"
                        },
                        transactions = new List <Transaction>
                        {
                            new Transaction
                            {
                                amount = new Amount
                                {
                                    currency = conversionRate != 1
                                        ? CurrencyCodes.Main.UnitedStatesDollar
                                        : _resources.GetCurrencyCode(),
                                    total = amount.ToString("N", CultureInfo.InvariantCulture)
                                },
                                description = regionName.HasValue()
                                    ? string.Format("order: {0}", orderId)
                                    : string.Format(_resources.Get("PaymentItemDescription", account.Language), orderId, amountToPreAuthorize)
                            }
                        }
                    };

                    var refreshToken = _accountDao.GetPayPalEncryptedRefreshToken(accountId);
                    if (!refreshToken.HasValue())
                    {
                        throw new Exception("Account has no PayPal refresh token");
                    }

                    var accessToken = GetAccessToken(accountId);

                    var createdPayment = futurePayment.Create(GetAPIContext(accessToken, isReAuth ? Guid.NewGuid() : orderId));
                    transactionId = createdPayment.transactions[0].related_resources[0].authorization.id;

                    switch (createdPayment.state)
                    {
                    case PaymentStates.Approved:
                        isSuccessful = true;
                        break;

                    case PaymentStates.Created:
                    case PaymentStates.Pending:
                        message = string.Format("Authorization state was {0}", createdPayment.state);
                        break;

                    case PaymentStates.Failed:
                    case PaymentStates.Canceled:
                    case PaymentStates.Expired:
                        message = string.Format("Authorization state was {0}", createdPayment.state);
                        break;
                    }
                }
                else
                {
                    // if we're preauthorizing $0, we skip the preauth with payment provider
                    // but we still send the InitiateCreditCardPayment command
                    // this should never happen in the case of a real preauth (hence the minimum of $50)
                    isSuccessful = true;
                }

                if (isSuccessful && !isReAuth)
                {
                    var paymentId = Guid.NewGuid();
                    _commandBus.Send(new InitiateCreditCardPayment
                    {
                        PaymentId     = paymentId,
                        Amount        = preAuthAmount,
                        TransactionId = transactionId,
                        OrderId       = orderId,
                        Provider      = PaymentProvider.PayPal,
                        IsNoShowFee   = false
                    });
                }

                return(new PreAuthorizePaymentResponse
                {
                    IsSuccessful = isSuccessful,
                    Message = message,
                    TransactionId = transactionId
                });
            }
            catch (Exception ex)
            {
                var exceptionMessage = ex.Message;

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

                _logger.LogMessage(string.Format("Error during preauthorization (validation of the PayPal account) for client {0}: {1} - {2}",
                                                 email, message + exceptionMessage, paymentException ?? ex));
                _logger.LogError(paymentException ?? ex);

                return(new PreAuthorizePaymentResponse
                {
                    IsSuccessful = false,
                    Message = message
                });
            }
        }
        // #Create Future Payment Using PayPal
        // This sample code demonstrates how you can process a future payment made using a PayPal account.
        /// <summary>
        /// Code example for creating a future payment object.
        /// </summary>
        /// <param name="correlationId"></param>
        /// <param name="authorizationCode"></param>
        private Payment CreateFuturePayment(string correlationId, string authorizationCode, string redirectUrl)
        {
            // ###Payer
            // A resource representing a Payer that funds a payment
            // Payment Method
            // as `paypal`
            Payer payer = new Payer()
            {
                payment_method = "paypal"
            };

            // ###Amount
            // Let's you specify a payment amount.
            var amount = new Amount()
            {
                currency = "USD",
                // Total must be equal to sum of shipping, tax and subtotal.
                total = "100",
                // ###Details
                // Let's you specify details of a payment amount.
                details = new Details()
                {
                    tax      = "15",
                    shipping = "10",
                    subtotal = "75"
                }
            };

            // # Redirect URLS
            var redirUrls = new RedirectUrls()
            {
                cancel_url = redirectUrl,
                return_url = redirectUrl
            };

            // ###Items
            // Items within a transaction.
            var itemList = new ItemList()
            {
                items = new List <Item>()
            };

            itemList.items.Add(new Item()
            {
                name     = "Item Name",
                currency = "USD",
                price    = "15",
                quantity = "5",
                sku      = "sku"
            });

            // ###Transaction
            // A transaction defines the contract of a
            // payment - what is the payment for and who
            // is fulfilling it.
            var transactionList = new List <Transaction>();

            // The Payment creation API requires a list of
            // Transaction; add the created `Transaction`
            // to a List
            transactionList.Add(new Transaction()
            {
                description = "Transaction description.",
                amount      = amount,
                item_list   = itemList
            });

            var authorizationCodeParameters = new CreateFromAuthorizationCodeParameters();

            authorizationCodeParameters.setClientId(Configuration.ClientId);
            authorizationCodeParameters.setClientSecret(Configuration.ClientSecret);
            authorizationCodeParameters.SetCode(authorizationCode);

            // ### 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();


            var tokenInfo   = Tokeninfo.CreateFromAuthorizationCodeForFuturePayments(apiContext, authorizationCodeParameters);
            var accessToken = string.Format("{0} {1}", tokenInfo.token_type, tokenInfo.access_token);

            var futurePaymentApiContext = Configuration.GetAPIContext(accessToken);

            // ###Payment
            // A FuturePayment Resource
            var futurePayment = new FuturePayment()
            {
                intent        = "authorize",
                payer         = payer,
                transactions  = transactionList,
                redirect_urls = redirUrls
            };

            return(futurePayment.Create(futurePaymentApiContext, correlationId));
        }