Exemplo n.º 1
0
		/// <summary>
		/// Erstellt ein neues Payment für Paypal.
		/// </summary>
		/// <param name="returnUrl"></param>
		/// <param name="cancelUrl"></param>
		/// <param name="subTotalPrice"></param>
		/// <param name="shippingCosts"></param>
		/// <param name="totalPrice"></param>
		/// <param name="description"></param>
		/// <returns>Die Url für Paypal auf die der Benutzer weiter geleitet werden muss.</returns>
        public Uri CreateNewPayment(Uri returnUrl, Uri cancelUrl, decimal subTotalPrice, decimal shippingCosts, decimal totalPrice, string description, out string paymentId) 
        {
			var context = GetPayPalToken();

            //string accessToken = tokenCredential.GetAccessToken();

			var amountDetails = new Details();
			amountDetails.subtotal = _toPayPalPrice(subTotalPrice);
			amountDetails.tax = "0.00"; // Derzeit geben wir keine Steuern an.
			amountDetails.shipping = _toPayPalPrice(shippingCosts);

			var amount = new Amount();
			amount.total = _toPayPalPrice(totalPrice);
            amount.currency = "EUR";
			amount.details = amountDetails;

			var transaction = new Transaction();
			transaction.amount = amount;
            transaction.description = description;

			var transactions = new List<Transaction>();
			transactions.Add(transaction);

			var payer = new Payer();
			payer.payment_method = "paypal";

			var payment = new Payment();
			payment.intent = "sale";
			payment.payer  = payer;
            payment.transactions = transactions;
            payment.redirect_urls = new RedirectUrls {
				return_url = returnUrl.AbsoluteUri,
				cancel_url = cancelUrl.AbsoluteUri
            };

			var createdPayment = payment.Create(context);

			if (createdPayment == null) {
				throw new Exception("Beim Bezahlen mit PayPal ist etwas schief gelaufen. Aber keine Angst, Dein Geld wurde nicht angefasst!");
            }

			// Wir können den Kunden an PayPal weiterleiten.
            if (createdPayment.state == "created") {
                var approvalUrl = (from link in createdPayment.links
                                   where link.rel == "approval_url"
                                   select link.href).FirstOrDefault();
                if (approvalUrl == null) {
                    throw new Exception("PayPal hat uns keinen Link gegeben mit dem du Deine Bezahlung bestätigen könntest. Probiere es später noch einmal.");
                }

#if DEBUG
				if (approvalUrl.ToLower().IndexOf("sandbox") == -1) throw new AccessViolationException("PAYPAYL ist NICHT im SANDBOX-Modus!");
#endif

                paymentId = createdPayment.id;
                return new Uri(approvalUrl);
            }

            throw new Exception("PayPal lässt Dich leider nicht zahlen. Hmmm....");
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpContext CurrContext = HttpContext.Current;
            Authorization authorization = null;
            try
            {
                // ### 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..
                APIContext apiContext = Configuration.GetAPIContext();

                // ###Reauthorization
                // Make a authorized payment using `PayPal Account Payments` with intent
                // as `authorize`. You can reauthorize a payment only once 4 to 29
                // days after 3-day honor period for the original authorization
                // expires.
                authorization = Authorization.Get(apiContext, "8HD57954KS1107638");
                Amount reauthorizeAmount = new Amount();
                reauthorizeAmount.currency = "USD";
                reauthorizeAmount.total = "1";
                authorization.amount = reauthorizeAmount;
                Authorization reauthorization = authorization.Reauthorize(apiContext);
                CurrContext.Items.Add("ResponseJson", JObject.Parse(reauthorization.ConvertToJson()).ToString(Formatting.Indented));
            }
            catch (PayPal.Exception.PayPalException ex)
            {
                CurrContext.Items.Add("Error", ex.Message);
            }
            CurrContext.Items.Add("RequestJson", JObject.Parse(authorization.ConvertToJson()).ToString(Formatting.Indented));
            Server.Transfer("~/Response.aspx");
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpContext CurrContext = HttpContext.Current;

            // ###Amount
            // Create an Amount object to
            // represent the amount to be
            // refunded. Create the refund object, if the refund is partial
            Amount amount = new Amount();
            amount.currency = "USD";
            amount.total = "0.01";

            // ###Refund
            // A refund transaction.
            // Use the amount to create
            // a refund object
            Refund refund = new Refund();
            refund.amount = amount;
            // ###Sale
            // A sale transaction.
            // Create a Sale object with the
            // given sale transaction id.
            Sale sale = new Sale();
            sale.id = "03W403310B593121A";
            try
            {
                // ###AccessToken
                // Retrieve the access token from
                // OAuthTokenCredential by passing in
                // ClientID and ClientSecret
                // It is not mandatory to generate Access Token on a per call basis.
                // Typically the access token can be generated once and
                // reused within the expiry window
                string accessToken = new OAuthTokenCredential(ConfigManager.Instance.GetProperties()["ClientID"], ConfigManager.Instance.GetProperties()["ClientSecret"]).GetAccessToken();

                // ### 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.
                APIContext apiContext = new APIContext(accessToken);
                // Use this variant if you want to pass in a request id
                // that is meaningful in your application, ideally
                // a order id.
                // String requestId = Long.toString(System.nanoTime();
                // APIContext apiContext = new APIContext(accessToken, requestId ));

                // Refund by posting to the APIService
                // using a valid AccessToken
                Refund refundedSale = sale.Refund(apiContext, refund);
                CurrContext.Items.Add("ResponseJson",JObject.Parse(refundedSale.ConvertToJson()).ToString(Formatting.Indented));
            }
            catch (PayPal.Exception.PayPalException ex)
            {
                CurrContext.Items.Add("Error", ex.Message);
            }
            CurrContext.Items.Add("RequestJson",
                  JObject.Parse(refund.ConvertToJson()).ToString(Formatting.Indented));
            Server.Transfer("~/Response.aspx");
        }
Exemplo n.º 4
0
        public void CreditCardPay(Address billingaddr, CreditCard cc, Amount amount)
        {
            Transaction transaction = new Transaction();
            transaction.amount = amount;
            transaction.description = "This is the payment transaction description.";

            List<Transaction> transactions = new List<Transaction>();
            transactions.Add(transaction);

            FundingInstrument fundingInstrument = new FundingInstrument();
            fundingInstrument.credit_card = cc;

            List<FundingInstrument> fundingInstruments = new List<FundingInstrument>();
            fundingInstruments.Add(fundingInstrument);

            Payer payer = new Payer();
            payer.funding_instruments = fundingInstruments;
            payer.payment_method = "credit_card";

            Payment payment = new Payment();
            payment.intent = "sale";
            payment.payer  = payer;
            payment.transactions = transactions;

            Payment createdPayment = payment.Create(AccessToken());
        }
 private Amount GetAmount()
 {
     Amount amnt = new Amount();
     amnt.currency = "USD";
     amnt.details = GetDetails();
     amnt.total = "100";
     return amnt;
 }
 public void TestReauthorization()
 {
     Authorization authorization = Authorization.Get(AccessToken, "7GH53639GA425732B");
     Amount reauthorizeAmount = new Amount();
     reauthorizeAmount.currency = "USD";
     reauthorizeAmount.total = "1";
     authorization.amount = reauthorizeAmount;
     Authorization reauthorization = authorization.Reauthorize(AccessToken);          
 }
 public void TestReauthorization()
 {
     Authorization authorization = Authorization.Get(UnitTestUtil.GetApiContext(), "7GH53639GA425732B");
     Amount reauthorizeAmount = new Amount();
     reauthorizeAmount.currency = "USD";
     reauthorizeAmount.total = "1";
     authorization.amount = reauthorizeAmount;
     UnitTestUtil.AssertThrownException<PayPal.Exception.HttpException>(() => authorization.Reauthorize(UnitTestUtil.GetApiContext()));
 }
Exemplo n.º 8
0
        public string EfetuarCompra(PessoaFisica pessoaFisica, CreditCard creditCard, int quantidadeFits)
        {
            string valor = (quantidadeFits * valorFits).ToString();

            Dictionary<string, string> payPalConfig = new Dictionary<string, string>();
            payPalConfig.Add("mode", this.mode);

            OAuthTokenCredential tokenCredential = new OAuthTokenCredential(this.clientId, this.clientSecret, payPalConfig);

            string accessToken = tokenCredential.GetAccessToken();

            Address billingAddress = new Address();
            billingAddress.line1 = string.Format("{0} Num {1}",pessoaFisica.Endereco.Rua, pessoaFisica.Endereco.Numero) ;
            billingAddress.city = pessoaFisica.Endereco.Cidade;
            billingAddress.country_code = "BR";
            billingAddress.postal_code = pessoaFisica.Endereco.CEP;
            billingAddress.state = pessoaFisica.Endereco.Estado;

            creditCard.billing_address = billingAddress;

            Details amountDetails = new Details();
            amountDetails.subtotal = valor;
            amountDetails.tax = "0.00";
            amountDetails.shipping = "0.00";

            Amount amount = new Amount();
            amount.total = (quantidadeFits * valorFits).ToString();
            amount.currency = "USD";
            amount.details = amountDetails;

            Transaction transaction = new Transaction();
            transaction.amount = amount;
            transaction.description = string.Format("Este pagamento foi efetuado por {0}, na quantia de {1} fits", pessoaFisica.Nome, quantidadeFits);

            List<Transaction> transactions = new List<Transaction>();
            transactions.Add(transaction);

            FundingInstrument fundingInstrument = new FundingInstrument();
            fundingInstrument.credit_card = creditCard;

            List<FundingInstrument> fundingInstruments = new List<FundingInstrument>();
            fundingInstruments.Add(fundingInstrument);

            Payer payer = new Payer();
            payer.funding_instruments = fundingInstruments;
            payer.payment_method = "credit_card";

            Payment payment = new Payment();
            payment.intent = "sale";
            payment.payer = payer;
            payment.transactions = transactions;

            Payment createdPayment = payment.Create(accessToken);

            return valor;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpContext CurrContext = HttpContext.Current;
            Refund refund = null;
            try
            {

                // ###AccessToken
                // Retrieve the access token from
                // OAuthTokenCredential by passing in
                // ClientID and ClientSecret
                // It is not mandatory to generate Access Token on a per call basis.
                // Typically the access token can be generated once and
                // reused within the expiry window
                string accessToken = new OAuthTokenCredential(ConfigManager.Instance.GetProperties()["ClientID"], ConfigManager.Instance.GetProperties()["ClientSecret"]).GetAccessToken();

                // ###Authorization
                // Retrieve a Authorization object
                // by making a Payment with intent
                // as 'authorize'
                Authorization authorization = GetAuthorization(accessToken);

                /// ###Capture
                // Create a Capture object
                // by doing a capture on
                // Authorization object
                Capture capture = GetCapture(accessToken, authorization);

                /// ###Refund
                /// Create a Refund object
                refund = new Refund();

                // ###Amount
                // Let's you specify a capture amount.
                Amount refundAmount = new Amount();
                refundAmount.currency = "USD";
                refundAmount.total = "1";

                refund.amount = refundAmount;

                // Do a Refund by
                // POSTing to
                // URI v1/payments/capture/{capture_id}/refund
                Refund responseRefund = capture.Refund(accessToken, refund);
                CurrContext.Items.Add("ResponseJson", JObject.Parse(responseRefund.ConvertToJson()).ToString(Formatting.Indented));

            }
            catch (PayPal.Exception.PayPalException ex)
            {
                CurrContext.Items.Add("Error", ex.Message);
            }
            CurrContext.Items.Add("RequestJson", JObject.Parse(refund.ConvertToJson()).ToString(Formatting.Indented));
            Server.Transfer("~/Response.aspx");
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpContext CurrContext = HttpContext.Current;
            Capture capture = null;
            try
            {
                // ### 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.
                APIContext apiContext = Configuration.GetAPIContext();
                                
                // ###Authorization
                // Retrieve a Authorization object
                // by making a Payment with intent
                // as `authorize`
                Authorization authorization = Common.CreateAuthorization(apiContext);

                // ###Amount
                // Let's you specify a capture amount.
                Amount amnt = new Amount();
                amnt.currency = "USD";
                amnt.total = "4.54";

                capture = new Capture();
                capture.amount = amnt;

                // ##IsFinalCapture
                // If set to true, all remaining 
                // funds held by the authorization 
                // will be released in the funding 
                // instrument. Default is `false`.
                capture.is_final_capture = true;                      
                
                // Capture an authorized payment by POSTing to
                // URI v1/payments/authorization/{authorization_id}/capture
                Capture responseCapture = authorization.Capture(apiContext, capture);
                CurrContext.Items.Add("ResponseJson", JObject.Parse(responseCapture.ConvertToJson()).ToString(Formatting.Indented));
            }
            catch (PayPal.Exception.PayPalException ex)
            {
                CurrContext.Items.Add("Error", ex.Message);
            }

            if (capture != null)
            {
                CurrContext.Items.Add("RequestJson", JObject.Parse(capture.ConvertToJson()).ToString(Formatting.Indented));
            }

            Server.Transfer("~/Response.aspx");

        }
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpContext CurrContext = HttpContext.Current;
            Refund refund = null;
            try
            {

                // ### 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..
                APIContext apiContext = Configuration.GetAPIContext();

                // ###Authorization
                // Retrieve a Authorization object
                // by making a Payment with intent
                // as 'authorize'
                Authorization authorization = Common.CreateAuthorization(apiContext);

                /// ###Capture
                // Create a Capture object
                // by doing a capture on
                // Authorization object
                Capture capture = Common.GetCapture(apiContext, authorization);

                /// ###Refund
                /// Create a Refund object
                refund = new Refund();

                // ###Amount
                // Let's you specify a capture amount.
                Amount refundAmount = new Amount();
                refundAmount.currency = "USD";
                refundAmount.total = "0.50";

                refund.amount = refundAmount;

                // Do a Refund by
                // POSTing to 
                // URI v1/payments/capture/{capture_id}/refund
                Refund responseRefund = capture.Refund(Configuration.GetAPIContext(), refund);
                CurrContext.Items.Add("ResponseJson", JObject.Parse(responseRefund.ConvertToJson()).ToString(Formatting.Indented));

            }
            catch (PayPal.Exception.PayPalException ex)
            {
                CurrContext.Items.Add("Error", ex.Message);
            }
            CurrContext.Items.Add("RequestJson", JObject.Parse(refund.ConvertToJson()).ToString(Formatting.Indented));
            Server.Transfer("~/Response.aspx");
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpContext CurrContext = HttpContext.Current;
            Capture capture = null;
            try
            {
                // ###AccessToken
                // Retrieve the access token from
                // OAuthTokenCredential by passing in
                // ClientID and ClientSecret
                // It is not mandatory to generate Access Token on a per call basis.
                // Typically the access token can be generated once and
                // reused within the expiry window
                string accessToken = new OAuthTokenCredential(ConfigManager.Instance.GetProperties()["ClientID"], ConfigManager.Instance.GetProperties()["ClientSecret"]).GetAccessToken();

                // ###Authorization
                // Retrieve a Authorization object
                // by making a Payment with intent
                // as 'authorize'
                Authorization authorization = GetAuthorization(accessToken);

                // ###Amount
                // Let's you specify a capture amount.
                Amount amnt = new Amount();
                amnt.currency = "USD";
                amnt.total = "4.54";

                capture = new Capture();
                capture.amount = amnt;

                // ##IsFinalCapture
                // If set to true, all remaining
                // funds held by the authorization
                // will be released in the funding
                // instrument. Default is ‘false’.
                capture.is_final_capture = true;

                // Capture by POSTing to
                // URI v1/payments/authorization/{authorization_id}/capture
                Capture responseCapture = authorization.Capture(accessToken, capture);
                CurrContext.Items.Add("ResponseJson", JObject.Parse(responseCapture.ConvertToJson()).ToString(Formatting.Indented));

            }
            catch (PayPal.Exception.PayPalException ex)
            {
                CurrContext.Items.Add("Error", ex.Message);
            }
            CurrContext.Items.Add("RequestJson", JObject.Parse(capture.ConvertToJson()).ToString(Formatting.Indented));

            Server.Transfer("~/Response.aspx");
        }
Exemplo n.º 13
0
        public Payment CreatePaymentPaypal(string orderAmount, string orderDescription, string paymentMethod, string returnUrl, string cancelUrl)
        {
            Payment pymnt = null;

            //Create item
            ItemList ItemList = new ItemList();
            ItemList.items = new List<Item>();
            ItemList.items.Add(new Item { name = "A", currency = "USD", price = "10", quantity = "1", sku = "1" });
            ItemList.items.Add(new Item { name = "B", currency = "USD", price = "20", quantity = "2", sku = "1" });
            ItemList.items.Add(new Item { name = "C", currency = "USD", price = "50", quantity = "3", sku = "1" });
            ItemList.items.Add(new Item { name = "D", currency = "USD", price = "100", quantity = "4", sku = "1" });

            Details amountDetails = new Details();
            amountDetails.shipping = "0";
            amountDetails.tax = "0";
            amountDetails.subtotal = orderAmount;

            Amount amount = new Amount();
            amount.currency = "USD";
            int total = Convert.ToInt32(amountDetails.tax) + Convert.ToInt32(amountDetails.shipping) + Convert.ToInt32(orderAmount);
            amount.total = total.ToString();
            amount.details = amountDetails;

            RedirectUrls redirectUrls = new RedirectUrls();
            redirectUrls.return_url = returnUrl;
            redirectUrls.cancel_url = cancelUrl;

            Transaction transaction = new Transaction();
            transaction.item_list = ItemList;
            transaction.amount = amount;
            transaction.description = orderDescription;
            List<Transaction> transactions = new List<Transaction>();
            transactions.Add(transaction);

            Payer payer = new Payer();
            payer.payment_method = paymentMethod;

            Payment pyment = new Payment();
            pyment.intent = "sale";
            pyment.payer = payer;
            pyment.transactions = transactions;
            pyment.redirect_urls = redirectUrls;

            pymnt = pyment.Create(Api);
            return pymnt;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpContext CurrContext = HttpContext.Current;

            // ###Amount
            // Create an Amount object to
            // represent the amount to be
            // refunded. Create the refund object, if the refund is partial
            Amount amount = new Amount();
            amount.currency = "USD";
            amount.total = "0.01";

            // ###Refund
            // A refund transaction.
            // Use the amount to create
            // a refund object
            Refund refund = new Refund();
            refund.amount = amount;
            // ###Sale
            // A sale transaction.
            // Create a Sale object with the
            // given sale transaction id.
            Sale sale = new Sale();
            sale.id = "7X350557WR366683S";
            try
            {
                // ### 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..
                APIContext apiContext = Configuration.GetAPIContext();

                // Refund by posting Refund object using a valid APIContext
                Refund refundedSale = sale.Refund(apiContext, refund);
                CurrContext.Items.Add("ResponseJson", JObject.Parse(refundedSale.ConvertToJson()).ToString(Formatting.Indented));
            }
            catch (PayPal.Exception.PayPalException ex)
            {
                CurrContext.Items.Add("Error", ex.Message);
            }
            CurrContext.Items.Add("RequestJson",
                  JObject.Parse(refund.ConvertToJson()).ToString(Formatting.Indented));
            Server.Transfer("~/Response.aspx");
        }
        public Payment CreatePayment(string email, PaymentMethod payMethod, string orderAmount, string orderDescription, string returnUrl, string cancelUrl)
        {
            Payment pay = null;

            Details amountDetails = new Details();
            amountDetails.shipping = "2";
            amountDetails.tax = "1";
            amountDetails.subtotal = orderAmount;

            Amount amount = new Amount();
            amount.currency = "USD";
            int total = Convert.ToInt32(amountDetails.tax) + Convert.ToInt32(amountDetails.shipping) + Convert.ToInt32(orderAmount);
            amount.total = total.ToString();
            amount.details = amountDetails;

            RedirectUrls redirectUrls = new RedirectUrls();
            redirectUrls.return_url = returnUrl;
            redirectUrls.cancel_url = cancelUrl;

            Transaction transaction = new Transaction();
            transaction.amount = amount;
            transaction.description = orderDescription;
            List<Transaction> transactions = new List<Transaction>();
            transactions.Add(transaction);

            Payer payr = new Payer();
            payr.payment_method = payMethod.ToString();

            Payment paymnt = new Payment();
            paymnt.intent = "sale";
            paymnt.payer = payr;
            paymnt.transactions = transactions;
            paymnt.redirect_urls = redirectUrls;

            pay = paymnt.Create(Api);
            return pay;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpContext CurrContext = HttpContext.Current;
            Authorization authorization = null;
            try
            {
                // ###AccessToken
                // Retrieve the access token from
                // OAuthTokenCredential by passing in
                // ClientID and ClientSecret
                // It is not mandatory to generate Access Token on a per call basis.
                // Typically the access token can be generated once and
                // reused within the expiry window
                string accessToken = new OAuthTokenCredential(ConfigManager.Instance.GetProperties()["ClientID"], ConfigManager.Instance.GetProperties()["ClientSecret"]).GetAccessToken();

                // ###Reauthorization
                // Retrieve a authorization id from authorization object
                // by making a `Payment Using PayPal` with intent
                // as `authorize`. You can reauthorize a payment only once 4 to 29
                // days after 3-day honor period for the original authorization
                // expires.
                authorization = Authorization.Get(accessToken, "7GH53639GA425732B");
                Amount reauthorizeAmount = new Amount();
                reauthorizeAmount.currency = "USD";
                reauthorizeAmount.total = "1";
                authorization.amount = reauthorizeAmount;
                Authorization reauthorization = authorization.Reauthorize(accessToken);
                CurrContext.Items.Add("ResponseJson", JObject.Parse(reauthorization.ConvertToJson()).ToString(Formatting.Indented));

            }
            catch (PayPal.Exception.PayPalException ex)
            {
                CurrContext.Items.Add("Error", ex.Message);
            }
            CurrContext.Items.Add("RequestJson", JObject.Parse(authorization.ConvertToJson()).ToString(Formatting.Indented));
            Server.Transfer("~/Response.aspx");
        }
 public void GetCaptureTest()
 {
     Payment payment = GetPaymentObject(AccessToken);
     string authorizationId = payment.transactions[0].related_resources[0].authorization.id;
     Authorization authorization = Authorization.Get(AccessToken, authorizationId);
     Capture capture = new Capture();
     Amount amount = new Amount();
     amount.total = "1";
     amount.currency = "USD";
     capture.amount = amount;
     Capture response = authorization.Capture(AccessToken, capture);
     Capture returnCapture = Capture.Get(AccessToken, response.id);
     Assert.AreEqual(response.id, returnCapture.id);
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpContext CurrContext = HttpContext.Current;
            Payment pymnt = null;

            // ## ExecutePayment
            if (Request.Params["PayerID"] != null)
            {
                pymnt = new Payment();
                if (Request.Params["guid"] != null)
                {
                    pymnt.id = (string)Session[Request.Params["guid"]];

                }
                try
                {
                    // ###AccessToken
                    // Retrieve the access token from
                    // OAuthTokenCredential by passing in
                    // ClientID and ClientSecret
                    // It is not mandatory to generate Access Token on a per call basis.
                    // Typically the access token can be generated once and
                    // reused within the expiry window
                    string accessToken = new OAuthTokenCredential(ConfigManager.Instance.GetProperties()["ClientID"], ConfigManager.Instance.GetProperties()["ClientSecret"]).GetAccessToken();

                    // ### 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.
                    APIContext apiContext = new APIContext(accessToken);
                    // Use this variant if you want to pass in a request id
                    // that is meaningful in your application, ideally
                    // a order id.
                    // String requestId = Long.toString(System.nanoTime();
                    // APIContext apiContext = new APIContext(accessToken, requestId ));
                    PaymentExecution pymntExecution = new PaymentExecution();
                    pymntExecution.payer_id = Request.Params["PayerID"];

                    Payment executedPayment = pymnt.Execute(apiContext,
                            pymntExecution);
                    CurrContext.Items.Add("ResponseJson", JObject.Parse(executedPayment.ConvertToJson()).ToString(Formatting.Indented));
                }
                catch (PayPal.Exception.PayPalException ex)
                {
                    CurrContext.Items.Add("Error", ex.Message);
                }
            }

            // ## Creating Payment
            else
            {
                // ###Payer
                // A resource representing a Payer that funds a payment
                // Payment Method
                // as `paypal`
                Payer payr = new Payer();
                payr.payment_method = "paypal";
                Random rndm = new Random();
                var guid = Convert.ToString(rndm.Next(100000));

                string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/PaymentWithPayPal.aspx?";

                // # Redirect URLS
                RedirectUrls redirUrls = new RedirectUrls();
                redirUrls.cancel_url = baseURI + "guid=" + guid;
                redirUrls.return_url = baseURI + "guid=" + guid;

                // ###Details
                // Let's you specify details of a payment amount.
                Details details = new Details();
                details.tax = "15";
                details.shipping = "10";
                details.subtotal = "75";

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

                // ###Transaction
                // A transaction defines the contract of a
                // payment - what is the payment for and who
                // is fulfilling it. Transaction is created with
                // a `Payee` and `Amount` types
                List<Transaction> transactionList = new List<Transaction>();
                Transaction tran = new Transaction();
                tran.description = "Transaction description.";
                tran.amount = amnt;
                // The Payment creation API requires a list of
                // Transaction; add the created `Transaction`
                // to a List
                transactionList.Add(tran);

                // ###Payment
                // A Payment Resource; create one using
                // the above types and intent as 'sale'
                pymnt = new Payment();
                pymnt.intent = "sale";
                pymnt.payer = payr;
                pymnt.transactions = transactionList;
                pymnt.redirect_urls = redirUrls;

                try
                {
                    // ###AccessToken
                    // Retrieve the access token from
                    // OAuthTokenCredential by passing in
                    // ClientID and ClientSecret
                    // It is not mandatory to generate Access Token on a per call basis.
                    // Typically the access token can be generated once and
                    // reused within the expiry window
                    string accessToken = new OAuthTokenCredential(ConfigManager.Instance.GetProperties()["ClientID"], ConfigManager.Instance.GetProperties()["ClientSecret"]).GetAccessToken();

                    // ### 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.
                    APIContext apiContext = new APIContext(accessToken);
                    // Use this variant if you want to pass in a request id
                    // that is meaningful in your application, ideally
                    // a order id.
                    // String requestId = Long.toString(System.nanoTime();
                    // APIContext apiContext = new APIContext(accessToken, requestId ));

                    // Create a payment by posting to the APIService
                    // using a valid AccessToken
                    // The return object contains the status;
                    Payment createdPayment = pymnt.Create(apiContext);

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

                    var links = createdPayment.links.GetEnumerator();

                    while (links.MoveNext())
                    {
                        Links lnk = links.Current;
                        if (lnk.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            CurrContext.Items.Add("RedirectURL", lnk.href);
                        }
                    }
                    Session.Add(guid, createdPayment.id);
                }
                catch (PayPal.Exception.PayPalException ex)
                {
                    CurrContext.Items.Add("Error", ex.Message);
                }
            }
            CurrContext.Items.Add("RequestJson", JObject.Parse(pymnt.ConvertToJson()).ToString(Formatting.Indented));

            Server.Transfer("~/Response.aspx");
        }
        public Payment CreatePayment(string email, PaymentMethod paymntMethod, string orderAmount, string orderDescription)
        {
            Payment pay = null;

            Amount amount = new Amount();
            amount.currency = "USD";
            amount.total = orderAmount;

            Transaction transaction = new Transaction();
            transaction.amount = amount;
            transaction.description = orderDescription;

            List<Transaction> transactions = new List<Transaction>();
            transactions.Add(transaction);

            FundingInstrument fundingInstrument = new FundingInstrument();
            CreditCardToken creditCardToken = new CreditCardToken();
            creditCardToken.credit_card_id = GetSignedInUserCreditCardID(email);
            fundingInstrument.credit_card_token = creditCardToken;

            List<FundingInstrument> fundingInstrumentList = new List<FundingInstrument>();
            fundingInstrumentList.Add(fundingInstrument);

            Payer payer = new Payer();
            payer.funding_instruments = fundingInstrumentList;
            payer.payment_method = paymntMethod.ToString();

            Payment pyment = new Payment();
            pyment.intent = "sale";
            pyment.payer = payer;
            pyment.transactions = transactions;
            pay = pyment.Create(Api);
            return pay;
        }
 public void AuthorizationCaptureTest()
 {
     Payment pay = CreatePayment();
     string authorizationId = pay.transactions[0].related_resources[0].authorization.id;
     Authorization authorize = Authorization.Get(UnitTestUtil.GetApiContext(), authorizationId);
     Capture cap = new Capture();
     Amount amt = new Amount();
     amt.total = "1";
     amt.currency = "USD";
     cap.amount = amt;
     Capture response = authorize.Capture(UnitTestUtil.GetApiContext(), cap);
     Assert.AreEqual("completed", response.state);
 }
        private string GetAuthorizationId(string accessToken)
        {
            // ###Address
            // Base Address object used as shipping or billing
            // address in a payment.
            Address billingAddress = new Address();
            billingAddress.city = "Johnstown";
            billingAddress.country_code = "US";
            billingAddress.line1 = "52 N Main ST";
            billingAddress.postal_code = "43210";
            billingAddress.state = "OH";

            // ###CreditCard
            // A resource representing a credit card that can be
            // used to fund a payment.
            CreditCard crdtCard = new CreditCard();
            crdtCard.billing_address = billingAddress;
            crdtCard.cvv2 = "874";
            crdtCard.expire_month = 11;
            crdtCard.expire_year = 2018;
            crdtCard.first_name = "Joe";
            crdtCard.last_name = "Shopper";
            crdtCard.number = "4417119669820331";
            crdtCard.type = "visa";

            // ###Details
            // Let's you specify details of a payment amount.
            Details details = new Details();
            details.shipping = "0.03";
            details.subtotal = "107.41";
            details.tax = "0.03";

            // ###Amount
            // Let's you specify a payment amount.
            Amount amnt = new Amount();
            amnt.currency = "USD";
            // Total must be equal to sum of shipping, tax and subtotal.
            amnt.total = "107.47";
            amnt.details = details;

            // ###Transaction
            // A transaction defines the contract of a
            // payment - what is the payment for and who
            // is fulfilling it. Transaction is created with
            // a `Payee` and `Amount` types
            Transaction tran = new Transaction();
            tran.amount = amnt;
            tran.description = "This is the payment transaction description.";

            // The Payment creation API requires a list of
            // Transaction; add the created `Transaction`
            // to a List
            List<Transaction> transactions = new List<Transaction>();
            transactions.Add(tran);

            // ###FundingInstrument
            // A resource representing a Payeer's funding instrument.
            // Use a Payer ID (A unique identifier of the payer generated
            // and provided by the facilitator. This is required when
            // creating or using a tokenized funding instrument)
            // and the `CreditCardDetails`
            FundingInstrument fundInstrument = new FundingInstrument();
            fundInstrument.credit_card = crdtCard;

            // The Payment creation API requires a list of
            // FundingInstrument; add the created `FundingInstrument`
            // to a List
            List<FundingInstrument> fundingInstrumentList = new List<FundingInstrument>();
            fundingInstrumentList.Add(fundInstrument);

            // ###Payer
            // A resource representing a Payer that funds a payment
            // Use the List of `FundingInstrument` and the Payment Method
            // as 'credit_card'
            Payer payr = new Payer();
            payr.funding_instruments = fundingInstrumentList;
            payr.payment_method = "credit_card";

            // ###Payment
            // A Payment Resource; create one using
            // the above types and intent as `sale`
            Payment pymnt = new Payment();
            pymnt.intent = "authorize";
            pymnt.payer = payr;
            pymnt.transactions = transactions;

            // Create a payment by posting to the APIService
            // using a valid AccessToken
            // The return object contains the status;
            Payment createdPayment = pymnt.Create(accessToken);

            return createdPayment.transactions[0].related_resources[0].authorization.id;
        }
 public void AmountConstructorTest()
 {
     Amount target = new Amount();
     Assert.IsNotNull(target);
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpContext CurrContext = HttpContext.Current;
            Payment pymnt = null;

            // ### 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..
            APIContext apiContext = Configuration.GetAPIContext();

            // ## ExecutePayment
            if (Request.Params["PayerID"] != null)
            {
                pymnt = new Payment();
                if (Request.Params["guid"] != null)
                {
                    pymnt.id = (string)Session[Request.Params["guid"]];

                }
                try
                {
                    PaymentExecution pymntExecution = new PaymentExecution();
                    pymntExecution.payer_id = Request.Params["PayerID"];

                    Payment executedPayment = pymnt.Execute(apiContext, pymntExecution);
                    CurrContext.Items.Add("ResponseJson", JObject.Parse(executedPayment.ConvertToJson()).ToString(Formatting.Indented));
                }
                catch (PayPal.Exception.PayPalException ex)
                {
                    CurrContext.Items.Add("Error", ex.Message);
                }
            }

            // ## Creating Payment
            else
            {
                // ###Items
                // Items within a transaction.
                Item item = new Item();
                item.name = "Item Name";
                item.currency = "USD";
                item.price = "15";
                item.quantity = "5";
                item.sku = "sku";

                List<Item> itms = new List<Item>();
                itms.Add(item);
                ItemList itemList = new ItemList();
                itemList.items = itms;

                // ###Payer
                // A resource representing a Payer that funds a payment
                // Payment Method
                // as `paypal`
                Payer payr = new Payer();
                payr.payment_method = "paypal";
                Random rndm = new Random();
                var guid = Convert.ToString(rndm.Next(100000));

                string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/PaymentWithPayPal.aspx?";

                // # Redirect URLS
                RedirectUrls redirUrls = new RedirectUrls();
                redirUrls.cancel_url = baseURI + "guid=" + guid;
                redirUrls.return_url = baseURI + "guid=" + guid;

                // ###Details
                // Let's you specify details of a payment amount.
                Details details = new Details();
                details.tax = "15";
                details.shipping = "10";
                details.subtotal = "75";

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

                // ###Transaction
                // A transaction defines the contract of a
                // payment - what is the payment for and who
                // is fulfilling it. 
                List<Transaction> transactionList = new List<Transaction>();
                Transaction tran = new Transaction();
                tran.description = "Transaction description.";
                tran.amount = amnt;
                tran.item_list = itemList;
                // The Payment creation API requires a list of
                // Transaction; add the created `Transaction`
                // to a List
                transactionList.Add(tran);

                // ###Payment
                // A Payment Resource; create one using
                // the above types and intent as `sale` or `authorize`
                pymnt = new Payment();
                pymnt.intent = "sale";
                pymnt.payer = payr;
                pymnt.transactions = transactionList;
                pymnt.redirect_urls = redirUrls;

                try
                {
                    // Create a payment using a valid APIContext
                    Payment createdPayment = pymnt.Create(apiContext);

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

                    var links = createdPayment.links.GetEnumerator();

                    while (links.MoveNext())
                    {
                        Links lnk = links.Current;
                        if (lnk.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            CurrContext.Items.Add("RedirectURL", lnk.href);
                        }
                    }
                    Session.Add(guid, createdPayment.id);
                }
                catch (PayPal.Exception.PayPalException ex)
                {
                    CurrContext.Items.Add("Error", ex.Message);
                }
            }
            CurrContext.Items.Add("RequestJson", JObject.Parse(pymnt.ConvertToJson()).ToString(Formatting.Indented));

            Server.Transfer("~/Response.aspx");

        }
Exemplo n.º 24
0
 public void RefundIdTest()
 {
     Payment pay = GetPayment();
     string authorizationId = pay.transactions[0].related_resources[0].authorization.id;
     Authorization authorization = Authorization.Get(AccessToken, authorizationId);
     Capture cap = new Capture();
     Amount amt = new Amount();
     amt.total = "1";
     amt.currency = "USD";
     cap.amount = amt;
     Capture response = authorization.Capture(AccessToken, cap);
     Refund fund = new Refund();
     Amount refundAmount = new Amount();
     refundAmount.total = "1";
     refundAmount.currency = "USD";
     fund.amount = refundAmount;
     Refund responseRefund = response.Refund(AccessToken, fund);
     Refund retrievedRefund = Refund.Get(AccessToken, responseRefund.id);
     Assert.AreEqual(responseRefund.id, retrievedRefund.id);
 }
 public void RefundCaptureTest()
 {
     Payment payment = GetPaymentObject(AccessToken);
     string authorizationId = payment.transactions[0].related_resources[0].authorization.id;
     Authorization authorization = Authorization.Get(AccessToken, authorizationId);
     Capture capture = new Capture();
     Amount amount = new Amount();
     amount.total = "1";
     amount.currency = "USD";
     capture.amount = amount;
     Capture response = authorization.Capture(AccessToken, capture);
     Refund refund = new Refund();
     Amount rAmount = new Amount();
     rAmount.total = "1";
     rAmount.currency = "USD";
     refund.amount = rAmount;
     Refund responseRefund = response.Refund(AccessToken, refund);
     Assert.AreEqual("completed", responseRefund.state);
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpContext CurrContext = HttpContext.Current;

            // ###CreditCard
            // A resource representing a credit card that can be
            // used to fund a payment.
            CreditCardToken credCardToken = new CreditCardToken();
            credCardToken.credit_card_id = "CARD-5BT058015C739554AKE2GCEI";

            // ###AmountDetails
            // Let's you specify details of a payment amount.
            AmountDetails amntDetails = new AmountDetails();
            amntDetails.shipping = "1";
            amntDetails.subtotal = "5";
            amntDetails.tax = "1";

            // ###Amount
            // Let's you specify a payment amount.
            Amount amnt = new Amount();
            amnt.currency = "USD";
            // Total must be equal to the sum of shipping, tax and subtotal.
            amnt.total = "7";
            amnt.details = amntDetails;

            // ###Transaction
            // A transaction defines the contract of a
            // payment - what is the payment for and who
            // is fulfilling it. Transaction is created with
            // a `Payee` and `Amount` types
            Transaction tran = new Transaction();
            tran.amount = amnt;
            tran.description = "This is the payment transaction description.";

            // The Payment creation API requires a list of
            // Transaction; add the created `Transaction`
            // to a List
            List<Transaction> transactions = new List<Transaction>();
            transactions.Add(tran);

            // ###FundingInstrument
            // A resource representing a Payeer's funding instrument.
            // Use a Payer ID (A unique identifier of the payer generated
            // and provided by the facilitator. This is required when
            // creating or using a tokenized funding instrument)
            // and the `CreditCardDetails`
            FundingInstrument fundInstrument = new FundingInstrument();
            fundInstrument.credit_card_token = credCardToken;

            // The Payment creation API requires a list of
            // FundingInstrument; add the created `FundingInstrument`
            // to a List
            List<FundingInstrument> fundingInstrumentList = new List<FundingInstrument>();
            fundingInstrumentList.Add(fundInstrument);

            // ###Payer
            // A resource representing a Payer that funds a payment
            // Use the List of `FundingInstrument` and the Payment Method
            // as 'credit_card'
            Payer payr = new Payer();
            payr.funding_instruments = fundingInstrumentList;
            payr.payment_method = "credit_card";

            // ###Payment
            // A Payment Resource; create one using
            // the above types and intent as 'sale'
            Payment pymnt = new Payment();
            pymnt.intent = "sale";
            pymnt.payer = payr;
            pymnt.transactions = transactions;

            try
            {
                // ###AccessToken
                // Retrieve the access token from
                // OAuthTokenCredential by passing in
                // ClientID and ClientSecret
                // It is not mandatory to generate Access Token on a per call basis.
                // Typically the access token can be generated once and
                // reused within the expiry window
                string accessToken = new OAuthTokenCredential(ConfigManager.Instance.GetProperties()["ClientID"], ConfigManager.Instance.GetProperties()["ClientSecret"]).GetAccessToken();

                // ### 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.
                APIContext apiContext = new APIContext(accessToken);
                // Use this variant if you want to pass in a request id
                // that is meaningful in your application, ideally
                // a order id.
                // String requestId = Long.toString(System.nanoTime();
                // APIContext apiContext = new APIContext(accessToken, requestId ));
                // Create a payment by posting to the APIService
                // using a valid AccessToken
                // The return object contains the status;

                // Create a payment by posting to the APIService
                // using a valid AccessToken
                // The return object contains the status;
                Payment createdPayment = pymnt.Create(apiContext);
                CurrContext.Items.Add("ResponseJson", JObject.Parse(createdPayment.ConvertToJson()).ToString(Formatting.Indented));
            }
            catch (PayPal.Exception.PayPalException ex)
            {
                CurrContext.Items.Add("Error", ex.Message);
            }
            CurrContext.Items.Add("RequestJson", JObject.Parse(pymnt.ConvertToJson()).ToString(Formatting.Indented));
            Server.Transfer("~/Response.aspx");
        }
Exemplo n.º 27
0
        public PaymentResponse ProcessPaymentForCart(Cart cart, string cancelUrl, string returnUrl)
        {
            var apiContext = ApiContextFactory.Create();

            var paypalItems = new ItemList
            {
                items = cart.GetItems().OfType<ProductCartItem>().Select(li => new Item
                {
                    name = li.Title,
                    price = li.PriceWithoutTax.ToString("N"),
                    currency = _config.Currency,
                    quantity = li.Quantity.ToString(),
                    sku = li.Id.ToString()
                }).ToList()
            };

            // ###Payer
            // A resource representing a Payer that funds a payment
            // Payment Method
            // as `paypal`
            var payer = new Payer { payment_method = "paypal" };

            //// # Redirect URLS
            var redirUrls = new RedirectUrls
            {
                cancel_url = cancelUrl,
                return_url = returnUrl
            };

            // ###Details
            // Let's you specify details of a payment amount.
            var details = new Details
            {
                tax = cart.CalculateTotalTax().TaxAmount.ToString("N"),
                shipping = cart.ShippingCost.Cost.ToString("N"),
                subtotal = cart.CalculateSubTotalWithoutTax().ToString("N"),
            };

            // ###Amount
            // Let's you specify a payment amount.
            var amount = new Amount
            {
                currency = _config.Currency,
                total = cart.CalculateGrandTotal().ToString("N"), // Total must be equal to sum of shipping, tax and subtotal.
                details = details
            };

            // ###Transaction
            // A transaction defines the contract of a
            // payment - what is the payment for and who
            // is fulfilling it.
            var transactionList = new List<Transaction>
            {
                new Transaction
                {
                    description = "UNIXMO Online Store",
                    amount = amount,
                    item_list = paypalItems
                }
            };

            // The Payment creation API requires a list of
            // Transaction; add the created `Transaction`
            // to a List

            // ###Payment
            // A Payment Resource; create one using
            // the above types and intent as `sale` or `authorize`
            var payment = new Payment
            {
                intent = "sale",
                payer = payer,
                transactions = transactionList,
                redirect_urls = redirUrls
            };

            var myResponse = payment.Create(apiContext);

            if (myResponse == null || myResponse.links == null)
            {
                return PaymentResponse.Failed();
            }

            var approvalUrl = myResponse.links.FirstOrDefault(lnk => lnk.rel.Equals("approval_url", StringComparison.OrdinalIgnoreCase));
            if (approvalUrl == null)
                return PaymentResponse.Failed();

            cart.SetPaymentTransaction(myResponse.id);

            return PaymentResponse.Completed(approvalUrl.href, myResponse.id);
        }
        // ##Create
        // Sample showing to create a Payment using
        // CreditCard as a FundingInstrument
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpContext CurrContext = HttpContext.Current;

            // ###Items
            // Items within a transaction.
            Item item = new Item();
            item.name = "Item Name";
            item.currency = "USD";
            item.price = "1";
            item.quantity = "5";
            item.sku = "sku";

            List<Item> itms = new List<Item>();
            itms.Add(item);
            ItemList itemList = new ItemList();
            itemList.items = itms;

            // ###Address
            // Base Address object used as shipping or billing
            // address in a payment.
            Address billingAddress = new Address();
            billingAddress.city = "Johnstown";
            billingAddress.country_code = "US";
            billingAddress.line1 = "52 N Main ST";
            billingAddress.postal_code = "43210";
            billingAddress.state = "OH";

            // ###CreditCard
            // A resource representing a credit card that can be
            // used to fund a payment.
            CreditCard crdtCard = new CreditCard();
            crdtCard.billing_address = billingAddress;
            crdtCard.cvv2 = "874";
            crdtCard.expire_month = 11;
            crdtCard.expire_year = 2018;
            crdtCard.first_name = "Joe";
            crdtCard.last_name = "Shopper";
            crdtCard.number = "4417119669820331";
            crdtCard.type = "visa";

            // ###Details
            // Let's you specify details of a payment amount.
            Details details = new Details();
            details.shipping = "1";
            details.subtotal = "5";
            details.tax = "1";

            // ###Amount
            // Let's you specify a payment amount.
            Amount amnt = new Amount();
            amnt.currency = "USD";
            // Total must be equal to sum of shipping, tax and subtotal.
            amnt.total = "7";
            amnt.details = details;

            // ###Transaction
            // A transaction defines the contract of a
            // payment - what is the payment for and who
            // is fulfilling it. 
            Transaction tran = new Transaction();
            tran.amount = amnt;
            tran.description = "This is the payment transaction description.";
            tran.item_list = itemList;

            // The Payment creation API requires a list of
            // Transaction; add the created `Transaction`
            // to a List
            List<Transaction> transactions = new List<Transaction>();
            transactions.Add(tran);

            // ###FundingInstrument
            // A resource representing a Payer's funding instrument.
            // For direct credit card payments, set the CreditCard
            // field on this object.
            FundingInstrument fundInstrument = new FundingInstrument();
            fundInstrument.credit_card = crdtCard;

            // The Payment creation API requires a list of
            // FundingInstrument; add the created `FundingInstrument`
            // to a List
            List<FundingInstrument> fundingInstrumentList = new List<FundingInstrument>();
            fundingInstrumentList.Add(fundInstrument);

            // ###Payer
            // A resource representing a Payer that funds a payment
            // Use the List of `FundingInstrument` and the Payment Method
            // as `credit_card`
            Payer payr = new Payer();
            payr.funding_instruments = fundingInstrumentList;
            payr.payment_method = "credit_card";

            // ###Payment
            // A Payment Resource; create one using
            // the above types and intent as `sale` or `authorize`
            Payment pymnt = new Payment();
            pymnt.intent = "sale";
            pymnt.payer = payr;
            pymnt.transactions = transactions;

            try
            {
                // ### 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..
                APIContext apiContext = Configuration.GetAPIContext();

                // Create a payment using a valid APIContext
                Payment createdPayment = pymnt.Create(apiContext);
                CurrContext.Items.Add("ResponseJson", JObject.Parse(createdPayment.ConvertToJson()).ToString(Formatting.Indented));
            }
            catch (PayPal.Exception.PayPalException ex)
            {
                CurrContext.Items.Add("Error", ex.Message);
            }

            CurrContext.Items.Add("RequestJson", JObject.Parse(pymnt.ConvertToJson()).ToString(Formatting.Indented));

            Server.Transfer("~/Response.aspx");
        }
 public void reauthorization()
 {
     Authorization authorization = Authorization.Get(AccessToken, "7GH53639GA425732B");
     Amount reauthorizeAmount = new Amount();
     reauthorizeAmount.currency = "USD";
     reauthorizeAmount.total = "1";
     authorization.amount = reauthorizeAmount;
     try
     {
         Authorization reauthorization = authorization.Reauthorize(AccessToken);
     }
     catch (PayPal.Exception.PayPalException exe)
     {
         Assert.IsNotNull(exe);
     }
 }
Exemplo n.º 30
0
        public PayPal.Api.Payments.Payment CreatePayment(IOrder order, string returnUrl, string cancelUrl)
        {
            Amount amount = new Amount();
            amount.currency = "AUD";
            amount.total = order.Total.ToString();
            amount.details = new Details();

            RedirectUrls redirectUrls = new RedirectUrls();
            redirectUrls.return_url = returnUrl;
            redirectUrls.cancel_url = cancelUrl;

            Transaction transaction = new Transaction();
            transaction.amount = amount;
            transaction.item_list = new ItemList() { items = new List<Item>() };

            foreach (var orderItem in order.Items)
            {
                Item item = new Item()
                {
                    name = orderItem.Product.Title,
                    price = orderItem.Product.Cost.ToString(),
                    quantity = orderItem.Quantity.ToString(),
                    currency = "AUD"
                };

                transaction.item_list.items.Add(item);
            }

            List<Transaction> transactions = new List<Transaction>() { transaction };

            Payer payer = new Payer() { payment_method = "paypal" };

            PayPal.Api.Payments.Payment pyment = new PayPal.Api.Payments.Payment();
            pyment.intent = "sale";
            pyment.payer = payer;
            pyment.transactions = transactions;
            pyment.redirect_urls = redirectUrls;

            return pyment.Create(this.GetApiContext());
        }