示例#1
0
        public ActionResult RedirectFromPaypal(string tx)
        {
            PayPalResponse resp = GetPayPalResponse(tx, true);

            ViewBag.tx = resp;

            return(View(resp));
        }
        private void VerifyIpn(string requestBody) //HttpRequestMessage ipnRequest)//HttpRequestBase ipnRequest)
        {
            var verificationResponse = string.Empty;

            try
            {
                Debug.Assert(false, "TODO GET REQUEST URL");
                var verificationRequest = (HttpWebRequest)WebRequest.Create("https://www.sandbox.paypal.com/cgi-bin/webscr");

                //Set values for the verification request
                verificationRequest.Method      = "POST";
                verificationRequest.ContentType = "application/x-www-form-urlencoded";
                //   var param = Request.BinaryRead(ipnRequest.ContentLength);
                //   var strRequest = Encoding.ASCII.GetString(param);

                //Add cmd=_notify-validate to the payload
                requestBody = "cmd=_notify-validate&" + requestBody;
                verificationRequest.ContentLength = requestBody.Length;

                //Attach payload to the verification request
                var streamOut = new StreamWriter(verificationRequest.GetRequestStream(), Encoding.ASCII);
                streamOut.Write(requestBody);
                streamOut.Close();

                //Send the request to PayPal and get the response
                var streamIn = new StreamReader(verificationRequest.GetResponse().GetResponseStream());
                verificationResponse = streamIn.ReadToEnd();
                streamIn.Close();
                if (VeriFyPurchase(verificationResponse))
                {
                    PayPalResponse payPalResponse = this.DeserializeIpn(requestBody);
                    ProcessPayPalPurchase(payPalResponse);
                }
            }
            catch (Exception ex)
            {
                Debug.Assert(false, ex.Message);
                _logger.InsertError(ex.Message, "PaymentGateway", "ProcessPayPalIPN");
            }
        }
        private PayPalResponse DeserializeIpn(string response)
        {
            if (string.IsNullOrWhiteSpace(response))
            {
                return(null);
            }

            PayPalResponse res = new PayPalResponse();

            string[] kvp = response.Split('&');

            if (kvp.Length == 0)
            {
                return(null);
            }

            for (int i = 0; i < kvp.Length; i++)
            {
                try
                {
                    string[] tokens = kvp[i].Split('=');

                    if (tokens.Length < 2)
                    {
                        continue;
                    }

                    string key   = tokens[0].Trim().ToLower();
                    string value = tokens[1].Trim();

                    if (string.IsNullOrWhiteSpace(key) || string.IsNullOrWhiteSpace(value))
                    {
                        continue;
                    }
                    switch (key)
                    {
                    case "mc_gross": res.mc_gross = StringEx.ConvertTo <decimal>(value); break;

                    case "protection_eligibility": res.protection_eligibility = value; break;

                    case "address_status": res.address_status = value; break;

                    case "payer_id": res.payer_id = value; break;

                    case "tax": res.tax = StringEx.ConvertTo <decimal>(value); break;

                    case "address_street": res.address_street = value; break;

                    case "payment_date":   res.payment_date = value; break;

                    case "payment_status": res.payment_status = value; break;

                    case "charset":        res.charset = value; break;

                    case "address_zip":    res.address_zip = value; break;

                    case "first_name":     res.first_name = value; break;

                    case "mc_fee": res.mc_fee = StringEx.ConvertTo <decimal>(value); break;

                    case "address_country_code":        res.address_country_code = value; break;

                    case "address_name":   res.address_name = value; break;

                    case "notify_version": res.notify_version = StringEx.ConvertTo <float>(value); break;

                    case "custom": res.custom = value; break;           //this is set to the cartUUID, the Order has a cartUUID field. Pull the order and update all the tables. see StoreManager.ProcessPayment() to figure out all the tables to update

                    case "payer_status":   res.payer_status = value; break;

                    case "address_country": res.address_country = value; break;

                    case "address_city":   res.address_city = value; break;

                    case "quantity":       res.quantity = StringEx.ConvertTo <int>(value); break;

                    case "verify_sign":    res.verify_sign = value; break;

                    case "payer_email":    res.payer_email = value; break;

                    case "txn_id": res.txn_id = value; break;

                    case "payment_type":   res.payment_type = value; break;

                    case "last_name":      res.last_name = value; break;

                    case "address_state":  res.address_state = value; break;

                    case "receiver_email": res.receiver_email = value; break;

                    case "payment_fee":    res.payment_fee = StringEx.ConvertTo <decimal>(value); break;

                    case "receiver_id":    res.receiver_id = value; break;

                    case "txn_type":       res.txn_type = value; break;

                    case "item_name":      res.item_name = value; break;

                    case "mc_currency":    res.mc_currency = value; break;

                    case "item_number":    res.item_number = value; break;

                    case "residence_country": res.residence_country = value; break;

                    case "test_ipn":       res.test_ipn = value; break;

                    case "handling_amount": res.handling_amount = StringEx.ConvertTo <decimal>(value); break;

                    case "transaction_subject": res.transaction_subject = value; break;

                    case "payment_gross":  res.payment_gross = StringEx.ConvertTo <decimal>(value); break;

                    case "shipping": res.shipping = StringEx.ConvertTo <decimal>(value); break;
                    }
                }
                catch (Exception ex)
                {
                    Debug.Assert(false, ex.Message);
                    _logger.InsertError(ex.Message + " index:" + i.ToString() + " response:" + response, "PaymentGatewayManager", "DeserializeIpn");
                    continue;
                }
            }

            return(res);
        }
        private void ProcessPayPalPurchase(PayPalResponse ipnResponse)
        {
            if (ipnResponse == null)
            {
                return;
            }

            if (ipnResponse.payment_status?.ToLower() != "completed")
            {
                return;
            }
            try
            {
                using (var transactionScope = new TransactionScope())
                    using (var context = new GreenWerxDbContext(_dbConnectionKey))
                    {
                        Order o = context.GetAll <Order>()?.FirstOrDefault(w => w.CartUUID == ipnResponse.custom);

                        if (o == null)
                        { //  get order by shoppingCartUUID == ipnResponse.custom
                            Debug.Assert(false, "ORDER NOT FOUND");
                            _logger.InsertError("ORDER NOT FOUND custom value:" + ipnResponse.custom, "PaymentGateway", "ProcessPayPalPurchase");
                            return;
                        }

                        if (o.TransactionID == ipnResponse.txn_id)
                        { // check that Txn_id has not been previously processed
                            Debug.Assert(false, "TRANSACTION ALREADY PROCESSED");
                            _logger.InsertError("TRANSACTION ALREADY PROCESSED:" + ipnResponse.txn_id, "PaymentGateway", "ProcessPayPalPurchase");
                            return;
                        }

                        if (o.Total > ipnResponse.mc_gross)
                        {
                            // Debug.Assert(false, "UNDERPAYMENT RECIEVED");
                            o.PayStatus = LedgerFlag.Status.PaymentPartialRecieved;
                            _logger.InsertInfo("UNDERPAYMENT RECIEVED order uuid:" + o.UUID, "PaymentGateway", "ProcessPayPalPurchase");
                            // return;
                        }
                        if (o.Total < ipnResponse.mc_gross)
                        {
                            o.PayStatus = LedgerFlag.Status.OverPaymentReceived;
                            //Debug.Assert(false, "OVERPAYMENT RECIEVED");
                            _logger.InsertInfo("OVERPAYMENT RECIEVED order uuid:" + o.UUID, "PaymentGateway", "ProcessPayPalPurchase");
                            // return;
                        }
                        if (o.Total == ipnResponse.mc_gross)
                        {
                            o.PayStatus = LedgerFlag.Status.Paid;
                        }

                        FinanceAccount financeAccount = context.GetAll <FinanceAccount>()?.FirstOrDefault(w => w.UUID == o.FinancAccountUUID);

                        if (financeAccount == null)
                        {
                            Debug.Assert(false, "Unable to find finance account.");
                            _logger.InsertInfo("Unable to find finance account.:" + o.FinancAccountUUID, "PaymentGateway", "ProcessPayPalPurchase");
                            return;
                        }
                        var    app    = new AppManager(_dbConnectionKey, "web", "");
                        string secret = app.GetSetting("AppKey")?.Value;
                        var    email  = Cipher.Crypt(secret, ipnResponse.receiver_email.ToLower(), true);

                        if (financeAccount.Email != email)
                        { // check that Receiver_email is your Primary PayPal email
                            Debug.Assert(false, "Receiver_email doesn't match financeAccount Email");
                            _logger.InsertInfo("Receiver_email doesn't match financeAccount Email:" + email + ":" + financeAccount.Email, "PaymentGateway", "ProcessPayPalPurchase");
                            return;
                        }
                        Currency currency = context.GetAll <Currency>( )?.FirstOrDefault(w => w.UUID == o.CurrencyUUID);
                        if (currency == null)
                        {
                            Debug.Assert(false, "Unable to find currency .");
                            _logger.InsertInfo("Unable to find currency .:" + o.CurrencyUUID, "PaymentGateway", "ProcessPayPalPurchase");
                            return;
                        }
                        if (!currency.Code.EqualsIgnoreCase(ipnResponse.mc_currency))
                        {                    // check that mc_gross/mc_currency = USD are correct
                            Debug.Assert(false, "mc_currency doesn't match currency.Code");
                            _logger.InsertInfo("mc_currency doesn't match currency.Code:" + ipnResponse.mc_currency + ":" + currency.Code, "PaymentGateway", "ProcessPayPalPurchase");
                            return;
                        }

                        if (o.PayStatus == LedgerFlag.Status.Paid || o.PayStatus == LedgerFlag.Status.OverPaymentReceived)
                        {
                            List <OrderItem> orderItems = context.GetAll <OrderItem>()?.Where(w => w.OrderUUID == o.UUID).ToList();
                            foreach (OrderItem oi in orderItems)
                            {
                                oi.AccessGranted = true;
                                oi.AccessExpires = DateTime.UtcNow.AddDays(120); //todo make configurable.
                                context.Update <OrderItem>(oi);
                            }
                        }
                        //update order status to paid or complete etc.
                        FinanceAccountTransaction payment = new FinanceAccountTransaction()
                        {
                            AccountEmail = financeAccount.Email,
                            DateCreated  = DateTime.UtcNow,
                            Image        = financeAccount.Image,
                            CurrencyUUID = financeAccount.CurrencyUUID,
                            //CustomerIp = ipAddress,
                            CreationDate           = DateTime.Now,
                            LastPaymentStatusCheck = DateTime.UtcNow,
                            OrderUUID                = o.UUID,
                            Balance                  = o.Total - ipnResponse.mc_gross,
                            AmountTransferred        = 0,
                            TransactionDate          = DateTime.UtcNow,
                            TransactionType          = LedgerFlag.TransactionTypes.Credit,
                            Status                   = LedgerFlag.Status.PendingIncome,
                            SelectedPaymentTypeTotal = o.Total,
                            UserUUID                 = o.UserUUID,
                            //   PayFromAccountUUID = todo this is the customers account id. won't need it for now. we could also use it to set up accounts where users
                            //                          can order and be billed later.
                            FinanceAccountUUID        = financeAccount.UUID,
                            PayToAccountUUID          = financeAccount.AccountNumber, //todo this should be the store account",
                            PaymentTypeUUID           = "PayPal",
                            SelectedPaymentTypeSymbol = currency?.Symbol
                                                        //    // = affiliateId,
                        };
                        context.Insert <FinanceAccountTransaction>(payment);

                        transactionScope.Complete();
                    }
            }
            catch (Exception ex)
            {
                Debug.Assert(false, ex.Message);
                _logger.InsertError(ex.Message, "PaymentGateway", "ProcessPayPalPurchase");
            }
        }
示例#5
0
        public PayPalResponse GetPayPalResponse(string tx, bool useSandbox)
        {
            string authToken = "7tBnRytY2SmPuvY6LCoqZ4uqAivCP4zSr_kibkj34-Egd71IZUfvPwWHJB4";
            string txToken   = tx;
            string query     = "cmd=_notify-synch&tx=" + txToken + "&at=" + authToken;

            //Post back to either sandbox or live
            string strSandbox = "https://www.sandbox.paypal.com/cgi-bin/webscr";
            //string strLive = "https://www.paypal.com/cgi-bin/webscr";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strSandbox);

            //Set values for the request back
            req.Method        = "POST";
            req.ContentType   = "application/x-www-form-urlencoded";
            req.ContentLength = query.Length;

            ServicePointManager.Expect100Continue      = true;
            ServicePointManager.SecurityProtocol       = SecurityProtocolType.Tls12;
            ServicePointManager.DefaultConnectionLimit = 9999;


            //Send the request to PayPal and get the response
            StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);

            streamOut.Write(query);
            streamOut.Close();
            StreamReader streamIn    = new StreamReader(req.GetResponse().GetResponseStream());
            string       strResponse = streamIn.ReadToEnd();
            string       result      = string.Empty;

            streamIn.Close();

            PayPalResponse resp = new PayPalResponse();

            Dictionary <string, string> results = new Dictionary <string, string>();

            if (strResponse != "")
            {
                StringReader reader = new StringReader(strResponse);
                string       line   = reader.ReadLine();

                if (line == "SUCCESS")
                {
                    while ((line = reader.ReadLine()) != null)
                    {
                        results.Add(line.Split('=')[0], line.Split('=')[1]);
                    }

                    result  = "<p><h3>Your order has been received.</h3></p>";
                    result += "<b>Details</b><br>";
                    result += "<li>Name: " + results["first_name"] + " " + results["last_name"] + "</li>";
                    result += "<li>Item: " + results["item_name"] + "</li>";
                    result += "<li>Amount: " + results["payment_gross"] + "</li>";
                    result += "<li>Custom: " + results["custom"] + "</li>";
                    result += "<hr>";

                    resp = new PayPalResponse
                    {
                        item_number = results["item_number"],
                        amount      = results["payment_gross"],
                        currency    = results["mc_currency"],
                        custom      = results["custom"],
                        item_name   = results["item_name"],
                        tx          = tx
                    };
                }
                else if (line == "FAIL")
                {
                    // Log for manual investigation
                    Response.Write("Unable to retrive transaction detail");
                }
            }
            else
            {
                //unknown error
                Response.Write("ERROR");
            }


            return(resp);
        }
示例#6
0
        public ActionResult paypalprocess(PayPalResponse response)
        {
            var      mailbody      = new ExcellentMarketResearch.Models.PaymentGateway.Emailsending();
            string   paymentstatus = string.Empty;
            BuyingVM buy           = new BuyingVM();
            var      userdata      = (from b in db.BuyingInfoes
                                      where b.GuId == response.guid
                                      select b).FirstOrDefault();
            var userreport = (from r in db.ReportMasters
                              where r.ReportId == userdata.ReportId
                              select new { r.ReportTitle, r.ReportUrl }).FirstOrDefault();

            buy.Name        = userdata.Name;
            buy.ReportTitle = userreport.ReportTitle.ToString();
            buy.ReportUrl   = userreport.ReportUrl.ToString();
            buy.Company     = userdata.Company;
            buy.EmailId     = userdata.EmailId;
            buy.Country     = userdata.Country;
            buy.IPAddress   = userdata.IPAddress;
            buy.PhoneNumber = userdata.PhoneNumber;
            buy.Designation = userdata.Designation;


            var updatestatus = db.BuyingInfoes.Where(x => x.GuId == response.guid).FirstOrDefault();

            // b.PaymentTransaction = true;
            //updatestatus.PaymentTransaction = response.PaymentTransaction;
            updatestatus.PaymentStatus   = response.PaymentStatus;
            updatestatus.Intent          = response.Intent;
            updatestatus.PaymentId       = response.PaymentID;
            updatestatus.PayerId         = response.PAYERID;
            updatestatus.OrderId         = Convert.ToInt32(response.OrderID);
            updatestatus.Token           = response.TOKEN;
            updatestatus.ACK             = response.ACK;
            db.Entry(updatestatus).State = EntityState.Modified;
            db.SaveChanges();


            if (response.PaymentStatus == "Success")
            {
                paymentstatus = "dear admin, payment made for <br /><br />";

                //auto mailer
                objEmailsending.SendEmail("*****@*****.**", "sales", userdata.EmailId, "", "*****@*****.**", "Excellent Market Research :payment confirmation ", mailbody.GenerateMailBody_PaymentMade(paymentstatus, buy));

                //to company
                objEmailsending.SendEmail("*****@*****.**", userdata.Name, "*****@*****.**", "*****@*****.**", ".com", "Excellent Market Research " + " :payment confirmation(paypal) ", mailbody.GenerateMailBody_PaymentMade_AutoReply(userdata.Name.ToString(), userreport.ReportTitle.ToString()));

                return(Json(new
                {
                    msg = "sucess"
                          //return RedirectToAction("Index", "InquiryForm", new { reportid = ObjBuy.ReportId });
                }));
                // return RedirectToAction("sucess", "paymentprocess");
            }
            else if (response.PaymentStatus == "Cancel")
            {
                return(Json(new
                {
                    msg = "Cancel"
                          //return RedirectToAction("Index", "InquiryForm", new { reportid = ObjBuy.ReportId });
                }));
            }
            else
            {
                paymentstatus = "dear admin, payment canceled or unapproved for report<br /><br />";


                //to buyer
                objEmailsending.SendEmail("*****@*****.**", "sales", userdata.EmailId, "", "", "Excellent Market Research : " + " : payment cancel(pay pal)", mailbody.GenerateMailBody_PaypalError_AutoReply(buy.Name, buy.ReportTitle, buy.ReportUrl));

                //to company
                objEmailsending.SendEmail("*****@*****.**", userdata.Name, "*****@*****.**", "*****@*****.**", "", "Excellent Market Research" + " : payment cancel(pay pal)", mailbody.GenerateMailBody_PaypalError_AutoReply(userdata.Name.ToString(), userreport.ReportTitle.ToString(), userreport.ReportUrl.ToString()));

                return(Json(new
                {
                    msg = "failure"
                          //return RedirectToAction("Index", "InquiryForm", new { reportid = ObjBuy.ReportId });
                }));
                //return RedirectToAction("failure", "paymentprocess");
            }
        }
示例#7
0
		public PaymentResult (PaymentResultStatus status, string errorMessage = null, PayPalResponse serverResponse = null)
		{
			Status = status;
			ErrorMessage = errorMessage;
			ServerResponse = serverResponse;
		}