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.
        public ActionResult PaymentWithPayPal(string donationAmt)
        {          
            //OAuthTokenCredential tokenCredential = new OAuthTokenCredential("AeJs4Inwk1Pn8ZNhkWiSLwerx4K64E1PD5TtL4FF7XImtEZ29aAWBTxYOVIBWxEXlW6FycnBz3U7J8jQ", "ENerw7v3F1YT1w5YRYHRPCbjfVSpAbvHVTJFfqc0jWPyeq8hcgmvaZn-1T1WzklDVqw7Pd7MGp3KEQXO");
            //string accessToken = tokenCredential.GetAccessToken();

            // Get a reference to the config
            var config = ConfigManager.Instance.GetProperties();

            // Use OAuthTokenCredential to request an access token from PayPal
            var accessToken = new OAuthTokenCredential(config).GetAccessToken();
            var apiContext = new APIContext(accessToken);

            try
            {
                string payerId = Request.Params["PayerID"];
                Payment payment = null;

                if (string.IsNullOrEmpty(payerId))
                {

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

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

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

                    string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/Donations/DonationSuccessView?";

                    // # 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 = "0";
                    details.shipping = "0";
                    details.subtotal = donationAmt;

                    // ###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 = donationAmt + ".00";
                    amnt.details = details;

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

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

                    var createdPayment = payment.Create(apiContext);
                    string paypalRedirectUrl = null;
                    var links = createdPayment.links.GetEnumerator();
                    while (links.MoveNext())
                    {
                        Links lnk = links.Current;

                        if (lnk.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            //saving the payapalredirect URL to which user will be redirected for payment
                            paypalRedirectUrl = lnk.href;
                        }
                    }

                    // saving the paymentID in the key guid
                    Session.Add(guid, createdPayment.id);
                    return Redirect(paypalRedirectUrl);
                }
                else
                {
                    var guid = Request.Params["guid"];
                    var paymentId = Session[guid] as string;
                    var paymentExecution = new PaymentExecution() { payer_id = payerId };
                    var pymnt = new Payment() { id = paymentId };
                    var executedPayment = pymnt.Execute(apiContext, paymentExecution);
                }
            }
            catch (Exception e)
            {
                string error = e.ToString();
                return View("DonationFailureView");
            }
            return View("DonationSuccessView");
        }
        /// <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
                var base64ClientId = OAuthTokenCredential.ConvertClientCredentialsToBase64String(this.ClientId, this.ClientSecret);

                logger.DebugFormat("\n" +
                                   "  ClientID:       {0}\n" +
                                   "  ClientSecret:   {1}\n" +
                                   "  Base64ClientId: {2}", this.ClientId, this.ClientSecret, base64ClientId);

                this.accessToken = this.GenerateOAuthToken(base64ClientId);
            }
            return(this.accessToken);
        }
 public void OAuthTokenCredentialCtorNullValuesTest()
 {
     // If null values are passed in, OAuthTokenCredential uses the values specified in the config.
     var oauthTokenCredential = new OAuthTokenCredential(null, null, null);
     Assert.IsTrue(!string.IsNullOrEmpty(oauthTokenCredential.ClientId));
     Assert.IsTrue(!string.IsNullOrEmpty(oauthTokenCredential.ClientSecret));
 }
 public void OAuthTokenCredentialCtorEmptyConfigTest()
 {
     var config = new Dictionary<string, string>();
     var oauthTokenCredential = new OAuthTokenCredential(config);
     Assert.IsTrue(string.IsNullOrEmpty(oauthTokenCredential.ClientId));
     Assert.IsTrue(string.IsNullOrEmpty(oauthTokenCredential.ClientSecret));
 }
Example #5
0
 public PaypalProcessor()
 {
     // Authenticate with PayPal
     var config = ConfigManager.Instance.GetProperties();
     var accessToken = new OAuthTokenCredential(config).GetAccessToken();
     _apiContext = new APIContext(accessToken);
 }
        private static string GetAccessToken()
        {
            // getting accesstocken from paypal
            string accessToken = new OAuthTokenCredential(ClientId, ClientSecret, GetConfig()).GetAccessToken();

            return accessToken;
        }
Example #7
0
        private static string GetAccessToken()
        {
            // getting accesstocken from paypal
            string accessToken = new PayPal.Api.OAuthTokenCredential(ClientId, ClientSecret, GetConfig()).GetAccessToken();

            return(accessToken);
        }
Example #8
0
 public APIContext GetGetAPIContext()
 {
     var config = ConfigManager.Instance.GetProperties();
     string accessToken = new OAuthTokenCredential(config["clientId"], config["clientSecret"], config).GetAccessToken();
     APIContext apiContext = new APIContext(accessToken);
     apiContext.Config = config;
     return apiContext;
 }
 public void OAuthTokenCredentialCtorConfigTest()
 {
     var config = new Dictionary<string, string>();
     config[BaseConstants.ClientId] = "xxx";
     config[BaseConstants.ClientSecret] = "yyy";
     var oauthTokenCredential = new OAuthTokenCredential(config);
     Assert.AreEqual("xxx", oauthTokenCredential.ClientId);
     Assert.AreEqual("yyy", oauthTokenCredential.ClientSecret);
 }
 // 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 OAuthTokenCredentialGetAccessTokenTest()
        {
            try
            {
                var oauthTokenCredential = new OAuthTokenCredential();
                var accessToken = oauthTokenCredential.GetAccessToken();
                this.RecordConnectionDetails();

                Assert.IsTrue(accessToken.StartsWith("Bearer "));
            }
            catch(ConnectionException)
            {
                this.RecordConnectionDetails(false);
                throw;
            }
        }
Example #12
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PaypalWebHookReceiver"/> class.
 /// This constructor is intended for testing purposes.
 /// </summary>
 internal PaypalWebHookReceiver(bool initialize)
 {
     if (initialize)
     {
         try
         {
             _credentials = new OAuthTokenCredential();
             _config = ConfigManager.GetConfigWithDefaults(ConfigManager.Instance.GetProperties());
         }
         catch (Exception ex)
         {
             string msg = string.Format(CultureInfo.CurrentCulture, PaypalReceiverResources.Receiver_InitFailure, ex.Message);
             throw new InvalidOperationException(msg, ex);
         }
     }
 }
        protected override void RunSample()
        {
            string accessToken = new OAuthTokenCredential("EBWKjlELKMYqRNQ6sYvFo64FtaRLRR5BdHEESmha49TM", "EO422dn3gQLgDbuwqTjzrFgFtaRLRR5BdHEESmha49TM", Configuration.GetConfig()).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.
            // See [Configuration.cs](/Source/Configuration.html) to know more about APIContext.
            var apiContext = new APIContext(accessToken);

            var webhookId = "9XL90610J3647323C";

            // ^ Ignore workflow code segment
            #region Track Workflow
            this.flow.AddNewRequest("Verify received webhook event");
            #endregion

            // Construct a `VerifyWebhookSignature` and assign its properties from the headers received in your webhook event.
            var signatureVerification = new PayPal.Api.VerifyWebhookSignature
            {
                auth_algo = headers["Paypal-Auth-Algo"],
                cert_url = headers["Paypal-Cert-Url"],
                transmission_id = headers["Paypal-Transmission-Id"],
                transmission_sig = headers["Paypal-Transmission-Sig"],
                transmission_time = headers["Paypal-Transmission-Time"],
                webhook_id = webhookId,
                webhook_event = JsonFormatter.ConvertFromJson<WebhookEvent>(requestBody)
            };

            // ^ Ignore workflow code segment
            #region Track Workflow
            this.flow.AddNewRequest("Verify the received webhook Event", signatureVerification);
            #endregion

            // Call the `Post` method on your `VerifyWebhookSignature` object to verify the Webhook event was actually sent by PayPal.
            var signatureVerificationResponse = signatureVerification.Post(apiContext);

            // ^ Ignore workflow code segment
            #region Track Workflow
            this.flow.RecordResponse(signatureVerificationResponse);
            #endregion
        }
Example #14
0
 private static string GetAccessToken()
 {
     string accessToken = new OAuthTokenCredential(ClientId, ClientSecret, GetConfig()).GetAccessToken();
     return accessToken;
 }
        public ActionResult PaymentWithCreditCard()
        {
            //create and item for which you are taking payment
            //if you need to add more items in the list
            //Then you will need to create multiple item objects or use some loop to instantiate object
            Item item = new Item();
            item.name = "Item Name";
            item.currency = "USD";
            item.price = "1";
            item.quantity = "5";
            item.sku = "sku";

            //Now make a List of Item and add the above item to it
            //you can create as many items as you want and add to this list
            List<Item> itms = new List<Item>();
            itms.Add(item);
            ItemList itemList = new ItemList();
            itemList.items = itms;

            //Address for the payment
            PayPal.Api.Address billingAddress = new PayPal.Api.Address();
            billingAddress.city = "Milwaukee";
            billingAddress.country_code = "US";
            billingAddress.line1 = "1313 Mockingbird Lane";
            billingAddress.postal_code = "53201";
            billingAddress.state = "WI";

            //Now Create an object of credit card and add above details to it
            //Please replace your credit card details over here which you got from paypal
            CreditCard crdtCard = new CreditCard();
            crdtCard.billing_address = billingAddress;
            crdtCard.cvv2 = "874";  //card cvv2 number
            crdtCard.expire_month = 1; //card expire date
            crdtCard.expire_year = 2020; //card expire year
            crdtCard.first_name = "John";
            crdtCard.last_name = "Cena";
            crdtCard.number = "4876542318908756"; //enter your credit card number here
            crdtCard.type = "visa"; //credit card type here paypal allows 4 types

            // Specify details of your payment amount.
            Details details = new Details();
            details.shipping = "1";
            details.subtotal = "5";
            details.tax = "1";

            // Specify your total payment amount and assign the details object
            Amount amnt = new Amount();
            amnt.currency = "USD";
            // Total = shipping tax + subtotal.
            amnt.total = "7";
            amnt.details = details;

            // Now make a transaction object and assign the Amount object
            Transaction tran = new Transaction();
            tran.amount = amnt;
            tran.description = "Description about the payment amount.";
            tran.item_list = itemList;
            tran.invoice_number = "your invoice number which you are generating";

            // Now, we have to make a list of transaction and add the transactions object
            // to this list. You can create one or more object as per your requirements

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

            // Now we need to specify the FundingInstrument of the Payer
            // for credit card payments, set the CreditCard which we made above

            FundingInstrument fundInstrument = new FundingInstrument();
            fundInstrument.credit_card = crdtCard;

            // The Payment creation API requires a list of FundingIntrument

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

            // Now create Payer object and assign the fundinginstrument list to the object
            Payer payr = new Payer();
            payr.funding_instruments = fundingInstrumentList;
            payr.payment_method = "credit_card";

            // finally create the payment object and assign the payer object & transaction list to it
            Payment pymnt = new Payment();
            pymnt.intent = "sale";
            pymnt.payer = payr;
            pymnt.transactions = transactions;

            try
            {
                //getting context from the paypal
                //basically we are sending the clientID and clientSecret key in this function
                //to the get the context from the paypal API to make the payment
                //for which we have created the object above.

                //Basically, apiContext object has a accesstoken which is sent by the paypal
                //to authenticate the payment to facilitator account.
                //An access token could be an alphanumeric string

                // Get a reference to the config
                var config = ConfigManager.Instance.GetProperties();

                // Use OAuthTokenCredential to request an access token from PayPal
                var accessToken = new OAuthTokenCredential(config).GetAccessToken();
                var apiContext = new APIContext(accessToken);

                //Create is a Payment class function which actually sends the payment details
                //to the paypal API for the payment. The function is passed with the ApiContext
                //which we received above.

                Payment createdPayment = pymnt.Create(apiContext);

                //if the createdPayment.state is "approved" it means the payment was successful else not

                if (createdPayment.state.ToLower() != "approved")
                {
                    return View("FailureView");
                }
            }
            catch (PayPal.PayPalException e)
            {
                string error = e.ToString();
                return View("FailureView");
            }
            return View("SuccessView");
        }
Example #16
0
        /// <summary>
        /// ตัดบัตรเครดิต
        /// </summary>
        /// <param name="payment">ข้อมูลบัตรเครดิตที่ต้องการดำเนินการ</param>
        public PaymentResult ChargeCreditCard(PaymentInformation paymentInfo)
        {
            var tokenCredential = new OAuthTokenCredential(_appConfig.PaypalClientId, _appConfig.PaypalClientSecret, new Dictionary<string, string>());
            var accessToken = tokenCredential.GetAccessToken();
            var config = new Dictionary<string, string>();
            config.Add("mode", "sandbox"); // HACK: Paypal mode ('live' or 'sandbox')
            var apiContext = new APIContext
            {
                Config = config,
                AccessToken = accessToken
            };

            // A transaction defines the contract of a payment - what is the payment for and who is fulfilling it. 
            var transaction = new Transaction()
            {
                amount = new Amount()
                {
                    currency = "USD",
                    total = paymentInfo.TotalPrice.ToString(),
                    details = new Details()
                    {
                        shipping = "0",
                        subtotal = paymentInfo.TotalPrice.ToString(),
                        tax = "0"
                    }
                },
                description = $"User { paymentInfo.UserProfileId } pay { paymentInfo.TotalPrice.ToString("C2") } for course { paymentInfo.PurchaseForCourseId }",
            };

            // A resource representing a Payer that funds a payment.
            var payer = new Payer()
            {
                payment_method = "credit_card",
                funding_instruments = new List<FundingInstrument>()
                {
                    new FundingInstrument()
                    {
                        credit_card = new CreditCard()
                        {
                            billing_address = new Address()
                            {
                                city = paymentInfo.City,
                                country_code = paymentInfo.Country,
                                line1 = paymentInfo.Address,
                                postal_code = paymentInfo.PostalCode,
                                state = paymentInfo.State
                            },
                            cvv2 = paymentInfo.CVV,
                            expire_month = paymentInfo.ExpiredMonth,
                            expire_year = paymentInfo.ExpiredYear,
                            first_name = paymentInfo.FirstName,
                            last_name = paymentInfo.LastName,
                            number = paymentInfo.CreditCardNumber,
                            type = paymentInfo.CardType.ToLower()
                        }
                     }
                },
                payer_info = new PayerInfo { email = paymentInfo.UserProfileId }
            };

            // A Payment resource; create one using the above types and intent as `sale` or `authorize`
            var payment = new PayPal.Api.Payment()
            {
                intent = "sale",
                payer = payer,
                transactions = new List<Transaction>() { transaction }
            };

            // Create a payment using a valid APIContext
            var createdPayment = payment.Create(apiContext);
            var result = PaymentResult.Unknow;
            return Enum.TryParse<PaymentResult>(createdPayment.state, out result) ? result : PaymentResult.Unknow;
        }
 // Authenticate with PayPal
 public static APIContext GetAPIContext()
 {
     var config = ConfigManager.Instance.GetProperties();
     var accessToken = new OAuthTokenCredential(config).GetAccessToken();
     return new APIContext(accessToken);
 }
Example #18
0
 private APIContext CreatePaypalContext()
 {
     var config = ConfigManager.Instance.GetProperties();
     var accessToken = new OAuthTokenCredential(config).GetAccessToken();
     return new APIContext(accessToken);
 }
 public void OAuthTokenCredentialCtorClientInfoTest()
 {
     var oauthTokenCredential = new OAuthTokenCredential("aaa", "bbb");
     Assert.AreEqual("aaa", oauthTokenCredential.ClientId);
     Assert.AreEqual("bbb", oauthTokenCredential.ClientSecret);
 }
Example #20
0
        protected void btnPaypal_Click(object sender, EventArgs e)
        {
            // Get a reference to the config
            var config = ConfigManager.Instance.GetProperties();

            var accessToken = new OAuthTokenCredential(config).GetAccessToken();
            Response.Write(accessToken);

            var apiContext = new APIContext(accessToken);
            // Initialize the apiContext's configuration with the default configuration for this application.
            apiContext.Config = ConfigManager.Instance.GetProperties();

            // Define any custom configuration settings for calls that will use this object.
            apiContext.Config["connectionTimeout"] = "1000"; // Quick timeout for testing purposes

            // Define any HTTP headers to be used in HTTP requests made with this APIContext object
            if (apiContext.HTTPHeaders == null)
            {
                apiContext.HTTPHeaders = new Dictionary<string, string>();
            }
            apiContext.HTTPHeaders["some-header-name"] = "some-value";
        }
 public void OAuthTokenCredentialInvalidClientIdTest()
 {
     try
     {
         var config = ConfigManager.Instance.GetProperties();
         config[BaseConstants.ClientId] = "abc";
         var oauthTokenCredential = new OAuthTokenCredential(config);
         TestingUtil.AssertThrownException<IdentityException>(() => oauthTokenCredential.GetAccessToken());
         this.RecordConnectionDetails();
     }
     catch (ConnectionException)
     {
         this.RecordConnectionDetails(false);
         throw;
     }
 }
 private string GetAccessToken()
 {
     var accessToken = new OAuthTokenCredential(_clientId, _clientSecret, GetConfig()).GetAccessToken();
     return accessToken;
 }
        // api/Payment
        /// <summary>
        /// Verify that payment was successful with PayPal. If successful, use Connector
        /// to connect to DB. Formulate insert statement to pass to DB to store transaction.
        /// Send purchase email to Willie's Cycles. Formulate delete statement to pass to DB to delete part.
        /// </summary>
        /// <param name="year">The year of the part.</param>
        /// <param name="make">The make of the part.</param>
        /// <param name="model">The model of the part.</param>
        /// <param name="partName">The name of the part.</param>
        /// <param name="location">The location of the part.</param>
        /// <param name="pkParts">The ID of the part.</param>
        /// <param name="price">The price of the part.</param>
        /// <param name="transaction">The transaction information as JSON.</param>
        /// <param name="modify">A boolean int indicating whether database should be modified.</param>
        /// <param name="token">The private key.</param>
        /// <returns>A string indicating success or the cause of failure.</returns>
        public string GetPerformPurchase(string year, string make, string model, string partName,
            string location, int pkParts, string price, string transaction, int modify, string token)
        {
            if (!token.Equals(key))
            {
                return "token";
            }
            else
            {
                try
                {
                    dynamic json = JObject.Parse(transaction);
                    string paymentId = json.response.id;

                    var config = ConfigManager.Instance.GetProperties();
                    var accessToken = new OAuthTokenCredential(config).GetAccessToken();
                    var apiContext = new APIContext(accessToken);
                    var payment = Payment.Get(apiContext, paymentId);

                    var paymentString = payment.ConvertToJson();
                    dynamic paymentJson = JObject.Parse(payment.ConvertToJson());
                    string state = paymentJson.state;
                    double amount = paymentJson.transactions[0].related_resources[0].sale.amount.total;
                    string saleState = paymentJson.transactions[0].related_resources[0].sale.state;

                    if (state.Equals("approved") && saleState.Equals("completed") && amount == double.Parse(price.Trim()))
                    {
                        var formattedMake = "";
                        if (make != null && make.Trim().Length > 0)
                        {
                            formattedMake = make.Substring(0, 1);
                        }
                        if (model != null && model.Trim().Length > 0)
                        {
                            formattedMake = formattedMake + "-" + model;
                        }

                        var queryPartName = partName;
                        if (queryPartName != null && queryPartName.Contains("'"))
                        {
                            queryPartName = queryPartName.Replace("'", "''");
                        }

                        if (modify == 0)
                        {
                            bool emailSuccess = sendEmail(year, formattedMake, queryPartName,
                                    location, pkParts, double.Parse(price.Trim()), paymentId);

                            if (emailSuccess)
                            {
                                return "Successfully sent email!";
                            }
                            else
                            {
                                return "Failed to send email.";
                            }
                        }
                        else
                        {
                            Connector connector = new Connector();
                            bool insertSuccess = connector.Insert("INSERT INTO Transactions (YR, Make, PartName, Location, pkParts, Price, PaymentID) "
                                + " VALUES (\'" + year + "\',\'" + formattedMake + "\',\'" + queryPartName + "\'"
                                + ",\'" + location + "\'," + pkParts + ",\'" + price + "\',\'" + paymentId + "\')");

                            if (insertSuccess)
                            {
                                bool emailSuccess = sendEmail(year, formattedMake, partName,
                                    location, pkParts, double.Parse(price.Trim()), paymentId);

                                if (emailSuccess)
                                {
                                    bool deleteSuccess = connector.Delete("DELETE FROM Parts WHERE pkParts = " + pkParts);

                                    if (deleteSuccess)
                                    {
                                        return "Successfully sent email and modified database!";
                                    }
                                    else
                                    {
                                        return "Failed to delete.";
                                    }
                                }
                                else
                                {
                                    return "Failed to send email.";
                                }
                            }
                            else
                            {
                                return "Failed to Insert";
                            }
                        }
                    }
                    else
                    {
                        return "Payment Values Bad";
                    }
                }
                catch (Exception e)
                {
                    return "Exception";
                }
            }
        }
Example #24
0
 private   APIContext getPaypalContext()
 {
     Dictionary<string, string> configurationPayment = new Dictionary<string, string>();
     configurationPayment.Add("mode", IsPayPalSandBox ? "sandbox" : "live");
     OAuthTokenCredential tokenCredential = new OAuthTokenCredential(clientId, Secret, configurationPayment);
     var api = new APIContext(tokenCredential.GetAccessToken());
     api.Config = configurationPayment;
     return api;
 }
 private static string GetAccessToken()
 {
     // getting accesstocken from paypal
     /*                string accessToken = new OAuthTokenCredential
                 (ClientId, ClientSecret, GetConfig()).GetAccessToken();
                     var config = ConfigManager.Instance.GetProperties();
                     return accessToken;*/
     var config = ConfigManager.Instance.GetProperties();
     var accessToken = new OAuthTokenCredential(config).GetAccessToken();
     return accessToken;
 }
Example #26
0
        public IHttpActionResult GetPaymentApproved(string paymentId, string token, string PayerId,string userId)
        {
            var config = ConfigManager.Instance.GetProperties();
            var accessToken = new OAuthTokenCredential(config).GetAccessToken();
            var apiContext = new APIContext(accessToken);

            apiContext.Config = config;

            Payment payment = Payment.Get(apiContext, paymentId);

            PaymentExecution paymentExecution = new PaymentExecution();
            paymentExecution.payer_id = PayerId;

            try
            {
                Payment executedPayment = payment.Execute(apiContext, paymentExecution); //this PAYLEMT (EXECUTE) CAN FAIL
                if(executedPayment.state != "approved")
                {
                    return BadRequest("PayPal payment has failed. Please try again!");
                }
            }
            catch
            {
                return BadRequest("PayPal payment failed!");
            }

            
            //Set unpaid rooms to paid

            List<RoomAvailability> listOfUnpaidRooms = new List<RoomAvailability>();
            List<ReservationsPaymentAPI> listOfUnpaidRoomsFullDetails = new List<ReservationsPaymentAPI>();
            if (userId != null)
            {
                listOfUnpaidRooms = db.RoomAvailabilities.Where(x => x.UserId == userId && x.IsPaid == false).ToList();
            }
            if (listOfUnpaidRooms.Count > 0)
            {
                foreach (var room in listOfUnpaidRooms)
                {
                    room.IsPaid = true;
                    room.PayPalPaymentId = paymentId;
                    db.Entry(room).State = System.Data.Entity.EntityState.Modified;
                }
            }
            db.SaveChanges();

            string returnUrl = String.Format("http://{0}{1}", HttpContext.Current.Request.Url.Authority, "/#/paymentConfirmation");

            return Redirect(returnUrl);
        }
 /// <summary>
 /// Help method which createxs apicontext 
 /// from token which paypal returned us
 /// </summary>
 /// <returns>created api context</returns>
 private APIContext GetApiContext()
 {
     try
     {
         var config = ConfigManager.Instance.GetProperties();
         var accessToken = new OAuthTokenCredential(config).GetAccessToken();
         var apiContext = new APIContext(accessToken);
         apiContext.Config = config;
         return apiContext;
     }
     catch
     {
         return null;
     }
 }
Example #28
0
        public IHttpActionResult PostCreatePayment([FromBody]PayPalPaymentConfirmation model)
        {
            var userName = this.User.Identity.Name;

            string userId = "";

            try
            {
                userId = db.Users.SingleOrDefault(x => x.Email == userName).Id;
            }
            catch
            {
                return BadRequest("Unregistered user");
            }

            List<RoomAvailability> listOfUnpaidRooms = new List<RoomAvailability>();
            List<ReservationsPaymentAPI> listOfUnpaidRoomsFullDetails = new List<ReservationsPaymentAPI>();
            if (userId != null)
            {
                listOfUnpaidRooms = db.RoomAvailabilities.Where(x => x.UserId == userId && x.IsPaid == false).ToList();
            }
            if (listOfUnpaidRooms.Count > 0)
            {
                foreach (var room in listOfUnpaidRooms)
                {
                    string accomodationName = db.Accomodations.Single(x => x.AccomodationId == room.AccomodationId).AccomodationName;
                    string roomName = db.Rooms.Single(x => x.RoomId == room.RoomId).RoomType.RoomTypeName;

                    listOfUnpaidRoomsFullDetails.Add(new ReservationsPaymentAPI 
                    { 
                        AccommodationName =  accomodationName,
                        RoomName = roomName,
                        AccomodationId = room.AccomodationId,
                        ArrivalDate = room.ArrivalDate,
                        DepartureDate = room.DepartureDate,
                        IsPaid = room.IsPaid,
                        RoomAvailabilityId = room.RoomAvailabilityId,
                        RoomId = room.RoomId,
                        TotalPrice = room.TotalPrice,
                        UserId = room.UserId,
                        UserEmail = userName
                    });
                }
            }

            //BEGIN OF PAYPAL PAYMENT

            var config = ConfigManager.Instance.GetProperties();
            var accessToken = new OAuthTokenCredential(config).GetAccessToken();
            var apiContext = new APIContext(accessToken);
            apiContext.Config = config;
            Amount amount = new Amount();

            amount.total = listOfUnpaidRoomsFullDetails.Sum(x => x.TotalPrice).ToString();
            amount.currency = "USD";

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

            List<Item> listOfRoomsToPay = new List<Item>();
            foreach(var room in listOfUnpaidRoomsFullDetails)
            {
                listOfRoomsToPay.Add(new Item
                {
                    name = room.RoomName,
                    description = room.AccommodationName,
                    quantity = "1",
                    price = room.TotalPrice.ToString(),
                    currency = "USD"
                });
            }


            transaction.item_list.items.AddRange(listOfRoomsToPay);

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

            Payment payment = new Payment();
            payment.intent = "sale";
            payment.payer = payer;
            payment.transactions = new List<Transaction>();
            payment.transactions.Add(transaction);
            payment.redirect_urls = new RedirectUrls();
            payment.redirect_urls.return_url = String.Format("http://{0}{1}", HttpContext.Current.Request.Url.Authority, "/api/PayPal?userId=" + userId);
            payment.redirect_urls.cancel_url = String.Format("http://{0}{1}", HttpContext.Current.Request.Url.Authority, "/api/PayPal");
  
            Payment createdPayment = payment.Create(apiContext);

            return Ok(createdPayment.GetApprovalUrl());
        }
Example #29
0
        public override PaymentResponse MakePayment()
        {
            try
            {
                #region Create Payment
                ServicePointManager.Expect100Continue = true;
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                ServicePointManager.DefaultConnectionLimit = 9999;

                var config = ConfigManager.Instance.GetProperties();
                var accessToken = new OAuthTokenCredential(config).GetAccessToken();

                var apiContext = new APIContext(accessToken);
                apiContext.Config = ConfigManager.Instance.GetProperties();
                apiContext.Config["connectionTimeout"] = "30000";
                if (apiContext.HTTPHeaders == null)
                {
                    apiContext.HTTPHeaders = new Dictionary<string, string>();
                }
                //apiContext.HTTPHeaders["some-header-name"] = "some-value";

                string payerId = this.PayerId;
                if (string.IsNullOrEmpty(payerId))
                {
                    // ###Items
                    // Items within a transaction.
                    var itemList = new ItemList()
                    {
                        items = new List<Item>()
                    {
                        new Item()
                        {
                            name = CompanyConfigurationSettings.CompanyConfigList.Find(cc => cc.Name.Equals(System.Configuration.ConfigurationSettings.AppSettings["creditsHero_PayPal:TransactionTitle"])).Value != null
                            ? CompanyConfigurationSettings.CompanyConfigList.Find(cc => cc.Name.Equals(System.Configuration.ConfigurationSettings.AppSettings["creditsHero_PayPal:TransactionTitle"])).Value
                            : "Credits",
                            currency = "USD",
                            price = this.Amount.ToString(),
                            quantity = "1",
                            sku = CompanyConfigurationSettings.CompanyConfigList.Find(cc => cc.Name.Equals(System.Configuration.ConfigurationSettings.AppSettings["creditsHero_PayPal:TransactionTitle"])).Value != null
                            ? CompanyConfigurationSettings.CompanyConfigList.Find(cc => cc.Name.Equals(System.Configuration.ConfigurationSettings.AppSettings["creditsHero_PayPal:TransactionTitle"])).Value
                            : "Credits"
                        }
                    }
                    };

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

                    // ###Redirect URLS
                    // These URLs will determine how the user is redirected from PayPal once they have either approved or canceled the payment.
                    //var baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/PaymentWithPayPal.aspx?";
                    var baseURI = CompanyConfigurationSettings.CompanyConfigList.Find(cc => cc.Name.Equals(System.Configuration.ConfigurationSettings.AppSettings["creditsHero_PayPal:ReturnUrl"])).Value != null
                            ? CompanyConfigurationSettings.CompanyConfigList.Find(cc => cc.Name.Equals(System.Configuration.ConfigurationSettings.AppSettings["creditsHero_PayPal:ReturnUrl"])).Value
                            : "http://www.thedesignheroes.com/PaymentWithPayPal.aspx?";
                    var guid = Convert.ToString((new Random()).Next(100000));
                    var redirectUrl = baseURI + "guid=" + guid;
                    var redirUrls = new RedirectUrls()
                    {
                        cancel_url = redirectUrl + "&cancel=true",
                        return_url = redirectUrl
                    };

                    // ###Details
                    // Let's you specify details of a payment amount.
                    var details = new Details()
                    {
                        tax = this.TaxAmount.ToString(),
                        shipping = "0",
                        subtotal = this.Amount.ToString()
                    };

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

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

                    // The Payment creation API requires a list of
                    // Transaction; add the created `Transaction`
                    // to a List
                    transactionList.Add(new Transaction()
                    {
                        description = "Transaction description.",
                        invoice_number = String.Format(String.Format("{0}:{1}", this.CompanyId.ToString(), guid)),
                        amount = amount,
                        item_list = itemList
                    });

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

                    // ^ Ignore workflow code segment
                    #region Track Workflow
                    //this.flow.AddNewRequest("Create PayPal payment", payment);
                    #endregion

                    // Create a payment using a valid APIContext
                    var createdPayment = payment.Create(apiContext);

                    // ^ Ignore workflow code segment
                    #region Track Workflow
                    //this.flow.RecordResponse(createdPayment);
                    #endregion

                    // Using the `links` provided by the `createdPayment` object, we can give the user the option to redirect to PayPal to approve the payment.
                    var links = createdPayment.links.GetEnumerator();
                    string responseLink = "";
                    while (links.MoveNext())
                    {
                        var link = links.Current;
                        if (link.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            responseLink = link.href;
                            //this.flow.RecordRedirectUrl("Redirect to PayPal to approve the payment...", link.href);
                        }
                    }
                    //Session.Add(guid, createdPayment.id);
                    //Session.Add("flow-" + guid, this.flow);
                    #endregion

                    return new PaymentResponse()
                    {
                        AuthCode = createdPayment.state,// executePayment.token,
                        Message = createdPayment.token, // executePayment.state,
                        MessageCode = createdPayment.intent,
                        ResponseCode = responseLink,
                        TransactionId = guid,
                        TransactionResult = createdPayment.state
                    };
                }
                else
                {
                    #region Execute Payment
                    //var guid = Request.Params["guid"];

                    // ^ Ignore workflow code segment
                    #region Track Workflow
                    //this.flow = Session["flow-" + guid] as RequestFlow;
                    //this.RegisterSampleRequestFlow();
                    //this.flow.RecordApproval("PayPal payment approved successfully.");
                    #endregion

                    // Using the information from the redirect, setup the payment to execute.
                    var paymentId = this.PaymentGuid;
                    var paymentExecution = new PaymentExecution() { payer_id = payerId };
                    var payment = new PayPal.Api.Payment() { id = this.PaymentId };

                    // ^ Ignore workflow code segment
                    #region Track Workflow
                    //this.flow.AddNewRequest("Execute PayPal payment", payment);
                    #endregion

                    // Execute the payment.
                    var executedPayment = payment.Execute(apiContext, paymentExecution);

                    // ^ Ignore workflow code segment
                    #region Track Workflow
                    //this.flow.RecordResponse(executedPayment);
                    #endregion
                    #endregion

                    return new PaymentResponse()
                    {
                        AuthCode = executedPayment.cart,
                        Message = executedPayment.payer.status,
                        MessageCode = executedPayment.intent,
                        ResponseCode = executedPayment.links[0].href,
                        TransactionId = executedPayment.id,
                        TransactionResult = executedPayment.state,
                    };
                }
            }
            catch (System.Exception exc)
            {
                return new PaymentResponse()
                {
                    ErrorMessage = exc.Message,
                    Message = exc.StackTrace,
                    TransactionResult = String.Format("Paypal Error:{0}--{1}", exc.Message, exc.StackTrace)
                };
            }
        }
 public void OAuthTokenCredentialMissingClientSecretTest()
 {
     var config = ConfigManager.Instance.GetProperties();
     config[BaseConstants.ClientSecret] = "";
     var oauthTokenCredential = new OAuthTokenCredential(config);
     TestingUtil.AssertThrownException<MissingCredentialException>(() => oauthTokenCredential.GetAccessToken());
 }