Ejemplo n.º 1
0
        public ActionResult paypal_confirmation(Int32 id = 0)
        {
            // Get the payer id
            string payerId = "";
            if (Request.Params["PayerID"] != null)
            {
                payerId = Server.UrlDecode(Request.Params["PayerID"]);
            }

            // Get the order
            Order order = Order.GetOneById(id);

            // Make sure that the order not is null
            if(order == null)
            {
                // Redirect the user to the order confirmation page
                return RedirectToAction("index", "home");
            }

            // Get the webshop settings
            KeyStringList webshopSettings = WebshopSetting.GetAllFromCache();

            // Get credentials
            string paypalClientId = webshopSettings.Get("PAYPAL-CLIENT-ID");
            string paypalClientSecret = webshopSettings.Get("PAYPAL-CLIENT-SECRET");
            string paypalMode = webshopSettings.Get("PAYPAL-MODE");
            Dictionary<string, string> config = new Dictionary<string, string> { { "mode", paypalMode } };

            // Create a error message
            string error_message = "";

            // Create a payment variable
            PayPal.Api.Payments.Payment createdPayment = null;

            try
            {
                // Create the credential token
                PayPal.OAuthTokenCredential tokenCredential = new PayPal.OAuthTokenCredential(paypalClientId, paypalClientSecret, config);

                // Create the api context
                PayPal.APIContext paypalContext = new PayPal.APIContext(tokenCredential.GetAccessToken());
                paypalContext.Config = config;

                // Get the payment
                PayPal.Api.Payments.Payment payment = PayPal.Api.Payments.Payment.Get(paypalContext, order.payment_token);

                // Create the payment excecution
                PayPal.Api.Payments.PaymentExecution paymentExecution = new PayPal.Api.Payments.PaymentExecution();
                paymentExecution.payer_id = payerId;
                paypalContext.HTTPHeaders = null;

                // Excecute the payment
                createdPayment = payment.Execute(paypalContext, paymentExecution);

            }
            catch (Exception ex)
            {
                error_message = ex.Message;
            }

            // Check if the created payment is different from null
            if (createdPayment != null && createdPayment.state == "approved")
            {
                // Get the sale id
                List<PayPal.Api.Payments.RelatedResources> resources = createdPayment.transactions[0].related_resources;

                // Save the paypal sale id
                Order.SetPaymentToken(order.id, resources[0].sale.id);

                // Update the order status
                Order.UpdatePaymentStatus(order.id, "payment_status_paid");

                // Add customer files
                CustomerFile.AddCustomerFiles(order);
            }

            // Redirect the user to the order confirmation page
            return RedirectToAction("confirmation", "order", new { id = id });

        } // End of the paypal_confirmation method
        public ActionResult ArgumentsSold(String id,      // your ID
                                          String token,   // PayPal token
                                          String PayerID)
        {
            String payment_id                   = String.Empty;
            String executeUrlFromCreatedPayment = String.Empty;
            // ................................
            //  ======>      // THINGS WE NEED TO USE THE PAYPAL REST API
            //  ======>      String argumentsPlusPayPalClentID = " ... your user ID for Arguments Plus ...";
            //  ======>      String argumentsPlusPayPalSecret  = " ... this is YOUR PASSWORD ...";
            String argumentsPlusPayPalClentID = "AU ... 6G"; // todo   ... your PayPal REST API SDK user ID
            String argumentsPlusPayPalSecret  = "EA ... -f"; // todo   ... your PayPal REST API SDK PASSWORD
            //  ======>      String payPalRestApiEndpoint      = "api.sandbox.paypal.com"; // For TESTING !!!
            //  ======>                                     // = "api.paypal.com";         // For LIVE    !!!
            Dictionary<String, String> sdkConfig = new Dictionary<String, String>();
            sdkConfig.Add("mode", "sandbox");
            // ................................
            // POTENTIAL POINT OF FAILURE
            // example:  "Exception in HttpConnection Execute: Invalid HTTP response The operation has timed out"
            String oAuthAccessTokenForPayPal = String.Empty; // scope outside of try/catch
            try
            {
                oAuthAccessTokenForPayPal = new PayPal.OAuthTokenCredential(argumentsPlusPayPalClentID,
                                                                            argumentsPlusPayPalSecret,
                                                                            sdkConfig).GetAccessToken();
            }                                                                      // .GetAccessToken takes us over to PayPal
            catch (Exception)
            {
                throw;  // todo ... make this code more robust
            }
            // ................................
            PayPal.APIContext apiContext = new PayPal.APIContext(oAuthAccessTokenForPayPal);
            apiContext.Config = sdkConfig;
            // ................................
            // id is our Guid for reconnecting to our customer's invoice
            PayPal.Api.Payments.Payment createdInvoice
                       = GetSavedPayPalInvoice(id);
            // ................................
            // now we convert the approved invoice into an actual payment
            PayPal.Api.Payments.Payment payment
                       = new PayPal.Api.Payments.Payment();
            payment.id = createdInvoice.id; // use the previously returned "invoice" identifier

            PayPal.Api.Payments.PaymentExecution askPayPalForMoney = new PayPal.Api.Payments.PaymentExecution();
            askPayPalForMoney.payer_id = PayerID; // from Query string ==> ?token=EC-3LN850372M719842K&PayerID=JJT6YSAZSFJTC
            PayPal.Api.Payments.Payment paidInvoice = null;  // scope outside of try/catch
            try
            {   //  an APPROVED PAYMENT morphs into a SALE !!!!!!!!!!!!!!!!!!!!!
                paidInvoice = payment.Execute(apiContext, askPayPalForMoney);  // off to PayPal
               		        // Here, if all has gone well, we're just right back from PayPal
                // and the money for the above invoice is now in our PayPal Merchant Account.
                ViewBag.PaidInvoice = paidInvoice;
             	}
            catch (PayPal.Exception.ConnectionException connectionExceptionPayPal)
            {
                if (String.Compare(connectionExceptionPayPal.Message,
                    "Invalid HTTP response The remote server returned an error: (400) Bad Request.")
                   == 0)
                {
                    String response_PAYMENT_STATE_INVALID =
                             "{\"name\":\"PAYMENT_STATE_INVALID\",\"message\":\"This request is invalid due to the current state of the payment\",\"information_link\":\"https://developer.paypal.com/webapps/developer/docs/api/#PAYMENT_STATE_INVALID\",\"debug_id\":\"";
                    Int32  response_PAYMENT_STATE_INVALID_Length = response_PAYMENT_STATE_INVALID.Length;
                    if (String.Compare(connectionExceptionPayPal.Response.Substring(0,response_PAYMENT_STATE_INVALID_Length),
                                       response_PAYMENT_STATE_INVALID) == 0)
                    {
                        // todo Take appropriate action
                    }
                    else
                    {
                        // todo Take appropriate action
                    }
                }
                else
                {
                    // todo Take appropriate action
                }
                throw;        // todo complete this code ... for PRODUCTION, more robustness is a must!
            }
             	catch (Exception generalExceptionGettingMoney)
             	{
             		throw;  // todo ... deal with this error appropriately ("throw" is not appropriate)
             	}
            // ................................
            // PayPal has provided data -- we capture as much or as little as when require.
            // We can save the PayPal data and/or display it on our web page, et cetera.
            // Remember:  respect your customers' privacy.  Protect their data.

            String payment_state    = String.Empty;       // N.B.:  this is NOT the province/state/region
            payment_state           = paidInvoice.state;  // Possible Values:  pending, approved
            ViewBag.Payment_State   = payment_state;

            String payment_intent   = String.Empty;
            payment_intent          = paidInvoice.intent;  // Expected Value:  "sale"
            ViewBag.Payment_Intent  = payment_intent;

            String payment_method   = String.Empty;
            payment_method          = paidInvoice.payer.payment_method;  // Expected Value:  "paypal"
            ViewBag.Payment_Method  = payment_method;

            String parent_payment = String.Empty;
            parent_payment          = paidInvoice.transactions[0].related_resources[0].sale.parent_payment;
            ViewBag.Parent_Payment  = parent_payment;

            String update_time      = String.Empty;
            update_time             = paidInvoice.update_time; // "2014-02-05T04:06:39Z"     string
            ViewBag.Update_Time     = update_time;

            String create_time      = String.Empty;
            create_time             = paidInvoice.create_time; // "2014-02-05T04:06:39Z"     string
            ViewBag.Create_Time     = create_time;

            // ................................
            String payPal_email_address  = String.Empty;  //  paidInvoice::email  "*****@*****.**"  string
            if (!String.IsNullOrWhiteSpace(paidInvoice.payer.payer_info.email))
                payPal_email_address     = paidInvoice.payer.payer_info.email;
            ViewBag.PayPal_Email_Address = payPal_email_address;

            String payPal_first_name     = String.Empty;  //  paidInvoice::first_name	"gerry"	string
            if (!String.IsNullOrWhiteSpace(paidInvoice.payer.payer_info.first_name))
                payPal_first_name        = paidInvoice.payer.payer_info.first_name;
            ViewBag.PayPal_First_Name    = payPal_first_name;

            String payPal_last_name      = String.Empty;  //  paidInvoice::last_name	"lowry"	string
            if (!String.IsNullOrWhiteSpace(paidInvoice.payer.payer_info.last_name))
                payPal_last_name         = paidInvoice.payer.payer_info.last_name;
            ViewBag.PayPal_Last_Name     = payPal_last_name;

            String payPal_phone  = String.Empty;  //  paidInvoice::phone null string
            if (!String.IsNullOrWhiteSpace(paidInvoice.payer.payer_info.phone))
                payPal_phone     = paidInvoice.payer.payer_info.phone;
            ViewBag.PayPal_Phone = payPal_phone;

            String payPal_city = String.Empty;  //  paidInvoice::city	"SAN Jose"	string
            if (!String.IsNullOrWhiteSpace(paidInvoice.payer.payer_info.shipping_address.city))
                payPal_city    = paidInvoice.payer.payer_info.shipping_address.city;
            ViewBag.City       = payPal_city;

            String payPal_country_code  = String.Empty;  //  paidInvoice::country_code	"US"	string
            if (!String.IsNullOrWhiteSpace(paidInvoice.payer.payer_info.shipping_address.country_code))
                payPal_country_code     = paidInvoice.payer.payer_info.shipping_address.country_code;
            ViewBag.PayPal_Country_Code = payPal_country_code;

            String payPal_address_line1  = String.Empty;  //  paidInvoice::line1	"1 Main St"	string
            if (!String.IsNullOrWhiteSpace(paidInvoice.payer.payer_info.shipping_address.line1))
                payPal_address_line1     = paidInvoice.payer.payer_info.shipping_address.line1;
            ViewBag.PayPal_Address_Line1 = payPal_address_line1;

            String payPal_address_line2  = String.Empty;  //  paidInvoice::line2	null	string
            if (!String.IsNullOrWhiteSpace(paidInvoice.payer.payer_info.shipping_address.line2))
                payPal_address_line2     = paidInvoice.payer.payer_info.shipping_address.line2;
            ViewBag.PayPal_Address_Line2 = payPal_address_line2;

            String payPal_postal_code  = String.Empty;  //  paidInvoice::postal_code	"95131"	string
            if (!String.IsNullOrWhiteSpace(paidInvoice.payer.payer_info.shipping_address.postal_code))
                payPal_postal_code     = paidInvoice.payer.payer_info.shipping_address.postal_code;
            ViewBag.PayPal_Postal_Code = payPal_postal_code;

            String payPal_address_state  = String.Empty;  //  paidInvoice::state	"CA"	string
            if (!String.IsNullOrWhiteSpace(paidInvoice.payer.payer_info.shipping_address.state))
                payPal_address_state     = paidInvoice.payer.payer_info.shipping_address.state;
            ViewBag.PayPal_Address_State = payPal_address_state;

            // ................................
            String payPal_transaction_amount_total  = String.Empty;  //  paidInvoice::transation[0].amount" string
            if (!String.IsNullOrWhiteSpace(paidInvoice.transactions[0].amount.total))
                payPal_transaction_amount_total     = paidInvoice.transactions[0].amount.total;
            ViewBag.PayPal_Transaction_Amount_Total = payPal_transaction_amount_total;

            String payPal_transaction_amount_currency  = String.Empty;  //  paidInvoice::transation[0].amount" string
            if (!String.IsNullOrWhiteSpace(paidInvoice.transactions[0].amount.total))
                payPal_transaction_amount_currency     = paidInvoice.transactions[0].amount.currency;
            ViewBag.PayPal_Transaction_Amount_Currency = payPal_transaction_amount_currency;

            String payPal_transaction_descripition = String.Empty;  //  paidInvoice::transation[0].amount" string
            if (!String.IsNullOrWhiteSpace(paidInvoice.transactions[0].amount.total))
                payPal_transaction_descripition = paidInvoice.transactions[0].description;
            ViewBag.PayPal_Transaction_Description = payPal_transaction_descripition;
            // ................................
            return View();
        }