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");
        }
Example #2
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;
        }
 public void DomEndpointTest()
 {
     APIContext baseAPIContext = new APIContext();
     Dictionary<string, string> configurationMap = new Dictionary<string, string>();
     configurationMap.Add("endpoint", "https://api-3t.sandbox.paypal.com/2.0");
     DefaultSOAPAPICallHandler defHandler = new DefaultSOAPAPICallHandler(new SampleBody(), baseAPIContext, configurationMap, "DoDirectPayment");
     Assert.AreEqual("https://api-3t.sandbox.paypal.com/2.0", defHandler.GetEndpoint());
 }
 public void APIContextConstructorTest()
 {
     string tokenAccess = AccessToken;
     string requestId = Convert.ToString(Guid.NewGuid());
     APIContext apiContext = new APIContext(tokenAccess, requestId);
     Assert.IsNotNull(apiContext);
     Assert.AreEqual(tokenAccess, apiContext.AccessToken);
     Assert.AreEqual(requestId, apiContext.RequestID);
 }
        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");
        }
        // Returns APIContext object
        public static APIContext GetAPIContext()
        {
            // ### 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(GetAccessToken());
            apiContext.Config = GetConfig();

            // 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;
        }
Example #7
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);
            }
        }
        public void DomPayloadTest()
        {
            DefaultSOAPAPICallHandler.XMLNamespaceProvider = new XmlNamespacePrefixProvider();
            APIContext api = new APIContext();
            api.SOAPHeader = new SampleHeader();
            Dictionary<string, string> configurationMap = new Dictionary<string, string>();
            configurationMap.Add("service.EndPoint", "https://api-3t.sandbox.paypal.com/2.0");
            api.Config = configurationMap;

            DefaultSOAPAPICallHandler defHandler = new DefaultSOAPAPICallHandler(new SampleBody(), api, null, "DoDirectPayment");
            string payload = defHandler.GetPayload().Trim();
            string expectedPayload = "<soapenv:Envelope xmlns:xml=\"http://www.w3.org/XML/1998/namespace\" xmlns:ed=\"urn:ebay:apis:EnhancedDataTypes\" xmlns:cc=\"urn:ebay:apis:CoreComponentTypes\" xmlns:ebl=\"urn:ebay:apis:eBLBaseComponents\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:wsdlsoap=\"http://schemas.xmlsoap.org/wsdl/soap/\" xmlns:ns=\"urn:ebay:api:PayPalAPI\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:wsdl=\"http://schemas.xmlsoap.org/wsdl/\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">"  +
                "<soapenv:Header>" +
                "<ns:RequesterCredentials>" +
                "<ebl:Credentials>" +
                "<ebl:Username>jb-us-seller_api1.paypal.com</ebl:Username>" +
                "</ebl:Credentials>" +
                "</ns:RequesterCredentials>" +
                "</soapenv:Header>" +
                "<soapenv:Body>" +
                "<ns:DoDirectPaymentReq>" +
                "<ns:DoDirectPaymentRequest>" +
                "<ebl:Version>98.0</ebl:Version>" +
                "<ebl:DoDirectPaymentRequestDetails>" +
                "<ebl:CreditCard>" +
                "<ebl:CreditCardType>Visa</ebl:CreditCardType>" +
                "<ebl:CreditCardNumber>4202297003827029</ebl:CreditCardNumber>" +
                "<ebl:CVV2>962</ebl:CVV2>" +
                "</ebl:CreditCard>" +
                "</ebl:DoDirectPaymentRequestDetails>" +
                "</ns:DoDirectPaymentRequest>" +
                "</ns:DoDirectPaymentReq>" +
                "</soapenv:Body>" +
            "</soapenv:Envelope>";
            Assert.AreEqual(expectedPayload, payload);
        }
Example #9
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);
        }
Example #10
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);
            }
        }
Example #11
0
        public static T ConfigureAndExecute <T>(string accessToken, HttpMethod httpMethod, string resource, string payLoad)
        {
            APIContext apiContext = new APIContext(accessToken);

            return(ConfigureAndExecute <T>(apiContext, httpMethod, resource, null, payLoad));
        }
 /// <summary>
 /// Obtain the Payment resource for the given identifier.
 /// </summary>
 public static Payment Get(APIContext apiContext, string paymentId)
 {
     if (string.IsNullOrEmpty(apiContext.AccessToken))
     {
         throw new ArgumentNullException("AccessToken cannot be null or empty");
     }
     if (paymentId == null)
     {
         throw new ArgumentNullException("paymentId cannot be null");
     }
     object[] parameters = new object[] {paymentId};
     string pattern = "v1/payments/payment/{0}";
     string resourcePath = SDKUtil.FormatURIPath(pattern, parameters);
     string payLoad = "";
     return PayPalResource.ConfigureAndExecute<Payment>(apiContext, HttpMethod.GET, resourcePath, payLoad);
 }
        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 void TestPayment()
 {
     APIContext context = new APIContext(AccessToken);
     Payment pay = GetPayment();
     Payment retrievedPayment = Payment.Get(context, pay.id);
     Assert.AreEqual(pay.id, retrievedPayment.id);
 }
Example #15
0
		/// <summary>
		/// Creates (and processes) a new Payment Resource.
		/// </summary>
		/// <param name="apiContext">APIContext used for the API call.</param>
		/// <returns>Payment</returns>
		public Payment Create(APIContext apiContext)
		{
			if (apiContext == null)
			{
				throw new ArgumentNullException("APIContext cannot be null");
			}
			if (string.IsNullOrEmpty(apiContext.AccessToken))
			{
				throw new ArgumentNullException("AccessToken cannot be null or empty");
			}
			if (apiContext.HTTPHeaders == null)
			{
				apiContext.HTTPHeaders = new Dictionary<string, string>();
			}
			apiContext.HTTPHeaders.Add(BaseConstants.ContentTypeHeader, BaseConstants.ContentTypeHeaderJson);
			apiContext.SdkVersion = new SDKVersionImpl();
			string resourcePath = "v1/payments/payment";
			string payLoad = this.ConvertToJson();
			return PayPalResource.ConfigureAndExecute<Payment>(apiContext, HttpMethod.POST, resourcePath, payLoad);
		}
Example #16
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;
		}
Example #17
0
 /// <summary>
 /// Obtain the Refund transaction resource for the given identifier.
 /// </summary>
 /// <param name="accessToken">Access Token used for the API call.</param>
 /// <param name="refundId">string</param>
 /// <returns>Refund</returns>
 public static Refund Get(string accessToken, string refundId)
 {
     APIContext apiContext = new APIContext(accessToken);
     return Get(apiContext, refundId);
 }
Example #18
0
 public static T ConfigureAndExecute <T>(APIContext apiContext, HttpMethod httpMethod, string resource, string payLoad)
 {
     return(ConfigureAndExecute <T>(apiContext, httpMethod, resource, null, payLoad));
 }
Example #19
0
		/// <summary>
		/// Executes the payment (after approved by the Payer) associated with this resource when the payment method is PayPal.
		/// </summary>
		/// <param name="apiContext">APIContext used for the API call.</param>
		/// <param name="paymentExecution">PaymentExecution</param>
		/// <returns>Payment</returns>
		public Payment Execute(APIContext apiContext, PaymentExecution paymentExecution)
		{
			if (apiContext == null)
			{
				throw new ArgumentNullException("APIContext cannot be null");
			}
			if (string.IsNullOrEmpty(apiContext.AccessToken))
			{
				throw new ArgumentNullException("AccessToken cannot be null or empty");
			}
			if (apiContext.HTTPHeaders == null)
			{
				apiContext.HTTPHeaders = new Dictionary<string, string>();
			}
			apiContext.HTTPHeaders.Add(BaseConstants.ContentTypeHeader, BaseConstants.ContentTypeHeaderJson);
			apiContext.SdkVersion = new SDKVersionImpl();
			if (this.id == null)
			{
				throw new ArgumentNullException("Id cannot be null");
			}
			if (paymentExecution == null)
			{
				throw new ArgumentNullException("paymentExecution cannot be null");
			}
			object[] parameters = new object[] {this.id};
			string pattern = "v1/payments/payment/{0}/execute";
			string resourcePath = SDKUtil.FormatURIPath(pattern, parameters);
			string payLoad = paymentExecution.ConvertToJson();
			return PayPalResource.ConfigureAndExecute<Payment>(apiContext, HttpMethod.POST, resourcePath, payLoad);
		}
        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");
        }
 /// <summary>
 /// Retrieves a list of Payment resources.
 /// </summary>
 public static PaymentHistory List(string accessToken, Dictionary<String, String> containerDictionary)
 {
     APIContext apiContext = new APIContext(accessToken);
     return List(apiContext, containerDictionary);
 }
 public void PaymentHistoryTest()
 {
     APIContext context = new APIContext(AccessToken);
     Dictionary<string, string> containerDictionary = new Dictionary<string, string>();
     containerDictionary.Add("count", "10");
     PaymentHistory paymentHistory = Payment.List(context, containerDictionary);
     Assert.AreEqual(10, paymentHistory.count);
 }
 /// <summary>
 /// Creates (and processes) a new Payment Resource.
 /// </summary>
 public Payment Create(string accessToken)
 {
     APIContext apiContext = new APIContext(accessToken);
     return Create(apiContext);
 }
 /// <summary>
 /// Obtain the Payment resource for the given identifier.
 /// </summary>
 public static Payment Get(string accessToken, string paymentId)
 {
     APIContext apiContext = new APIContext(accessToken);
     return Get(apiContext, paymentId);
 }
 /// <summary>
 /// Executes the payment (after approved by the Payer) associated with this resource when the payment method is PayPal.
 /// </summary>
 public Payment Execute(string accessToken, PaymentExecution paymentExecution)
 {
     APIContext apiContext = new APIContext(accessToken);
     return Execute(apiContext, paymentExecution);
 }
 public static PaymentHistory Get(string accessToken, QueryParameters queryParameters)
 {
     APIContext apiContext = new APIContext(accessToken);
     return Get(apiContext, queryParameters);
 }
Example #27
0
        public static T ConfigureAndExecute <T>(APIContext apiContext, HttpMethod httpMethod, string resource, Dictionary <string, string> headersMap, string payLoad)
        {
            try
            {
                string response = null;
                Dictionary <string, String> headers;
                Uri uniformResourceIdentifier = null;
                Uri baseUri = null;
                Dictionary <string, string> config = null;
                if (apiContext.Config == null)
                {
                    config = ConfigManager.getConfigWithDefaults(ConfigManager.Instance.GetProperties());
                }
                else
                {
                    config = ConfigManager.getConfigWithDefaults(apiContext.Config);
                }
                baseUri = GetBaseURI(config);
                bool success = Uri.TryCreate(baseUri, resource, out uniformResourceIdentifier);

                RESTConfiguration restConfiguration = new RESTConfiguration(config, headersMap);
                restConfiguration.authorizationToken = apiContext.AccessToken;
                restConfiguration.requestId          = apiContext.RequestID;
                headers = restConfiguration.GetHeaders();

                ConnectionManager connMngr = ConnectionManager.Instance;
                connMngr.GetConnection(config, uniformResourceIdentifier.ToString());
                HttpWebRequest httpRequest = connMngr.GetConnection(config, uniformResourceIdentifier.ToString());
                httpRequest.Method = httpMethod.ToString();
                if (headers != null && headers.ContainsKey("Content-Type"))
                {
                    httpRequest.ContentType = headers["Content-Type"];
                    headers.Remove("Content-Type");
                }
                else
                {
                    httpRequest.ContentType = "application/json";
                }
                httpRequest.ContentLength = payLoad.Length;
                foreach (KeyValuePair <string, string> header in headers)
                {
                    if (header.Key.Trim().Equals("User-Agent"))
                    {
                        httpRequest.UserAgent = header.Value;
                    }
                    else
                    {
                        httpRequest.Headers.Add(header.Key, header.Value);
                    }
                }
                if (logger.IsDebugEnabled)
                {
                    foreach (string headerName in httpRequest.Headers)
                    {
                        logger.Debug(headerName + ":" + httpRequest.Headers[headerName]);
                    }
                }
                HttpConnection connectionHttp = new HttpConnection(config);
                response = connectionHttp.Execute(payLoad, httpRequest);
                if (typeof(T).Name.Equals("Object"))
                {
                    return(default(T));
                }
                else
                {
                    return(JsonConvert.DeserializeObject <T>(response));
                }
            }
            catch (PayPalException ex)
            {
                throw ex;
            }
            catch (System.Exception ex)
            {
                throw new PayPalException(ex.Message, ex);
            }
        }
 /// <summary>
 /// Retrieves a list of Payment resources.
 /// </summary>
 public static PaymentHistory List(APIContext apiContext, Dictionary<String, String> containerDictionary)
 {
     if (string.IsNullOrEmpty(apiContext.AccessToken))
     {
         throw new ArgumentNullException("AccessToken cannot be null or empty");
     }
     if (containerDictionary == null)
     {
         throw new ArgumentNullException("containerDictionary cannot be null");
     }
     object[] parameters = new object[] {containerDictionary};
     string pattern = "v1/payments/payment?count={0}&start_id={1}&start_index={2}&start_time={3}&end_time={4}&payee_id={5}&sort_by={6}&sort_order={7}";
     string resourcePath = SDKUtil.FormatURIPath(pattern, parameters);
     string payLoad = "";
     return PayPalResource.ConfigureAndExecute<PaymentHistory>(apiContext, HttpMethod.GET, resourcePath, payLoad);
 }
Example #29
0
 /// <summary>
 /// Get call for Payment.
 /// GET /v1/payments/payment?count=:count&start_id=:start_id&start_index=:start_index&start_time=:start_time&end_time=:end_time&payee_id=:payee_id&sort_by=:sort_by&sort_order=:sort_order
 /// <param name="apiContext">APIContext required for the call</param>
 /// <param name="parameters">Container for query strings</param>
 /// <returns>Returns PaymentHistory object</returns>
 /// </summary>
 public static PaymentHistory Get(APIContext apiContext, QueryParameters parameters)
 {
     if (string.IsNullOrEmpty(apiContext.AccessToken))
     {
         throw new ArgumentNullException("AccessToken cannot be null");
     }
     string pattern = "v1/payments/payment?count={0}&start_id={1}&start_index={2}&start_time={3}&end_time={4}&payee_id={5}&sort_by={6}&sort_order={7}";
     object[] container = new object[] { parameters };
     string resourcePath = SDKUtil.FormatURIPath(pattern, container);
     string payLoad = string.Empty;
     return PayPalResource.ConfigureAndExecute<PaymentHistory>(apiContext, HttpMethod.GET, resourcePath, payLoad);
 }
 /// <summary>
 /// Creates (and processes) a new Payment Resource.
 /// </summary>
 public Payment Create(APIContext apiContext)
 {
     if (string.IsNullOrEmpty(apiContext.AccessToken))
     {
         throw new ArgumentNullException("AccessToken cannot be null or empty");
     }
     string resourcePath = "v1/payments/payment";
     string payLoad = this.ConvertToJson();
     return PayPalResource.ConfigureAndExecute<Payment>(apiContext, HttpMethod.POST, resourcePath, payLoad);
 }
Example #31
0
 /// <summary>
 /// Get call for Payment.
 /// GET /v1/payments/payment/:paymentId
 /// <param name="apiContext">APIContext required for the call</param>
 /// <param name="paymentId">PaymentId</param>
 /// <returns>Returns Payment object</returns>
 /// </summary>
 public static Payment Get(APIContext apiContext, string paymentId)
 {
     if (string.IsNullOrEmpty(apiContext.AccessToken))
     {
         throw new ArgumentNullException("AccessToken cannot be null");
     }
     if (String.IsNullOrEmpty(paymentId))
     {
         throw new System.ArgumentNullException("paymentId cannot be null or empty");
     }
     string pattern = "v1/payments/payment/{0}";
     object[] container = new Object[] { paymentId };
     string resourcePath = SDKUtil.FormatURIPath(pattern, container);
     string payLoad = string.Empty;
     return PayPalResource.ConfigureAndExecute<Payment>(apiContext, HttpMethod.GET, resourcePath, payLoad);
 }
 /// <summary>
 /// Executes the payment (after approved by the Payer) associated with this resource when the payment method is PayPal.
 /// </summary>
 public Payment Execute(APIContext apiContext, PaymentExecution paymentExecution)
 {
     if (string.IsNullOrEmpty(apiContext.AccessToken))
     {
         throw new ArgumentNullException("AccessToken cannot be null or empty");
     }
     if (this.id == null)
     {
         throw new ArgumentNullException("Id cannot be null");
     }
     if (paymentExecution == null)
     {
         throw new ArgumentNullException("paymentExecution cannot be null");
     }
     object[] parameters = new object[] {this.id};
     string pattern = "v1/payments/payment/{0}/execute";
     string resourcePath = SDKUtil.FormatURIPath(pattern, parameters);
     string payLoad = paymentExecution.ConvertToJson();
     return PayPalResource.ConfigureAndExecute<Payment>(apiContext, HttpMethod.POST, resourcePath, payLoad);
 }
Example #33
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);
            }
        }