OAuthTokenCredential is used for generation of OAuth Token used by PayPal REST API service. clientId and clientSecret are required by the class to generate OAuth Token, the resulting token is of the form "Bearer xxxxxx". The class has two constructors, one of it taking an additional Dictionary used for dynamic configuration.
 /// <summary>
 /// Helper method for getting an access token for test purposes.
 /// </summary>
 /// <param name="endpoint"></param>
 /// <param name="clientId"></param>
 /// <param name="clientSecret"></param>
 /// <returns></returns>
 private string GetAccessToken(string endpoint, string clientId, string clientSecret)
 {
     Dictionary<string, string> config = new Dictionary<string, string>();
     config.Add("endpoint", endpoint);
     OAuthTokenCredential target = new OAuthTokenCredential(clientId, clientSecret, config);
     return target.GetAccessToken();
 }
 public void GetAccessTokenTest()
 {
     OAuthTokenCredential target = new OAuthTokenCredential(ClientID, ClientSecret); // TODO: Initialize to an appropriate value
     string expected = target.GetAccessToken();
     string actual = target.GetAccessToken();
     Assert.IsTrue(actual.ToLower().Contains("bearer"));
 }
 protected void Page_Load(object sender, EventArgs e)
 {
     HttpContext CurrContext = HttpContext.Current;
     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.GetProperty("ClientID"), ConfigManager.Instance.GetProperty("ClientSecret")).GetAccessToken();
         // ### Sale
         // Pass an AccessToken and the ID of the sale
         // transaction from your payment resource.
         Sale s = Sale.Get(accessToken, "4V7971043K262623A");
         CurrContext.Items.Add("ResponseJson",
             JObject.Parse(s.ConvertToJson()).ToString(Formatting.Indented));
     }
     catch (PayPal.Exception.PayPalException ex)
     {
         CurrContext.Items.Add("Error", ex.Message);
     }
     Server.Transfer("~/Response.aspx");
 }
Beispiel #4
0
        //Retriving the Token
        public static string GetPayPalToken()
        {
            OAuthTokenCredential tokenCredential = new OAuthTokenCredential(clientID, clientSecret);
            string accessToken = tokenCredential.GetAccessToken();

            return accessToken;
        }
Beispiel #5
0
        /// <summary>
        /// Returns the currently cached access token. If no access token was
        /// previously cached, or if the current access token is expired, then
        /// a new one is generated and returned.
        /// </summary>
        /// <returns>The OAuth access token to use for making PayPal requests.</returns>
        /// <exception cref="PayPal.Exception.MissingCredentialException">Thrown if clientId or clientSecret are null or empty.</exception>
        /// <exception cref="PayPal.Exception.InvalidCredentialException">Thrown if there is an issue converting the credentials to a formatted authorization string.</exception>
        /// <exception cref="PayPal.Exception.IdentityException">Thrown if authorization fails as a result of providing invalid credentials.</exception>
        /// <exception cref="PayPal.Exception.HttpException">Thrown if authorization fails and an HTTP error response is received.</exception>
        /// <exception cref="PayPal.Exception.ConnectionException">Thrown if there is an issue attempting to connect to PayPal's services.</exception>
        /// <exception cref="PayPal.Exception.ConfigException">Thrown if there is an error with any informaiton provided by the <see cref="PayPal.Manager.ConfigManager"/>.</exception>
        /// <exception cref="PayPal.Exception.PayPalException">Thrown for any other general exception. See inner exception for further details.</exception>
        public string GetAccessToken()
        {
            // If the cached access token value is valid, then check to see if
            // it has expired.
            if (!string.IsNullOrEmpty(this.accessToken))
            {
                // If the time since the access token was created is greater
                // than the access token's specified expiration time less the
                // safety gap, then regenerate the token.
                double elapsedSeconds = (DateTime.Now - this.AccessTokenLastCreationDate).TotalSeconds;
                if (elapsedSeconds > this.AccessTokenExpirationInSeconds - this.AccessTokenExpirationSafetyGapInSeconds)
                {
                    this.accessToken = null;
                }
            }

            // If the cached access token is empty or null, then generate a new token.
            if (string.IsNullOrEmpty(this.accessToken))
            {
                // Write Logic for passing in Detail to Identity Api Serv and
                // computing the token
                // Set the Value inside the accessToken and result
                string base64ClientId = OAuthTokenCredential.ConvertClientCredentialsToBase64String(this.ClientId, this.ClientSecret);
                this.accessToken = this.GenerateOAuthToken(base64ClientId);
            }
            return(this.accessToken);
        }
        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();

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

                // Void an Authorization
                // by POSTing to
                // URI v1/payments/authorization/{authorization_id}/void
                Authorization returnAuthorization = authorization.Void(accessToken);

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

            Server.Transfer("~/Response.aspx");
        }
        // ##GetPaymentByPaymentId
        // Call the method with a valid Payment ID
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpContext CurrContext = HttpContext.Current;
            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();

                // Retrieve the payment object by calling the
                // static `Get` method
                // on the Payment class by passing a valid
                // AccessToken and Payment ID
                Payment pymnt = Payment.Get(accessToken, "PAY-0XL713371A312273YKE2GCNI");

                CurrContext.Items.Add("ResponseJson", JObject.Parse(pymnt.ConvertToJson()).ToString(Formatting.Indented));
            }
            catch (PayPal.Exception.PayPalException ex)
            {
                CurrContext.Items.Add("Error", ex.Message);
            }
            Server.Transfer("~/Response.aspx");
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpContext CurrContext = HttpContext.Current;
            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();

                var parameters = new QueryParameters();
                parameters.SetCount("10");
                parameters.SetStartIndex("5");
                // ###Retrieve
                // Retrieve the PaymentHistory object by calling the
                // static `Get` method
                // on the Payment class, and pass the
                // AccessToken and a QueryParameters object that contains
                // query parameters for paginations and filtering.
                // Refer the API documentation
                // for valid values for keys
                PaymentHistory paymentHistory = Payment.Get(accessToken, parameters);
                CurrContext.Items.Add("ResponseJson", JObject.Parse(paymentHistory.ConvertToJson()).ToString(Formatting.Indented));
            }
            catch (PayPal.Exception.PayPalException ex)
            {
                CurrContext.Items.Add("Error", ex.Message);
            }
            Server.Transfer("~/Response.aspx");
        }
Beispiel #9
0
        public static APIContext Create()
        {
            var config = ConfigManager.Instance.GetProperties();

            var credentials = new OAuthTokenCredential(
                config[BaseConstants.ClientId],
                config[BaseConstants.ClientSecret]
                
                );

            // ### 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. 
            var apiContext = new APIContext(credentials.GetAccessToken())
            {
                Config = config
            };

            // 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(GetAccessToken(), requestId ));

            return apiContext;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpContext CurrContext = HttpContext.Current;
            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();

                // Retrieve the CreditCard object by calling the
                // static 'Get' method on the CreditCard class
                // by passing a valid AccessToken and CreditCard ID
                CreditCard credtCard = CreditCard.Get(accessToken, "CARD-5BT058015C739554AKE2GCEI");
                CurrContext.Items.Add("ResponseJson", JObject.Parse(credtCard.ConvertToJson()).ToString(Formatting.Indented));
            }
            catch (PayPal.Exception.PayPalException ex)
            {
                CurrContext.Items.Add("Error", ex.Message);
            }

            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");
        }
 public void GetAccessTokenTimeoutTest()
 {
     Dictionary<string, string> config = new Dictionary<string, string>();
     config[BaseConstants.ApplicationModeConfig] = BaseConstants.SandboxMode;
     config[BaseConstants.HttpConnectionTimeoutConfig] = "10";
     OAuthTokenCredential target = new OAuthTokenCredential(clientId, clientSecret, config);
     string accessToken = target.GetAccessToken();
 }
        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;

            // ###CreditCard
            // A resource representing a credit card that can be
            // used to fund a payment.
            CreditCard credtCard = new CreditCard();
            credtCard.expire_month = "11";
            credtCard.expire_year = "2018";
            credtCard.number = "4417119669820331";
            credtCard.type = "visa";

            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.GetProperty("ClientID"), ConfigManager.Instance.GetProperty("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 ));

                // ###Save
                // Creates the credit card as a resource
                // in the PayPal vault. The response contains
                // an 'id' that you can use to refer to it
                // in the future payments.
                CreditCard createdCreditCard = credtCard.Create(apiContext);
                CurrContext.Items.Add("ResponseJson", JObject.Parse(createdCreditCard.ConvertToJson()).ToString(Formatting.Indented));
            }
            catch (PayPal.Exception.PayPalException ex)
            {
                CurrContext.Items.Add("Error", ex.Message);
            }

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

            Server.Transfer("~/Response.aspx");
        }
 // Create accessToken
 private static string GetAccessToken()
 {
     // ###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("EBWKjlELKMYqRNQ6sYvFo64FtaRLRR5BdHEESmha49TM", "EO422dn3gQLgDbuwqTjzrFgFtaRLRR5BdHEESmha49TM", GetConfig()).GetAccessToken();
     return accessToken;
 }
 // Create accessToken
 private static string GetAccessToken()
 {
     // ###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(ClientId, ClientSecret, GetConfig()).GetAccessToken();
     return accessToken;
 }
 public void GetAccessTokenTest()
 {
     Dictionary<string, string> config = new Dictionary<string, string>();
     config.Add("endpoint", "https://api.sandbox.paypal.com");
     string clientId = "EBWKjlELKMYqRNQ6sYvFo64FtaRLRR5BdHEESmha49TM";
     string clientSecret = "EO422dn3gQLgDbuwqTjzrFgFtaRLRR5BdHEESmha49TM";
     OAuthTokenCredential target = new OAuthTokenCredential(clientId, clientSecret, config);
     string expected = string.Empty;
     string actual;
     actual = target.GetAccessToken();
     Assert.AreEqual(true, actual.StartsWith("Bearer "));
 }
        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");
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpContext CurrContext = HttpContext.Current;
            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
                // and retrieve the Id
                string captureId = GetCaptureId(accessToken, authorization);

                // Retrieve the Capture object by
                // doing a GET call to
                // URI v1/payments/capture/{capture_id}
                Capture capture = Capture.Get(accessToken, captureId);
                CurrContext.Items.Add("ResponseJson", JObject.Parse(capture.ConvertToJson()).ToString(Formatting.Indented));

            }
            catch (PayPal.Exception.PayPalException ex)
            {
                CurrContext.Items.Add("Error", ex.Message);
            }

            Server.Transfer("~/Response.aspx");
        }
Beispiel #21
0
        public ActionResult Capture(string authorizationId)
        {
            var viewData = new PayPalViewData();

            try
            {
                var accessToken = new OAuthTokenCredential(ConfigManager.Instance.GetProperties()["ClientID"], ConfigManager.Instance.GetProperties()["ClientSecret"]).GetAccessToken();
                var apiContext = new APIContext(accessToken);
                var authorization = Authorization.Get(apiContext, authorizationId);

                if (authorization != null)
                {
                    var total = Convert.ToDecimal(authorization.amount.total);

                    var capture = authorization.Capture(apiContext, new Capture
                       {
                           is_final_capture = true,
                           amount = new Amount
                           {
                               currency = "USD",
                               total = (total + (total * .05m)).ToString("f2")
                           },
                       });

                    viewData.JsonResponse = JObject.Parse(capture.ConvertToJson()).ToString(Formatting.Indented);

                    return View("Success", viewData);
                }

                viewData.ErrorMessage = "Could not find previous authorization.";

                return View("Error", viewData);
            }
            catch (PayPalException ex)
            {
                viewData.ErrorMessage = ex.Message;

                return View("Error", viewData);
            }
        }
        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");
        }
Beispiel #23
0
        public ActionResult Confirmed(Guid id, string token, string payerId)
        {
            var viewData = new OrderConfirmedViewData
            {
                Id = id,
                Token = token,
                PayerId = payerId
            };

            var accessToken = new OAuthTokenCredential(ConfigManager.Instance.GetProperties()["ClientID"], ConfigManager.Instance.GetProperties()["ClientSecret"]).GetAccessToken();
            var apiContext = new APIContext(accessToken);
            var payment = new Payment()
            {
                id = (string)Session[id.ToString()],
            };

            var executedPayment = payment.Execute(apiContext, new PaymentExecution { payer_id = payerId });

            viewData.AuthorizationId = executedPayment.transactions[0].related_resources[0].authorization.id;
            viewData.JsonRequest = JObject.Parse(payment.ConvertToJson()).ToString(Formatting.Indented);
            viewData.JsonResponse = JObject.Parse(executedPayment.ConvertToJson()).ToString(Formatting.Indented);

            return View(viewData);
        }
 public void OAuthTokenCredentialConstructorTest()
 {
     OAuthTokenCredential target = new OAuthTokenCredential(ClientID, ClientSecret);
     Assert.IsNotNull(target);
 }
        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");
        }
Beispiel #26
0
        private APIContext GetApiContext()
        {
            Dictionary<string, string> payPalConfig = new Dictionary<string, string>();

            if (this._isSandbox)
            {
                payPalConfig.Add("mode", "sandbox");
            }
            else
            {
                payPalConfig.Add("endpoint", this._payPalUrl);
            }

            OAuthTokenCredential tokenCredential = new OAuthTokenCredential(this._payPalClientId, this._payPalSecret, payPalConfig);
            string accessToken = tokenCredential.GetAccessToken();

            APIContext context = new APIContext(accessToken);
            context.Config = payPalConfig;
            return context;
        }
        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");
        }
Beispiel #28
0
        public ActionResult Void(string authorizationId)
        {
            var viewData = new PayPalViewData();

            try
            {
                var accessToken = new OAuthTokenCredential(ConfigManager.Instance.GetProperties()["ClientID"], ConfigManager.Instance.GetProperties()["ClientSecret"]).GetAccessToken();
                var apiContext = new APIContext(accessToken);
                var authorization = Authorization.Get(apiContext, authorizationId);

                if (authorization != null)
                {
                    var voidedAuthorization = authorization.Void(apiContext);

                    viewData.JsonResponse = JObject.Parse(voidedAuthorization.ConvertToJson()).ToString(Formatting.Indented);

                    return View(viewData);
                }

                viewData.ErrorMessage = "Could not find previous authorization.";

                return View("Error", viewData);
            }
            catch (PayPalException ex)
            {
                viewData.ErrorMessage = ex.Message;

                return View("Error", viewData);
            }
        }
Beispiel #29
0
        public ActionResult CreatePayment(string description, decimal price, decimal tax = 0, decimal shipping = 0)
        {
            var viewData = new PayPalViewData();
            var guid = Guid.NewGuid().ToString();

            var paymentInit = new Payment
            {
                intent = "authorize",
                payer = new Payer
                {
                    payment_method = "paypal"
                },
                transactions = new List<Transaction>
                {
                    new Transaction
                    {
                        amount = new Amount
                        {
                            currency = "USD",
                            total = (price + tax + shipping).ToString(),
                            details = new Details
                            {
                                subtotal = price.ToString(),
                                tax = tax.ToString(),
                                shipping = shipping.ToString()
                            }
                        },
                        description = description
                    }
                },
                redirect_urls = new RedirectUrls
                {
                    return_url = Utilities.ToAbsoluteUrl(HttpContext, Url.Action("Confirmed", new { id = guid })),
                    cancel_url = Utilities.ToAbsoluteUrl(HttpContext, Url.Action("Canceled", new { id = guid })),
                },
            };

            viewData.JsonRequest = JObject.Parse(paymentInit.ConvertToJson()).ToString(Formatting.Indented);

            try
            {
                var accessToken = new OAuthTokenCredential(ConfigManager.Instance.GetProperties()["ClientID"], ConfigManager.Instance.GetProperties()["ClientSecret"]).GetAccessToken();
                var apiContext = new APIContext(accessToken);
                var createdPayment = paymentInit.Create(apiContext);

                var approvalUrl = createdPayment.links.ToArray().FirstOrDefault(f => f.rel.Contains("approval_url"));

                if (approvalUrl != null)
                {
                    Session.Add(guid, createdPayment.id);

                    return Redirect(approvalUrl.href);
                }

                viewData.JsonResponse = JObject.Parse(createdPayment.ConvertToJson()).ToString(Formatting.Indented);

                return View("Error", viewData);
            }
            catch (PayPalException ex)
            {
                viewData.ErrorMessage = ex.Message;

                return View("Error", viewData);
            }
        }
Beispiel #30
0
 public static string AccessToken()
 {
     OAuthTokenCredential token = new OAuthTokenCredential(APIKey, APISecret);
     return token.GetAccessToken();
 }
Beispiel #31
0
		/// <summary>
		/// Helper: Holt von PayPal ein neues Accesstoken.
		/// </summary>
		/// <returns></returns>
		public APIContext GetPayPalToken()
		{
            var config = new Dictionary<string, string>();
            config.Add("clientId", ConfigurationManager.AppSettings["PayPal:Username"]);
            config.Add("clientSecret", ConfigurationManager.AppSettings["PayPal:Password"]);
            if (ConfigurationManager.AppSettings["PayPal:Sandbox"] != "False") {
                config.Add("mode", "sandbox");
            }

            var tokenCredential = new OAuthTokenCredential(
                config["clientId"],
                config["clientSecret"],
                config);

            var apiContext = new APIContext(tokenCredential.GetAccessToken());
            apiContext.Config = config;

			return apiContext;
		}