public override bool HandleRequest( WorldPayPaymentResponse wpResponse, PayPalLog worldPayLog, Page page) { bool result = false; if (worldPayLog.SerializedObject.Length == 0) { return result; } Cart cart = (Cart)SerializationHelper.DeserializeFromString(typeof(Cart), worldPayLog.SerializedObject); Store store = new Store(cart.StoreGuid); //SiteSettings siteSettings = new SiteSettings(store.SiteGuid); config = SiteUtils.GetCommerceConfig(); switch (wpResponse.TransStatus) { case "Y": //success ProcessOrder(cart, store, wpResponse, worldPayLog, page); result = true; break; case "C": // cancelled default: ProcessCancellation(cart, store, wpResponse, worldPayLog, page); break; } return result; }
public void GetStatus(byte[] parameters) { //verify the transaction var status = Verify(true, parameters); if (status == "VERIFIED") { //check that the payment_status is Completed if (PayPalPaymentInfo.payment_status.ToLower() == "completed") { //check that txn_id has not been previously processed to prevent duplicates //check that receiver_email is your Primary PayPal email //check that payment_amount/payment_currency are correct //process payment/refund/etc } else if (status == "INVALID") { //log for manual investigation } else { PayPalLog.Debug(string.Format("Unknown status[{0}] {1}", status, JsonConvert.SerializeObject(PayPalPaymentInfo))); } } }
private void ProcessCancellation( Cart cart, Store store, WorldPayPaymentResponse wpResponse, PayPalLog worldPayLog, Page page) { //string serializedResponse = SerializationHelper.SerializeToString(wpResponse); //log.Info("received cancellation worldpay postback, xml to follow"); //log.Info(serializedResponse); // return an html order cancelled template for use at world pay if (config.WorldPayProduceShopperCancellationResponse) { string htmlTemplate = ResourceHelper.GetMessageTemplate(CultureInfo.CurrentUICulture, config.WorldPayShopperCancellationResponseTemplate); StringBuilder finalOutput = new StringBuilder(); finalOutput.Append(htmlTemplate); finalOutput.Replace("#WorldPayBannerToken", "<WPDISPLAY ITEM=banner>"); //required by worldpay finalOutput.Replace("#CustomerName", wpResponse.Name); finalOutput.Replace("#StoreName", store.Name); string storePageUrl = worldPayLog.RawResponse; finalOutput.Replace("#StorePageLink", "<a href='" + storePageUrl + "'>" + storePageUrl + "</a>"); page.Response.Write(finalOutput.ToString()); page.Response.Flush(); } }
/// <summary> /// This is really a fallback method, it will not be executed in normal use because we are setting the postbackurl of the button /// to post directly to paypal, so this method should not fire unless somehow the page is manipulated to postback to itself. /// In this case, we just consolidate the cart into a buy now button. /// </summary> private void DoPayPalStandardCheckout() { PayPalLog payPalLog = new PayPalLog(); payPalLog.ProviderName = "WebStorePayPalHandler"; payPalLog.PDTProviderName = "WebStorePayPalPDTHandlerProvider"; payPalLog.IPNProviderName = "WebStorePayPalIPNHandlerProvider"; payPalLog.ReturnUrl = SiteRoot + "/WebStore/OrderDetail.aspx?pageid=" + pageId.ToInvariantString() + "&mid=" + moduleId.ToInvariantString() + "&orderid=" + cart.CartGuid.ToString(); payPalLog.RequestType = "StandardCheckout"; cart.SerializeCartOffers(); payPalLog.SerializedObject = SerializationHelper.SerializeToString(cart); payPalLog.CartGuid = cart.CartGuid; payPalLog.SiteGuid = store.SiteGuid; payPalLog.StoreGuid = store.Guid; payPalLog.UserGuid = cart.UserGuid; payPalLog.CartTotal = cart.OrderTotal; payPalLog.CurrencyCode = siteSettings.GetCurrency().Code; payPalLog.Save(); string payPalStandardUrl = StoreHelper.GetBuyNowUrl( payPalLog.RowGuid, cart, store, commerceConfig); WebUtils.SetupRedirect(this, payPalStandardUrl); }
private async Task <PayPalLog> SavePaymentDetails(Payment payment, PayPalSuccessModel model) { var total = decimal.Parse(payment.transactions[0].amount.total, CultureInfo.InvariantCulture); var price = decimal.Parse(payment.transactions[0].item_list.items[0].price, CultureInfo.InvariantCulture); int.TryParse(payment.transactions[0].item_list.items[0].quantity, out var quantity); var payerInfo = payment.payer.payer_info; var shippingInfo = payerInfo.shipping_address; var payPalLog = new PayPalLog() { UserId = model.UserId, PayerId = model.PayerId, PaymentId = model.PaymentId, Total = total, Currency = "USD", Date = DateTime.Now, PayerFirstName = payerInfo.first_name, PayerLastName = payerInfo.last_name, PayerEmail = payerInfo.email, Item = "Donation Point", Price = price, Quantity = quantity, PayerPostalCode = shippingInfo.postal_code, PayerCity = shippingInfo.city }; await _websiteContext.PayPalLogs.AddAsync(payPalLog); await _websiteContext.SaveChangesAsync(); return(payPalLog); }
// GET: PayPal public ActionResult ProcessPaypalPayment(string userpackageID) { try { if (userpackageID == string.Empty) { return(View("Failure")); } else { int userpackage = Convert.ToInt32(userpackageID); var payment = db.UserPackages.Where(m => m.Id == userpackage).FirstOrDefault(); if (payment == null) { return(View("Failure")); } var finalPrice = payment.TotalPrice + payment.TaxAmount + payment.TipAmount; SetExpressCheckOut express = new SetExpressCheckOut(); PayPalSystem.Models.PaypalResponse response = new PayPalSystem.Models.PaypalResponse(); response = express.SetExpressCheckout(userpackageID, payment.AspNetUser.Email, "Car Cleaning Services", "Accept to Pay weekly", null, "GreenPro", Convert.ToDouble(finalPrice), payment.Package.Package_Name, Convert.ToDouble(finalPrice), payment.Package.Package_Description); string responseString = string.Empty; responseString = JsonConvert.SerializeObject(response); string text = "Paypal ProcessPaypalPayment ActionResult: " + DateTime.Now.ToString(); text += Environment.NewLine + Environment.NewLine + "responseFrom Paypal: " + responseString; string fileName = DateTime.Now.ToString("Response_" + userpackageID + "_" + "yyyy-MM-dd-HH-mm", CultureInfo.InvariantCulture) + ".txt"; System.IO.File.WriteAllText(Server.MapPath("~/App_Data/" + fileName), text); PayPalLog log = new PayPalLog() { UserId = User.Identity.GetUserId(), ACK = "Express", ApiSatus = response.ApiStatus, BillingAggrementID = (response.BillingAgreementID == null) ? string.Empty : response.BillingAgreementID, CorrelationID = response.CorrelationID, ECToken = response.ECToken, ResponseError = (response.ResponseError == null) ? string.Empty : response.ResponseError.ToString(), ResponseRedirectURL = (response.ResponseRedirectURL == null) ? string.Empty : response.ResponseRedirectURL, ServerDate = DateTime.Now, TimeStamp = response.Timestamp, SubscriptionID = payment.Id }; db.PayPalLogs.Add(log); db.SaveChanges(); if (response.ResponseRedirectURL != null) { Response.Redirect(response.ResponseRedirectURL); } } } catch (Exception ex) { throw ex.InnerException; } return(View()); }
public override bool HandleRequest( WorldPayPaymentResponse wpResponse, PayPalLog worldPayLog, Page page) { // do nothing return false; }
/// <summary> /// return true if the transaction was processed with no problems /// </summary> public override bool HandleRequest( string transactionId, NameValueCollection form, PayPalLog standardCheckoutLog) { // do nothing return false; }
public override bool HandleRequest( WorldPayPaymentResponse wpResponse, PayPalLog worldPayLog, Page page) { // do nothing return(false); }
/// <summary> /// return true if the transaction was processed with no problems /// </summary> public override bool HandleRequest( string transactionId, NameValueCollection form, PayPalLog standardCheckoutLog) { // do nothing return(false); }
public override string HandleRequestAndReturnUrlForRedirect( string rawResponse, StringDictionary pdtItems, string transactionId, PayPalLog standardCheckoutLog) { // do nothing return(string.Empty); }
public override string HandleRequestAndReturnUrlForRedirect( HttpContext context, string payPalToken, string payPalPayerId, PayPalLog setExpressCheckoutLog) { // do nothing return string.Empty; }
public override string HandleRequestAndReturnUrlForRedirect( HttpContext context, string payPalToken, string payPalPayerId, PayPalLog setExpressCheckoutLog) { // do nothing return(string.Empty); }
public override string HandleRequestAndReturnUrlForRedirect( string rawResponse, StringDictionary pdtItems, string transactionId, PayPalLog standardCheckoutLog) { // do nothing return string.Empty; }
private void SetupWorldPay() { if ((!Request.IsAuthenticated) && (!canCheckoutWithoutAuthentication)) { return; } if (commerceConfig.WorldPayInstallationId.Length == 0) { return; } if (cart.OrderTotal <= 0) { return; } pnlWorldPay.Visible = true; frmCardInput.Visible = false; heading.Text = WebStoreResources.WorldPayCheckoutHeader; worldPayAcceptanceMark.InstId = commerceConfig.WorldPayInstallationId; btnWorldPay.Text = WebStoreResources.ContinueButton; btnWorldPay.InstId = commerceConfig.WorldPayInstallationId; btnWorldPay.Md5Secret = commerceConfig.WorldPayMd5Secret; btnWorldPay.MerchantCode = commerceConfig.WorldPayMerchantCode; btnWorldPay.CurrencyCode = siteSettings.GetCurrency().Code; btnWorldPay.Amount = cart.OrderTotal; btnWorldPay.UseTestServer = commerceConfig.PaymentGatewayUseTestMode; btnWorldPay.OrderDescription = cart.GetStringOfCartOfferNames(); btnWorldPay.CustomerEmail = cart.OrderInfo.CustomerEmail; if ((cart.OrderInfo.CustomerFirstName.Length > 0) && (cart.OrderInfo.CustomerLastName.Length > 0)) { btnWorldPay.CustomerName = string.Format(CultureInfo.InvariantCulture, WebStoreResources.FirstNameLastNameFormat, cart.OrderInfo.CustomerFirstName, cart.OrderInfo.CustomerLastName); } btnWorldPay.Address1 = cart.OrderInfo.CustomerAddressLine1; btnWorldPay.Address2 = cart.OrderInfo.CustomerAddressLine2; btnWorldPay.Town = cart.OrderInfo.CustomerCity; btnWorldPay.Region = cart.OrderInfo.CustomerState; btnWorldPay.Country = cart.OrderInfo.CustomerCountry; btnWorldPay.PostalCode = cart.OrderInfo.CustomerPostalCode; btnWorldPay.CustomerPhone = cart.OrderInfo.CustomerTelephoneDay; PayPalLog worldPayLog = StoreHelper.EnsureWorldPayCheckoutLog( cart, store, SiteRoot, WebUtils.ResolveServerUrl(SiteUtils.GetCurrentPageUrl()), pageId, moduleId); // note that we actually pass the PayPalLog guid not the cart id // we then deserialize the cart form tha PayPsalLog to ensure it has not been modified // since the user left our site and went to WorldPay btnWorldPay.CartId = worldPayLog.RowGuid.ToString(); //btnWorldPay.CustomData = worldPayLog.RowGuid.ToString(); }
private void HandleRequest(HttpContext context) { if (payPalToken.Length == 0) { log.Info("invalid request no PayPalLog token provided"); SiteUtils.RedirectToDefault(); return; } PayPalLog setExpressCheckoutLog = PayPalLog.GetSetExpressCheckout(payPalToken); if (setExpressCheckoutLog == null) { log.Info("invalid request no PayPalLog found for token " + payPalToken); SiteUtils.RedirectToDefault(); return; } PayPalReturnHandlerProvider provider = null; string returnUrl = string.Empty; try { provider = PayPalReturnHandlerManager.Providers[setExpressCheckoutLog.ProviderName]; } catch (TypeInitializationException ex) { log.Error(ex); } if (provider != null) { returnUrl = provider.HandleRequestAndReturnUrlForRedirect( context, payPalToken, payPalPayerId, setExpressCheckoutLog); } else { log.Info("could not find PayPalReturnHandlerProvider " + setExpressCheckoutLog.ProviderName); } if (returnUrl.Length == 0) { log.Info("no return url determined so redirecting to site root"); returnUrl = SiteUtils.GetNavigationSiteRoot(); } context.Response.Redirect(returnUrl); }
public HttpResponseMessage Get() { try { return(Request.CreateResponse(HttpStatusCode.OK, PayPalLog.GetAll())); } catch (Exception ex) { return(Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message)); } }
public OrderRecord UpdateOrderStatus(PayPalPaymentInfo payPalPaymentInfo) { var order = GetOrderByNumber(payPalPaymentInfo.invoice); OrderStatus orderStatus; switch (payPalPaymentInfo.payment_status.ToLower()) { case "completed": orderStatus = OrderStatus.Paid; break; default: orderStatus = OrderStatus.Cancelled; break; } //if (order.Status == orderStatus) // return; order.Status = orderStatus; order.PaymentServiceProviderResponse = JsonConvert.SerializeObject(payPalPaymentInfo); order.PaymentReference = payPalPaymentInfo.txn_id; switch (order.Status) { case OrderStatus.Paid: order.PaidAt = _dateTimeService.Now; break; case OrderStatus.Completed: order.CompletedAt = _dateTimeService.Now; break; case OrderStatus.Cancelled: order.CancelledAt = _dateTimeService.Now; break; } //PayPalLog.Debug(JsonConvert.SerializeObject(order)); // _orderRepository.Update(order); PayPalLog.Debug("Updated"); return(order); }
private void HandleRequest(HttpContext context) { if (payPalToken.Length == 0) { SiteUtils.RedirectToDefault(); return; } PayPalLog setExpressCheckoutLog = PayPalLog.GetSetExpressCheckout(payPalToken); if (setExpressCheckoutLog == null) { SiteUtils.RedirectToDefault(); return; } PayPalReturnHandlerProvider provider = null; string returnUrl = string.Empty; try { provider = PayPalReturnHandlerManager.Providers[setExpressCheckoutLog.ProviderName]; } catch (TypeInitializationException ex) { log.Error(ex); } if (provider != null) { returnUrl = provider.HandleRequestAndReturnUrlForRedirect( context, payPalToken, payPalPayerId, setExpressCheckoutLog); } if (returnUrl.Length == 0) { returnUrl = SiteUtils.GetNavigationSiteRoot(); } context.Response.Redirect(returnUrl); }
private void SetupPayPalStandardForm() { PayPalLog payPalLog = StoreHelper.EnsurePayPalStandardCheckoutLog(cart, store, SiteRoot, pageId, moduleId); if (payPalLog == null) { // this shouldn't happen but if we don't have the log then hide the button btnPayPal.Visible = false; return; } litPayPalFormVariables.Text = StoreHelper.GetCartUploadFormFields( payPalLog.RowGuid, cart, store, commerceConfig); btnPayPal.PostBackUrl = commerceConfig.PayPalStandardUrl; }
public void LogTransaction(Guid siteGuid, Guid moduleGuid, Guid storeGuid, Guid cartGuid, Guid userGuid, string providerName, string method, string serializedCart) { PayPalLog payPalLog = new PayPalLog(); payPalLog.ProviderName = providerName; payPalLog.RawResponse = RawResponse; payPalLog.RequestType = "DirectPayment"; payPalLog.CartGuid = cartGuid; payPalLog.StoreGuid = storeGuid; payPalLog.UserGuid = userGuid; payPalLog.SiteGuid = siteGuid; payPalLog.PendingReason = ResponseReason; payPalLog.ReasonCode = ReasonCode; payPalLog.PaymentType = "CreditCard"; payPalLog.PaymentStatus = Response.ToString(); payPalLog.TransactionId = TransactionId; payPalLog.CartTotal = ChargeTotal; payPalLog.CurrencyCode = CurrencyCode; payPalLog.SerializedObject = serializedCart; payPalLog.Save(); }
private void SetupPayPalStandardForm() { if (cart == null) { return; } if (siteUser == null) { return; } if (cart.UserGuid == Guid.Empty) { cart.UserGuid = siteUser.UserGuid; cart.Save(); } if (cart.CartOffers.Count == 0) { litOr.Visible = false; btnPayPal.Visible = false; //btnGoogleCheckout.Visible = false; return; } PayPalLog payPalLog = StoreHelper.EnsurePayPalStandardCheckoutLog(cart, store, SiteRoot, pageId, moduleId); if (payPalLog == null) { return; } litPayPalFormVariables.Text = StoreHelper.GetCartUploadFormFields( payPalLog.RowGuid, cart, store, commerceConfig); btnPayPal.PostBackUrl = commerceConfig.PayPalStandardUrl; }
private void BindGrid() { if (cartGuid == Guid.Empty) { this.Visible = false; return; } using (IDataReader reader = PayPalLog.GetByCart(cartGuid)) { pgrCheckoutLog.Visible = false; grdCheckoutLog.PageIndex = pageNumber; grdCheckoutLog.PageSize = pageSize; grdCheckoutLog.DataSource = reader; grdCheckoutLog.DataBind(); } if (grdCheckoutLog.Rows.Count == 0) { this.Visible = false; } }
public HttpResponseMessage Get(string id) { try { switch (id.ToLowerInvariant()) { case "errors": return(Request.CreateResponse(HttpStatusCode.OK, PayPalLog.GetErrors())); case "debug": return(Request.CreateResponse(HttpStatusCode.OK, PayPalLog.GetDebug())); } return(Request.CreateResponse(HttpStatusCode.NoContent)); } catch (Exception ex) { return(Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message)); } }
public override bool HandleRequest( WorldPayPaymentResponse wpResponse, PayPalLog worldPayLog, Page page) { bool result = false; if (worldPayLog.SerializedObject.Length == 0) { return(result); } Cart cart = (Cart)SerializationHelper.DeserializeFromString(typeof(Cart), worldPayLog.SerializedObject); Store store = new Store(cart.StoreGuid); //SiteSettings siteSettings = new SiteSettings(store.SiteGuid); config = SiteUtils.GetCommerceConfig(); switch (wpResponse.TransStatus) { case "Y": //success ProcessOrder(cart, store, wpResponse, worldPayLog, page); result = true; break; case "C": // cancelled default: ProcessCancellation(cart, store, wpResponse, worldPayLog, page); break; } return(result); }
public override string HandleRequestAndReturnUrlForRedirect( string rawResponse, StringDictionary pdtItems, string transactionId, PayPalLog standardCheckoutLog) { string redirectUrl = string.Empty; if (standardCheckoutLog.SerializedObject.Length == 0) { return redirectUrl; } Cart cart = (Cart)SerializationHelper.DeserializeFromString(typeof(Cart), standardCheckoutLog.SerializedObject); Store store = new Store(cart.StoreGuid); bool debugPayPal = WebConfigSettings.DebugPayPal; string firstName = string.Empty; string lastName = string.Empty; string paymentStatus = string.Empty; string payerEmail = string.Empty; string currencyUsed = string.Empty; string paymentGross = string.Empty; string payPalFee = string.Empty; string payPalTax = string.Empty; string payPalShipping = string.Empty; string payPalSettlement = string.Empty; string pendingReason = string.Empty; string reasonCode = string.Empty; string paymentType = string.Empty; string customerAddress = string.Empty; string customerCity = string.Empty; string customerState = string.Empty; string customerPostalCode = string.Empty; string customerCountry = string.Empty; string customerPhone = string.Empty; string customerBusinessName = string.Empty; string customerMemo = string.Empty; if (pdtItems.ContainsKey("first_name")) { firstName = pdtItems["first_name"]; } if (pdtItems.ContainsKey("last_name")) { lastName = pdtItems["last_name"]; } if (pdtItems.ContainsKey("payment_status")) { paymentStatus = pdtItems["payment_status"]; } if (pdtItems.ContainsKey("payer_email")) { payerEmail = pdtItems["payer_email"]; } if (pdtItems.ContainsKey("mc_gross")) { paymentGross = pdtItems["mc_gross"]; } if (pdtItems.ContainsKey("mc_fee")) { payPalFee = pdtItems["mc_fee"]; } if (pdtItems.ContainsKey("tax")) { payPalTax = pdtItems["tax"]; } if (pdtItems.ContainsKey("shipping")) { payPalShipping = pdtItems["shipping"]; } if (pdtItems.ContainsKey("mc_currency")) { currencyUsed = pdtItems["mc_currency"]; } if (pdtItems.ContainsKey("pending_reason")) { pendingReason = pdtItems["pending_reason"]; } if (pdtItems.ContainsKey("reason_code")) { reasonCode = pdtItems["reason_code"]; } if (pdtItems.ContainsKey("txn_type")) { paymentType = pdtItems["txn_type"]; } if (pdtItems.ContainsKey("settle_amount")) { payPalSettlement = pdtItems["settle_amount"]; } if (pdtItems.ContainsKey("address_street")) { customerAddress = pdtItems["address_street"]; } if (pdtItems.ContainsKey("address_city")) { customerCity = pdtItems["address_city"]; } if (pdtItems.ContainsKey("address_state")) { customerState = pdtItems["address_state"]; } if (pdtItems.ContainsKey("address_zip")) { customerPostalCode = pdtItems["address_zip"]; } if (pdtItems.ContainsKey("address_country")) { customerCountry = pdtItems["address_country"]; } if (pdtItems.ContainsKey("contact_phone")) { customerPhone = pdtItems["contact_phone"]; } if (pdtItems.ContainsKey("payer_business_name")) { customerBusinessName = pdtItems["payer_business_name"]; } // TODO: we need to store this somewhere on the cart/order // its the message the user enters in special instructions on paypal checkout if (pdtItems.ContainsKey("memo")) { customerMemo = pdtItems["memo"]; } //Regardless of the specified currency, the format will have decimal point //with exactly two digits to the right and an optional thousands separator to the left, //which must be a comma; for example, EUR 2.000,00 must be specified as 2000.00 or 2,000.00 // So we want to parse it with US Culture CultureInfo currencyCulture = new CultureInfo("en-US"); //if (currencyUsed.Length > 0) //{ // currencyCulture = ResourceHelper.GetCurrencyCulture(currencyUsed); // if (debugPayPal) { log.Info("PayPal currencyUsed was " + currencyUsed); } //} //else //{ // SiteSettings siteSettings = new SiteSettings(store.SiteGuid); // //Currency currency = new Currency(store.DefaultCurrencyId); // //currencyCulture = ResourceHelper.GetCurrencyCulture(currency.Code); // Currency currency = siteSettings.GetCurrency(); // currencyCulture = ResourceHelper.GetCurrencyCulture(currency.Code); // currencyUsed = currency.Code; //} if (debugPayPal) { log.Info("PayPal rawResponse was " + rawResponse); } if (debugPayPal) { log.Info("PayPal final currency culture was " + currencyUsed); } decimal grossAmount = 0; decimal.TryParse(paymentGross, NumberStyles.Currency, currencyCulture, out grossAmount); decimal feeAmount = 0; decimal.TryParse(payPalFee, NumberStyles.Currency, currencyCulture, out feeAmount); decimal taxAmount = 0; decimal.TryParse(payPalTax, NumberStyles.Currency, currencyCulture, out taxAmount); decimal shippingAmount = 0; decimal.TryParse(payPalShipping, NumberStyles.Currency, currencyCulture, out shippingAmount); decimal settleAmount = 0; decimal.TryParse(payPalSettlement, NumberStyles.Currency, currencyCulture, out settleAmount); if (debugPayPal) { log.Info("PayPal paymentGross was " + paymentGross + " which was parsed as " + grossAmount.ToString()); log.Info("PayPal payPalFee was " + payPalFee + " which was parsed as " + feeAmount.ToString()); log.Info("PayPal payPalTax was " + payPalTax + " which was parsed as " + taxAmount.ToString()); log.Info("PayPal payPalShipping was " + payPalShipping + " which was parsed as " + shippingAmount.ToString()); log.Info("PayPal payPalSettlement was " + payPalSettlement + " which was parsed as " + settleAmount.ToString()); } PayPalLog payPalLog = new PayPalLog(); payPalLog.PDTProviderName = standardCheckoutLog.PDTProviderName; payPalLog.IPNProviderName = standardCheckoutLog.IPNProviderName; payPalLog.ReturnUrl = standardCheckoutLog.ReturnUrl; payPalLog.ProviderName = standardCheckoutLog.ProviderName; payPalLog.SiteGuid = standardCheckoutLog.SiteGuid; payPalLog.StoreGuid = standardCheckoutLog.StoreGuid; payPalLog.UserGuid = standardCheckoutLog.UserGuid; payPalLog.ApiVersion = standardCheckoutLog.ApiVersion; payPalLog.CartGuid = standardCheckoutLog.CartGuid; payPalLog.SerializedObject = standardCheckoutLog.SerializedObject; payPalLog.CartTotal = standardCheckoutLog.CartTotal; payPalLog.PayPalAmt = grossAmount; payPalLog.FeeAmt = feeAmount; if (settleAmount > 0) { payPalLog.SettleAmt = settleAmount; } else { payPalLog.SettleAmt = (grossAmount - feeAmount); } payPalLog.TaxAmt = taxAmount; payPalLog.CurrencyCode = currencyUsed; payPalLog.TransactionId = transactionId; payPalLog.RawResponse = rawResponse; payPalLog.Response = "PDTSuccess"; payPalLog.RequestType = "PDT"; payPalLog.PayerId = payerEmail; payPalLog.PaymentType = paymentType; payPalLog.PaymentStatus = paymentStatus; payPalLog.PendingReason = pendingReason; payPalLog.ReasonCode = reasonCode; payPalLog.Save(); // see if this cart has already been proceesed Order existingOrder = new Order(cart.CartGuid); // order already exists if (existingOrder.OrderGuid != Guid.Empty) { // lookup order status if needed make it fullfillable // then redirect to order detail page if (existingOrder.StatusGuid == OrderStatus.OrderStatusReceivedGuid) { if (paymentStatus == "Completed") { existingOrder.StatusGuid = OrderStatus.OrderStatusFulfillableGuid; existingOrder.Save(); try { StoreHelper.ConfirmOrder(store, existingOrder); GoogleCheckoutLog.DeleteByCart(existingOrder.OrderGuid); } catch (Exception ex) { log.Error("error sending confirmation email", ex); } } } // this was set in Checkout.aspx and should return to order detail page if (standardCheckoutLog.ReturnUrl.Length > 0) { redirectUrl = standardCheckoutLog.ReturnUrl; } payPalLog.ReasonCode = "existing order found"; payPalLog.Save(); return redirectUrl; } // if we get here the cart has not yet been processed into an order cart.DeSerializeCartOffers(); Guid orderStatus; if (paymentStatus == "Completed") { orderStatus = OrderStatus.OrderStatusFulfillableGuid; } else { orderStatus = OrderStatus.OrderStatusReceivedGuid; } // update the order with customer shipping info cart.OrderInfo.DeliveryCompany = customerBusinessName; cart.OrderInfo.DeliveryAddress1 = customerAddress; cart.OrderInfo.DeliveryCity = customerCity; cart.OrderInfo.DeliveryFirstName = firstName; cart.OrderInfo.DeliveryLastName = lastName; cart.OrderInfo.DeliveryPostalCode = customerPostalCode; cart.OrderInfo.DeliveryState = customerState; cart.OrderInfo.DeliveryCountry = customerCountry; if (customerPhone.Length > 0) { cart.OrderInfo.CustomerTelephoneDay = customerPhone; } if (payerEmail.Length > 0) { cart.OrderInfo.CustomerEmail = payerEmail; } cart.CopyShippingToBilling(); cart.CopyShippingToCustomer(); cart.TaxTotal = taxAmount; cart.OrderTotal = grossAmount; if (shippingAmount > 0) { cart.ShippingTotal = shippingAmount; } StoreHelper.EnsureUserForOrder(cart); cart.Save(); cart.SerializeCartOffers(); payPalLog.SerializedObject = SerializationHelper.SerializeToString(cart); payPalLog.Save(); Order order = Order.CreateOrder( store, cart, transactionId, transactionId, string.Empty, currencyUsed, "PayPal", orderStatus); if (standardCheckoutLog.ReturnUrl.Length > 0) { redirectUrl = standardCheckoutLog.ReturnUrl; } if (orderStatus == OrderStatus.OrderStatusFulfillableGuid) { try { StoreHelper.ConfirmOrder(store, order); GoogleCheckoutLog.DeleteByCart(order.OrderGuid); } catch (Exception ex) { log.Error("error sending confirmation email", ex); } } if (orderStatus == OrderStatus.OrderStatusReceivedGuid) { if ((paymentStatus == "Pending") && (pendingReason == "echeck")) { StoreHelper.ConfirmOrderReceived(store, existingOrder, true); } } return redirectUrl; }
public abstract bool HandleRequest( WorldPayPaymentResponse wpResponse, PayPalLog worldPayLog, Page page);
public HttpStatusCodeResult IPN(FormCollection result) { try { var payPalPaymentInfo = new PayPalPaymentInfo(); TryUpdateModel(payPalPaymentInfo, result.ToValueProvider()); var model = new PayPalListenerModel { PayPalPaymentInfo = payPalPaymentInfo }; var parameters = Request.BinaryRead(Request.ContentLength); if (parameters.Length > 0) { model.GetStatus(parameters); PayPalLog.Debug(payPalPaymentInfo.invoice); PayPalLog.Debug(payPalPaymentInfo.payment_status); try { var order = _orderService.GetOrderByNumber(payPalPaymentInfo.invoice); OrderStatus orderStatus; switch (payPalPaymentInfo.payment_status.ToLower()) { case "completed": orderStatus = OrderStatus.Paid; break; default: orderStatus = OrderStatus.Cancelled; break; } order.Status = orderStatus; order.PaymentReference = payPalPaymentInfo.txn_id; switch (order.Status) { case OrderStatus.Paid: order.PaidAt = DateTime.Now; break; case OrderStatus.Completed: order.CompletedAt = DateTime.Now; break; case OrderStatus.Cancelled: order.CancelledAt = DateTime.Now; break; } } catch (Exception ex) { PayPalLog.Debug(string.Format("Error saving order [{0}] {1}", payPalPaymentInfo.invoice, JsonConvert.SerializeObject(payPalPaymentInfo))); PayPalLog.Error(ex); } } else { PayPalLog.Debug(string.Format("No PayPal return parameters [{0}]", JsonConvert.SerializeObject(result))); } } catch (Exception ex) { PayPalLog.Debug(string.Format("Error unknown [{0}] {1}", ex.Message, result)); PayPalLog.Error(ex); } return(new HttpStatusCodeResult(200, "Success")); }
private void HandleRequest() { string formValues = string.Empty; try { //Per PayPal Order Management / Integration Guide Pg.25 //we have to validate the price, transactionId, etc. string transactionId = HttpUtility.UrlDecode(Request.Form["txn_id"].ToString()); string custom = HttpUtility.UrlDecode(Request.Form["custom"].ToString()); byte[] buffer = Request.BinaryRead(HttpContext.Current.Request.ContentLength); formValues = System.Text.Encoding.ASCII.GetString(buffer); string response = Verify(formValues); if (response.StartsWith("VERIFIED")) { Guid standardCheckoutLogGuid = Guid.Empty; if (custom.Length == 36) { standardCheckoutLogGuid = new Guid(custom); } PayPalLog standardCheckoutLog = new PayPalLog(standardCheckoutLogGuid); bool result = false; if ((standardCheckoutLog != null) && (standardCheckoutLog.IPNProviderName.Length > 0)) { PayPalIPNHandlerProvider provider = PayPalIPNHandlerProviderManager.Providers[standardCheckoutLog.IPNProviderName]; if (provider != null) { result = provider.HandleRequest( transactionId, Request.Form, standardCheckoutLog); } } //if (result) //{ // Response.StatusCode = (int)System.Net.HttpStatusCode.OK; // Response.Flush(); // Response.End(); //} //else //{ // // TODO: what? log it? // Response.StatusCode = (int)System.Net.HttpStatusCode.OK; // Response.Flush(); // Response.End(); //} } else { // failed verification // TODO: what log it? Response.StatusCode = (int)System.Net.HttpStatusCode.OK; Response.Flush(); Response.End(); } } catch (Exception ex) { log.Error(formValues, ex); } }
private void DoPayPalStandardCheckout() { PayPalLog payPalLog = new PayPalLog(); payPalLog.ProviderName = WebStorePayPalReturnHandler.ProviderName; payPalLog.PDTProviderName = WebStorePayPalPDTHandlerProvider.ProviderName; payPalLog.IPNProviderName = WebStorePayPalIPNHandlerProvider.ProviderName; payPalLog.ReturnUrl = SiteRoot + "/WebStore/OrderDetail.aspx?pageid=" + pageId.ToInvariantString() + "&mid=" + moduleId.ToInvariantString() + "&orderid=" + cart.CartGuid.ToString(); payPalLog.RequestType = "StandardCheckout"; cart.SerializeCartOffers(); payPalLog.SerializedObject = SerializationHelper.SerializeToString(cart); //Currency currency = new Currency(store.DefaultCurrencyId); payPalLog.CartGuid = cart.CartGuid; payPalLog.SiteGuid = store.SiteGuid; payPalLog.StoreGuid = store.Guid; payPalLog.UserGuid = cart.UserGuid; payPalLog.CartTotal = cart.OrderTotal; payPalLog.CurrencyCode = siteSettings.GetCurrency().Code; payPalLog.Save(); string payPalStandardUrl = StoreHelper.GetBuyNowUrl( payPalLog.RowGuid, cart, store, commerceConfig); WebUtils.SetupRedirect(this, payPalStandardUrl); }
private void DoPayPalExpressCeckout() { string siteRoot = SiteUtils.GetNavigationSiteRoot(); PayPalExpressGateway gateway = new PayPalExpressGateway( commerceConfig.PayPalAPIUsername, commerceConfig.PayPalAPIPassword, commerceConfig.PayPalAPISignature, commerceConfig.PayPalStandardEmailAddress ) { UseTestMode = commerceConfig.PaymentGatewayUseTestMode, MerchantCartId = cart.CartGuid.ToString(), ChargeTotal = cart.OrderTotal, ReturnUrl = siteRoot + "/Services/PayPalReturnHandler.ashx", CancelUrl = siteRoot + Request.RawUrl, CurrencyCode = siteSettings.GetCurrency().Code, OrderDescription = store.Name + " " + WebStoreResources.OrderHeading, BuyerEmail = cart.OrderInfo.CustomerEmail, ShipToFirstName = cart.OrderInfo.DeliveryFirstName, ShipToLastName = cart.OrderInfo.DeliveryLastName, ShipToAddress = cart.OrderInfo.DeliveryAddress1, ShipToAddress2 = cart.OrderInfo.DeliveryAddress2, ShipToCity = cart.OrderInfo.DeliveryCity, ShipToState = cart.OrderInfo.DeliveryState, ShipToCountry = cart.OrderInfo.DeliveryCountry, ShipToPostalCode = cart.OrderInfo.DeliveryPostalCode, ShipToPhone = cart.OrderInfo.CustomerTelephoneDay }; // this tells paypal to use the shipping address we pass in // rather than what the customer has on file // when we implement shippable products we'll do shipping calculations before // sending the user to paypal //gateway.OverrideShippingAddress = true; //commented out the above, we want user to be able to populate shipping info from their paypal account bool executed = gateway.CallSetExpressCheckout(); if (executed) { //TODO: log the raw response if (gateway.PayPalExpressUrl.Length > 0) { cart.SerializeCartOffers(); // record the gateway.PayPalToken PayPalLog payPalLog = new PayPalLog { RawResponse = gateway.RawResponse, ProviderName = WebStorePayPalReturnHandler.ProviderName, ReturnUrl = siteRoot + Request.RawUrl, Token = HttpUtility.UrlDecode(gateway.PayPalToken), RequestType = "SetExpressCheckout", SerializedObject = SerializationHelper.SerializeToString(cart), CartGuid = cart.CartGuid, SiteGuid = store.SiteGuid, StoreGuid = store.Guid, UserGuid = cart.UserGuid }; payPalLog.Save(); Response.Redirect(gateway.PayPalExpressUrl); } else { if (commerceConfig.PaymentGatewayUseTestMode) { lblMessage.Text = gateway.RawResponse; } } } else { lblMessage.Text = WebStoreResources.TransactionNotInitiatedMessage; if (gateway.LastExecutionException != null) { if (commerceConfig.PaymentGatewayUseTestMode) { lblMessage.Text = gateway.LastExecutionException.ToString(); } } else { if (commerceConfig.PaymentGatewayUseTestMode) { lblMessage.Text = gateway.RawResponse; } } } }
public abstract string HandleRequestAndReturnUrlForRedirect( string rawResponse, StringDictionary pdtItems, string transactionId, PayPalLog standardCheckoutLog);
private void ProcessOrder( Cart cart, Store store, WorldPayPaymentResponse wpResponse, PayPalLog worldPayLog, Page page) { // process the cart into an order then // return an html order result template for use at world pay cart.DeSerializeCartOffers(); if (wpResponse.CompName.Length > 0) { cart.OrderInfo.CustomerCompany = wpResponse.CompName; } if (wpResponse.Address1.Length > 0) { cart.OrderInfo.CustomerAddressLine1 = wpResponse.Address1; } if (wpResponse.Address2.Length > 0) { cart.OrderInfo.CustomerAddressLine2 = wpResponse.Address2; } if (wpResponse.Address3.Length > 0) { cart.OrderInfo.CustomerAddressLine2 += " " + wpResponse.Address3; } if (wpResponse.Town.Length > 0) { cart.OrderInfo.CustomerCity = wpResponse.Town; } //cart.OrderInfo.DeliveryFirstName = wpResponse.Name; if ( (wpResponse.Name.Length > 0) && ((cart.OrderInfo.CustomerLastName.Length == 0) || (!wpResponse.Name.Contains((cart.OrderInfo.CustomerLastName)))) ) { cart.OrderInfo.CustomerLastName = wpResponse.Name; // this is full name } if (wpResponse.Postcode.Length > 0) { cart.OrderInfo.CustomerPostalCode = wpResponse.Postcode; } if (wpResponse.Region.Length > 0) { cart.OrderInfo.CustomerState = wpResponse.Region; } if (wpResponse.Country.Length > 0) { cart.OrderInfo.CustomerCountry = wpResponse.Country; } if (wpResponse.Tel.Length > 0) { cart.OrderInfo.CustomerTelephoneDay = wpResponse.Tel; } if (wpResponse.Email.Length > 0) { cart.OrderInfo.CustomerEmail = wpResponse.Email; } cart.CopyCustomerToBilling(); cart.CopyCustomerToShipping(); //cart.TaxTotal = taxAmount; //cart.OrderTotal = grossAmount; //if (shippingAmount > 0) //{ // cart.ShippingTotal = shippingAmount; //} StoreHelper.EnsureUserForOrder(cart); cart.Save(); Order order = Order.CreateOrder( store, cart, wpResponse.TransId, wpResponse.TransId, string.Empty, wpResponse.Currency, "WorldPay", OrderStatus.OrderStatusFulfillableGuid); // grab the return url before we delete the un-needed logs string orderDetailUrl = worldPayLog.ReturnUrl; string storePageUrl = worldPayLog.RawResponse; // remove any previous logs GoogleCheckoutLog.DeleteByCart(order.OrderGuid); PayPalLog.DeleteByCart(order.OrderGuid); // create a final log that has the serialized reposnse from worldpay rather than the serialized cart worldPayLog = new PayPalLog(); worldPayLog.SiteGuid = store.SiteGuid; worldPayLog.StoreGuid = store.Guid; worldPayLog.CartGuid = order.OrderGuid; worldPayLog.UserGuid = order.UserGuid; worldPayLog.ProviderName = "WebStoreWorldPayResponseHandler"; worldPayLog.RequestType = "WorldPay"; worldPayLog.PaymentStatus = "Paid"; worldPayLog.PaymentType = "WorldPay"; worldPayLog.CartTotal = order.OrderTotal; worldPayLog.PayPalAmt = wpResponse.AuthAmount; worldPayLog.TransactionId = wpResponse.TransId; worldPayLog.CurrencyCode = wpResponse.Currency; worldPayLog.ReasonCode = wpResponse.AVS; worldPayLog.RawResponse = SerializationHelper.SerializeToString(wpResponse); worldPayLog.CreatedUtc = DateTime.UtcNow; worldPayLog.ReturnUrl = orderDetailUrl; worldPayLog.Save(); try { StoreHelper.ConfirmOrder(store, order); } catch (Exception ex) { log.Error("error sending confirmation email", ex); } // retrun the html if (config.WorldPayProduceShopperResponse) { CultureInfo currencyCulture = ResourceHelper.GetCurrencyCulture(wpResponse.Currency); string htmlTemplate = ResourceHelper.GetMessageTemplate(CultureInfo.CurrentUICulture, config.WorldPayShopperResponseTemplate); StringBuilder finalOutput = new StringBuilder(); finalOutput.Append(htmlTemplate); finalOutput.Replace("#WorldPayBannerToken", "<WPDISPLAY ITEM=banner>"); //required by worldpay finalOutput.Replace("#CustomerName", wpResponse.Name); finalOutput.Replace("#StoreName", store.Name); finalOutput.Replace("#OrderId", order.OrderGuid.ToString()); finalOutput.Replace("#StorePageLink", "<a href='" + storePageUrl + "'>" + storePageUrl + "</a>"); finalOutput.Replace("#OrderDetailLink", "<a href='" + orderDetailUrl + "'>" + orderDetailUrl + "</a>"); StringBuilder orderDetails = new StringBuilder(); DataSet dsOffers = Order.GetOrderOffersAndProducts(store.Guid, order.OrderGuid); foreach (DataRow row in dsOffers.Tables["Offers"].Rows) { string og = row["OfferGuid"].ToString(); orderDetails.Append(row["Name"].ToString() + " "); orderDetails.Append(row["Quantity"].ToString() + " @ "); orderDetails.Append(string.Format(currencyCulture, "{0:c}", Convert.ToDecimal(row["OfferPrice"]))); orderDetails.Append("<br />"); string whereClause = string.Format("OfferGuid = '{0}'", og); DataView dv = new DataView(dsOffers.Tables["Products"], whereClause, "", DataViewRowState.CurrentRows); if (dv.Count > 1) { foreach (DataRow r in dsOffers.Tables["Products"].Rows) { string pog = r["OfferGuid"].ToString(); if (og == pog) { orderDetails.Append(r["Name"].ToString() + " "); orderDetails.Append(r["Quantity"].ToString() + " <br />"); } } } } finalOutput.Replace("#OrderDetails", orderDetails.ToString()); page.Response.Write(finalOutput.ToString()); page.Response.Flush(); } }
/// <summary> /// return true if the transaction was processed with no problems /// </summary> public abstract bool HandleRequest( string transactionId, NameValueCollection form, PayPalLog standardCheckoutLog);
private void HandleRequest() { // the handler will return html that worldpay will display on their own site so make sure this page doesn't write to the response Response.Clear(); Response.Buffer = true; log.Info("Received a post"); WorldPayPaymentResponse wpResponse = WorldPayPaymentResponse.ParseRequest(); if (wpResponse == null) { log.Info("wpResponse object was null"); SiteUtils.RedirectToAccessDeniedPage(this); return; } CommerceConfiguration commerceConfig = SiteUtils.GetCommerceConfig(); if ( (commerceConfig.WorldPayResponsePassword.Length > 0) &&(wpResponse.CallbackPW != commerceConfig.WorldPayResponsePassword) ) { log.Info("recieved post but the response password was not correct. so redirecting to access denied."); //TODO: should we log what was posted? SiteUtils.RedirectToAccessDeniedPage(this); return; } Guid logGuid = Guid.Empty; if (wpResponse.CartId.Length == 36) { log.Info("wpResponse.CartId was 36 chars"); logGuid = new Guid(wpResponse.CartId); } PayPalLog worldPayLog = new PayPalLog(logGuid); if (worldPayLog.RowGuid == Guid.Empty) { // log was not found log.Info("WorldPay/PayPal log not found "); SiteUtils.RedirectToAccessDeniedPage(this); return; } log.Info("Provider name is " + worldPayLog.ProviderName); WorldPayResponseHandlerProvider handler = WorldPayResponseHandlerProviderManager.Providers[worldPayLog.ProviderName]; if (handler == null) { //log the details of the request. string serializedResponse = SerializationHelper.SerializeToString(wpResponse); log.Info("failed to find a handler for worldpay postback, xml to follow"); log.Info(serializedResponse); SiteUtils.RedirectToAccessDeniedPage(this); return; } handler.HandleRequest(wpResponse, worldPayLog, this); }
private void ProcessOrder( Cart cart, Store store, WorldPayPaymentResponse wpResponse, PayPalLog worldPayLog, Page page) { // process the cart into an order then // return an html order result template for use at world pay cart.DeSerializeCartOffers(); if (wpResponse.CompName.Length > 0) { cart.OrderInfo.CustomerCompany = wpResponse.CompName; } if (wpResponse.Address1.Length > 0) { cart.OrderInfo.CustomerAddressLine1 = wpResponse.Address1; } if (wpResponse.Address2.Length > 0) { cart.OrderInfo.CustomerAddressLine2 = wpResponse.Address2; } if (wpResponse.Address3.Length > 0) { cart.OrderInfo.CustomerAddressLine2 += " " + wpResponse.Address3; } if (wpResponse.Town.Length > 0) { cart.OrderInfo.CustomerCity = wpResponse.Town; } //cart.OrderInfo.DeliveryFirstName = wpResponse.Name; if( (wpResponse.Name.Length > 0) && ((cart.OrderInfo.CustomerLastName.Length == 0) || (!wpResponse.Name.Contains((cart.OrderInfo.CustomerLastName)))) ) { cart.OrderInfo.CustomerLastName = wpResponse.Name; // this is full name } if (wpResponse.Postcode.Length > 0) { cart.OrderInfo.CustomerPostalCode = wpResponse.Postcode; } if (wpResponse.Region.Length > 0) { cart.OrderInfo.CustomerState = wpResponse.Region; } if (wpResponse.Country.Length > 0) { cart.OrderInfo.CustomerCountry = wpResponse.Country; } if (wpResponse.Tel.Length > 0) { cart.OrderInfo.CustomerTelephoneDay = wpResponse.Tel; } if (wpResponse.Email.Length > 0) { cart.OrderInfo.CustomerEmail = wpResponse.Email; } cart.CopyCustomerToBilling(); cart.CopyCustomerToShipping(); //cart.TaxTotal = taxAmount; //cart.OrderTotal = grossAmount; //if (shippingAmount > 0) //{ // cart.ShippingTotal = shippingAmount; //} StoreHelper.EnsureUserForOrder(cart); cart.Save(); Order order = Order.CreateOrder( store, cart, wpResponse.TransId, wpResponse.TransId, string.Empty, wpResponse.Currency, "WorldPay", OrderStatus.OrderStatusFulfillableGuid); // grab the return url before we delete the un-needed logs string orderDetailUrl = worldPayLog.ReturnUrl; string storePageUrl = worldPayLog.RawResponse; // remove any previous logs GoogleCheckoutLog.DeleteByCart(order.OrderGuid); PayPalLog.DeleteByCart(order.OrderGuid); // create a final log that has the serialized reposnse from worldpay rather than the serialized cart worldPayLog = new PayPalLog(); worldPayLog.SiteGuid = store.SiteGuid; worldPayLog.StoreGuid = store.Guid; worldPayLog.CartGuid = order.OrderGuid; worldPayLog.UserGuid = order.UserGuid; worldPayLog.ProviderName = "WebStoreWorldPayResponseHandler"; worldPayLog.RequestType = "WorldPay"; worldPayLog.PaymentStatus = "Paid"; worldPayLog.PaymentType = "WorldPay"; worldPayLog.CartTotal = order.OrderTotal; worldPayLog.PayPalAmt = wpResponse.AuthAmount; worldPayLog.TransactionId = wpResponse.TransId; worldPayLog.CurrencyCode = wpResponse.Currency; worldPayLog.ReasonCode = wpResponse.AVS; worldPayLog.RawResponse = SerializationHelper.SerializeToString(wpResponse); worldPayLog.CreatedUtc = DateTime.UtcNow; worldPayLog.ReturnUrl = orderDetailUrl; worldPayLog.Save(); try { StoreHelper.ConfirmOrder(store, order); } catch (Exception ex) { log.Error("error sending confirmation email", ex); } // retrun the html if (config.WorldPayProduceShopperResponse) { CultureInfo currencyCulture = ResourceHelper.GetCurrencyCulture(wpResponse.Currency); string htmlTemplate = ResourceHelper.GetMessageTemplate(CultureInfo.CurrentUICulture, config.WorldPayShopperResponseTemplate); StringBuilder finalOutput = new StringBuilder(); finalOutput.Append(htmlTemplate); finalOutput.Replace("#WorldPayBannerToken", "<WPDISPLAY ITEM=banner>"); //required by worldpay finalOutput.Replace("#CustomerName", wpResponse.Name); finalOutput.Replace("#StoreName", store.Name); finalOutput.Replace("#OrderId", order.OrderGuid.ToString()); finalOutput.Replace("#StorePageLink", "<a href='" + storePageUrl + "'>" + storePageUrl + "</a>"); finalOutput.Replace("#OrderDetailLink", "<a href='" + orderDetailUrl + "'>" + orderDetailUrl + "</a>"); StringBuilder orderDetails = new StringBuilder(); DataSet dsOffers = Order.GetOrderOffersAndProducts(store.Guid, order.OrderGuid); foreach (DataRow row in dsOffers.Tables["Offers"].Rows) { string og = row["OfferGuid"].ToString(); orderDetails.Append(row["Name"].ToString() + " "); orderDetails.Append(row["Quantity"].ToString() + " @ "); orderDetails.Append(string.Format(currencyCulture, "{0:c}", Convert.ToDecimal(row["OfferPrice"]))); orderDetails.Append("<br />"); string whereClause = string.Format("OfferGuid = '{0}'", og); DataView dv = new DataView(dsOffers.Tables["Products"], whereClause, "", DataViewRowState.CurrentRows); if (dv.Count > 1) { foreach (DataRow r in dsOffers.Tables["Products"].Rows) { string pog = r["OfferGuid"].ToString(); if (og == pog) { orderDetails.Append(r["Name"].ToString() + " "); orderDetails.Append(r["Quantity"].ToString() + " <br />"); } } } } finalOutput.Replace("#OrderDetails", orderDetails.ToString()); page.Response.Write(finalOutput.ToString()); page.Response.Flush(); } }
/// <summary> /// return true if the transaction was processed with no problems /// </summary> /// <param name="context"></param> /// <param name="transactionId"></param> /// <param name="orderId"></param> /// <param name="grossAmount"></param> /// <param name="standardCheckoutLog"></param> /// <returns></returns> public override bool HandleRequest( string transactionId, NameValueCollection form, PayPalLog standardCheckoutLog) { bool result = false; if (standardCheckoutLog.SerializedObject.Length == 0) { return(result); } Cart cart = (Cart)SerializationHelper.DeserializeFromString(typeof(Cart), standardCheckoutLog.SerializedObject); Store store = new Store(cart.StoreGuid); SiteSettings siteSettings = new SiteSettings(store.SiteGuid); bool debugPayPal = WebConfigSettings.DebugPayPal; //mc_gross=5.00 //&address_status=confirmed //&item_number1=d28a6bed-7e51-4f18-a893-77b4d5665a64 //&payer_id=zzzzzz //&tax=0.00 //&address_street=nnnn //&payment_date=10%3A08%3A08+Jul+29%2C+2008+PDT //&payment_status=Completed //&charset=windows-1252 //&address_zip=92843 //&mc_shipping=0.00 //&mc_handling=0.00 //&first_name=zz //&mc_fee=0.45 //&address_country_code=US //&address_name=zzzz //¬ify_version=2.4 //&custom=d9ef5324-2201-4749-b06a-9bba7a9dce61 //&payer_status=verified //&business=sales%40mojoportal.com //&address_country=United+States //&num_cart_items=1 //&mc_handling1=0.00 //&address_city=nnnn //&verify_sign= //&payer_email=zzzzzz //&mc_shipping1=0.00 //&tax1=0.00 //&txn_id=81Y88484JA1416221 //&payment_type=instant //&payer_business_name=EBShoes //&last_name=Ngo //&address_state=CA //&item_name1=Buy+Joe+a+Beer //&receiver_email=sales%40mojoportal.com //&payment_fee=0.45 //&quantity1=1 //&receiver_id=nnnn //&txn_type=cart //&mc_gross_1=5.00 //&mc_currency=USD //&residence_country=US //&payment_gross=5.00 string firstName = string.Empty; if (form["first_name"] != null) { firstName = form["first_name"].ToString(); } string lastName = string.Empty; if (form["last_name"] != null) { lastName = form["last_name"].ToString(); } string paymentStatus = string.Empty; if (form["payment_status"] != null) { paymentStatus = form["payment_status"].ToString(); } string payerEmail = string.Empty; if (form["payer_email"] != null) { payerEmail = form["payer_email"].ToString(); } string paymentGross = string.Empty; if (form["mc_gross"] != null) { paymentGross = form["mc_gross"].ToString(); } string payPalFee = string.Empty; if (form["mc_fee"] != null) { payPalFee = form["mc_fee"].ToString(); } string payPalTax = string.Empty; if (form["tax"] != null) { payPalTax = form["tax"].ToString(); } string payPalShipping = string.Empty; if (form["mc_shipping"] != null) { payPalShipping = form["mc_shipping"].ToString(); } string currencyUsed = string.Empty; if (form["mc_currency"] != null) { currencyUsed = form["mc_currency"].ToString(); } string pendingReason = string.Empty; if (form["pending_reason"] != null) { pendingReason = form["pending_reason"].ToString(); } string reasonCode = string.Empty; if (form["reason_code"] != null) { reasonCode = form["reason_code"].ToString(); } string paymentType = string.Empty; if (form["txn_type"] != null) { paymentType = form["txn_type"].ToString(); } string payPalSettlement = "0"; if (form["settle_amount"] != null) { payPalSettlement = form["settle_amount"].ToString(); } string customerAddress = string.Empty; if (form["address_street"] != null) { customerAddress = form["address_street"].ToString(); } string customerCity = string.Empty; if (form["address_city"] != null) { customerCity = form["address_city"].ToString(); } string customerState = string.Empty; if (form["address_state"] != null) { customerState = form["address_state"].ToString(); } string customerPostalCode = string.Empty; if (form["address_zip"] != null) { customerPostalCode = form["address_zip"].ToString(); } string customerCountry = string.Empty; if (form["address_country"] != null) { customerCountry = form["address_country"].ToString(); } string customerPhone = string.Empty; if (form["contact_phone"] != null) { customerPhone = form["contact_phone"].ToString(); } string customerBusinessName = string.Empty; if (form["payer_business_name"] != null) { customerBusinessName = form["payer_business_name"].ToString(); } // TODO: we need to store this somewhere on the cart/order // its the message the user enters in special instructions on paypal checkout string customerMemo = string.Empty; if (form["memo"] != null) { customerMemo = form["memo"].ToString(); } if (debugPayPal) { log.Info("PayPal currencyUsed was " + currencyUsed); } //Regardless of the specified currency, the format will have decimal point //with exactly two digits to the right and an optional thousands separator to the left, //which must be a comma; for example, EUR 2.000,00 must be specified as 2000.00 or 2,000.00 // So we want to parse it with US Culture CultureInfo currencyCulture = new CultureInfo("en-US"); //if (currencyUsed.Length > 0) //{ // currencyCulture = ResourceHelper.GetCurrencyCulture(currencyUsed); //} //else //{ // //Currency currency = new Currency(store.DefaultCurrencyId); // //currencyCulture = ResourceHelper.GetCurrencyCulture(currency.Code); // Currency currency = siteSettings.GetCurrency(); // currencyCulture = ResourceHelper.GetCurrencyCulture(currency.Code); // currencyUsed = currency.Code; //} //if (debugPayPal) { log.Info("PayPal final currency culture was " + currencyUsed); } decimal grossAmount = 0; decimal.TryParse(paymentGross, NumberStyles.Currency, currencyCulture, out grossAmount); decimal feeAmount = 0; decimal.TryParse(payPalFee, NumberStyles.Currency, currencyCulture, out feeAmount); decimal taxAmount = 0; decimal.TryParse(payPalTax, NumberStyles.Currency, currencyCulture, out taxAmount); decimal shippingAmount = 0; decimal.TryParse(payPalShipping, NumberStyles.Currency, currencyCulture, out shippingAmount); decimal settleAmount = 0; decimal.TryParse(payPalSettlement, NumberStyles.Currency, currencyCulture, out settleAmount); if (debugPayPal) { log.Info("PayPal paymentGross was " + paymentGross + " which was parsed as " + grossAmount.ToString()); log.Info("PayPal payPalFee was " + payPalFee + " which was parsed as " + feeAmount.ToString()); log.Info("PayPal payPalTax was " + payPalTax + " which was parsed as " + taxAmount.ToString()); log.Info("PayPal payPalShipping was " + payPalShipping + " which was parsed as " + shippingAmount.ToString()); log.Info("PayPal payPalSettlement was " + payPalSettlement + " which was parsed as " + settleAmount.ToString()); } PayPalLog payPalLog = new PayPalLog(); payPalLog.PDTProviderName = standardCheckoutLog.PDTProviderName; payPalLog.IPNProviderName = standardCheckoutLog.IPNProviderName; payPalLog.ReturnUrl = standardCheckoutLog.ReturnUrl; payPalLog.ProviderName = standardCheckoutLog.ProviderName; payPalLog.SiteGuid = standardCheckoutLog.SiteGuid; payPalLog.StoreGuid = standardCheckoutLog.StoreGuid; payPalLog.UserGuid = standardCheckoutLog.UserGuid; payPalLog.ApiVersion = standardCheckoutLog.ApiVersion; payPalLog.CartGuid = standardCheckoutLog.CartGuid; payPalLog.SerializedObject = standardCheckoutLog.SerializedObject; payPalLog.CartTotal = grossAmount; payPalLog.PayPalAmt = feeAmount; if (settleAmount > 0) { payPalLog.SettleAmt = settleAmount; } else { payPalLog.SettleAmt = (grossAmount - feeAmount); } payPalLog.TaxAmt = taxAmount; payPalLog.CurrencyCode = currencyUsed; payPalLog.TransactionId = transactionId; payPalLog.RawResponse = form.ToString(); payPalLog.Response = "IPNSuccess"; payPalLog.RequestType = "IPN"; payPalLog.PayerId = payerEmail; payPalLog.PaymentType = paymentType; payPalLog.PaymentStatus = paymentStatus; payPalLog.PendingReason = pendingReason; payPalLog.ReasonCode = reasonCode; payPalLog.Save(); // see if this cart has already been proceesed Order existingOrder = new Order(cart.CartGuid); // order already exists if (existingOrder.OrderGuid != Guid.Empty) { // lookup order status if needed make it fullfillable // then redirect to order detail page if (existingOrder.StatusGuid == OrderStatus.OrderStatusReceivedGuid) { if (paymentStatus == "Completed") { existingOrder.StatusGuid = OrderStatus.OrderStatusFulfillableGuid; existingOrder.Save(); try { StoreHelper.ConfirmOrder(store, existingOrder); GoogleCheckoutLog.DeleteByCart(existingOrder.OrderGuid); } catch (Exception ex) { log.Error("error sending confirmation email", ex); } } } result = true; payPalLog.ReasonCode = "existing order found"; payPalLog.Save(); return(result); } // if we get here the cart has not yet been processed into an order cart.DeSerializeCartOffers(); Guid orderStatus; if (paymentStatus == "Completed") { orderStatus = OrderStatus.OrderStatusFulfillableGuid; } else { orderStatus = OrderStatus.OrderStatusReceivedGuid; } // update the order with customer shipping info cart.OrderInfo.DeliveryCompany = customerBusinessName; cart.OrderInfo.DeliveryAddress1 = customerAddress; cart.OrderInfo.DeliveryCity = customerCity; cart.OrderInfo.DeliveryFirstName = firstName; cart.OrderInfo.DeliveryLastName = lastName; cart.OrderInfo.DeliveryPostalCode = customerPostalCode; cart.OrderInfo.DeliveryState = customerState; cart.OrderInfo.DeliveryCountry = customerCountry; if (customerPhone.Length > 0) { cart.OrderInfo.CustomerTelephoneDay = customerPhone; } if (payerEmail.Length > 0) { cart.OrderInfo.CustomerEmail = payerEmail; } cart.CopyShippingToBilling(); cart.CopyShippingToCustomer(); cart.TaxTotal = taxAmount; cart.OrderTotal = grossAmount; if (shippingAmount > 0) { cart.ShippingTotal = shippingAmount; } StoreHelper.EnsureUserForOrder(cart); cart.Save(); cart.SerializeCartOffers(); payPalLog.SerializedObject = SerializationHelper.SerializeToString(cart); payPalLog.Save(); Order order = Order.CreateOrder( store, cart, transactionId, transactionId, string.Empty, currencyUsed, "PayPal", orderStatus); if (orderStatus == OrderStatus.OrderStatusFulfillableGuid) { try { StoreHelper.ConfirmOrder(store, order); GoogleCheckoutLog.DeleteByCart(order.OrderGuid); } catch (Exception ex) { log.Error("error sending confirmation email", ex); } } if (orderStatus == OrderStatus.OrderStatusReceivedGuid) { StoreHelper.ConfirmOrderReceived(store, order); } result = true; return(result); }
private void LoadSettings() { PageId = WebUtils.ParseInt32FromQueryString("pageid", -1); ModuleId = WebUtils.ParseInt32FromQueryString("mid", -1); payPalGetExpressCheckoutLogGuid = WebUtils.ParseGuidFromQueryString("plog", payPalGetExpressCheckoutLogGuid); if (payPalGetExpressCheckoutLogGuid == Guid.Empty) { Response.Redirect(SiteUtils.GetCurrentPageUrl()); } checkoutDetailsLog = new PayPalLog(payPalGetExpressCheckoutLogGuid); if (checkoutDetailsLog.RowGuid == Guid.Empty) { Response.Redirect(SiteUtils.GetCurrentPageUrl()); } cart = (Cart)SerializationHelper.DeserializeFromString(typeof(Cart), checkoutDetailsLog.SerializedObject); if (cart == null) { Response.Redirect(SiteUtils.GetCurrentPageUrl()); } cart.DeSerializeCartOffers(); cart.RefreshTotals(); if ((cart.LastModified < DateTime.UtcNow.AddDays(-1)) && (cart.DiscountCodesCsv.Length > 0)) { StoreHelper.EnsureValidDiscounts(store, cart); } siteUser = SiteUtils.GetCurrentSiteUser(); //if (siteUser == null) //{ // Response.Redirect(SiteUtils.GetCurrentPageUrl()); //} if ((siteUser != null)&&(cart.UserGuid == Guid.Empty)) { // user wasn't logged in when express checkout was called cart.UserGuid = siteUser.UserGuid; cart.Save(); //if (checkoutDetailsLog.UserGuid == Guid.Empty) //{ // // we need to make sure we have the user in the log and serialized cart // checkoutDetailsLog.UserGuid = siteUser.UserGuid; // cart.SerializeCartOffers(); // checkoutDetailsLog.SerializedObject = SerializationHelper.SerializeToSoap(cart); // checkoutDetailsLog.Save(); //} } if ((siteUser != null)&&(cart.UserGuid != siteUser.UserGuid)) { Response.Redirect(SiteUtils.GetCurrentPageUrl()); } if (ModuleId == -1) { ModuleId = StoreHelper.FindStoreModuleId(CurrentPage); } store = StoreHelper.GetStore(); commerceConfig = SiteUtils.GetCommerceConfig(); currencyCulture = ResourceHelper.GetCurrencyCulture(siteSettings.GetCurrency().Code); if (siteUser != null) { pnlRequireLogin.Visible = false; } else { btnMakePayment.Visible = false; } AddClassToBody("webstore webstoreexpresscheckout"); }
void btnMakePayment_Click(object sender, EventArgs e) { PayPalExpressGateway gateway = new PayPalExpressGateway( commerceConfig.PayPalAPIUsername, commerceConfig.PayPalAPIPassword, commerceConfig.PayPalAPISignature, commerceConfig.PayPalStandardEmailAddress); gateway.UseTestMode = commerceConfig.PaymentGatewayUseTestMode; gateway.PayPalToken = checkoutDetailsLog.Token; gateway.PayPalPayerId = checkoutDetailsLog.PayerId; gateway.MerchantCartId = cart.CartGuid.ToString(); gateway.ChargeTotal = cart.OrderTotal; gateway.ReturnUrl = SiteRoot + "/Services/PayPalReturnHandler.ashx"; gateway.CancelUrl = SiteUtils.GetCurrentPageUrl(); gateway.CurrencyCode = siteSettings.GetCurrency().Code; // **** here's where the payment is requested ****** bool executed = gateway.CallDoExpressCheckoutPayment(); PayPalLog payPalLog = new PayPalLog(); payPalLog.RequestType = "DoExpressCheckoutPayment"; payPalLog.ProviderName = WebStorePayPalReturnHandler.ProviderName; payPalLog.SerializedObject = checkoutDetailsLog.SerializedObject; payPalLog.ReturnUrl = checkoutDetailsLog.ReturnUrl; payPalLog.RawResponse = gateway.RawResponse; payPalLog.TransactionId = gateway.TransactionId; payPalLog.PaymentType = gateway.PayPalPaymentType; payPalLog.PaymentStatus = gateway.PayPalPaymentStatus; payPalLog.PendingReason = gateway.PayPalPendingReason; payPalLog.ReasonCode = gateway.ReasonCode; payPalLog.PayPalAmt = gateway.ChargeTotal; payPalLog.FeeAmt = gateway.PayPalFeeAmount; payPalLog.SettleAmt = gateway.PayPalSettlementAmount; payPalLog.TaxAmt = gateway.PayPalTaxTotal; payPalLog.Token = gateway.PayPalToken; payPalLog.PayerId = gateway.PayPalPayerId; payPalLog.RequestType = "DoExpressCheckoutPayment"; payPalLog.SiteGuid = store.SiteGuid; payPalLog.StoreGuid = store.Guid; payPalLog.CartGuid = cart.CartGuid; payPalLog.UserGuid = cart.UserGuid; payPalLog.CartTotal = cart.OrderTotal; payPalLog.CurrencyCode = gateway.CurrencyCode; if (gateway.PayPalExchangeRate.Length > 0) payPalLog.ExchangeRate = decimal.Parse(gateway.PayPalExchangeRate); payPalLog.Save(); if (!executed) { lblMessage.Text = WebStoreResources.TransactionNotInitiatedMessage; if (gateway.LastExecutionException != null) { log.Error("ExpressCheckout gateway error", gateway.LastExecutionException); if (commerceConfig.PaymentGatewayUseTestMode) { lblMessage.Text = gateway.LastExecutionException.ToString(); } } else { if (commerceConfig.PaymentGatewayUseTestMode) { lblMessage.Text = gateway.RawResponse; } } return; } string redirectUrl = string.Empty; if (gateway.TransactionId.Length == 0) { // TODO: redirect where? redirectUrl = SiteRoot + "/WebStore/PayPalGatewayError.aspx?plog=" + payPalLog.RowGuid.ToString(); Response.Redirect(redirectUrl); } Guid orderStatusGuid; if (payPalLog.PaymentStatus == "Completed") { orderStatusGuid = OrderStatus.OrderStatusFulfillableGuid; } else { orderStatusGuid = OrderStatus.OrderStatusReceivedGuid; } Order order = Order.CreateOrder( store, cart, payPalLog.RawResponse, payPalLog.TransactionId, string.Empty, siteSettings.GetCurrency().Code, "PayPal", orderStatusGuid); StoreHelper.ClearCartCookie(cart.StoreGuid); // send confirmation email // paypal sends an order confirmation so no need // redirect to order details redirectUrl = SiteRoot + "/WebStore/OrderDetail.aspx?pageid=" + PageId.ToString(CultureInfo.InvariantCulture) + "&mid=" + store.ModuleId.ToString(CultureInfo.InvariantCulture) + "&orderid=" + order.OrderGuid.ToString(); Response.Redirect(redirectUrl); }
private void HandleRequest() { if (transactionId.Length == 0) { WebUtils.SetupRedirect(this, lastResortRedirectUrl); return; } try { //Log the querystring in case we have to investigate //Logger.Information(Request.QueryString.ToString()); transactionId = HttpUtility.UrlDecode(transactionId); custom = HttpUtility.UrlDecode(custom); string pdtResponse = Verify(transactionId); if (pdtResponse.StartsWith("SUCCESS")) { string redirectUrl = string.Empty; Guid logGuid = Guid.Empty; if (custom.Length == 36) { logGuid = new Guid(custom); } PayPalLog standardCheckoutLog = new PayPalLog(logGuid); if ((standardCheckoutLog != null)&&(standardCheckoutLog.PDTProviderName.Length > 0)) { PayPalPDTHandlerProvider provider = PayPalPDTHandlerProviderManager.Providers[standardCheckoutLog.PDTProviderName]; if (provider != null) { redirectUrl = provider.HandleRequestAndReturnUrlForRedirect( pdtResponse, PayPalStandardPaymentGateway.GetPDTValues(pdtResponse), transactionId, standardCheckoutLog); if (redirectUrl.Length > 0) { WebUtils.SetupRedirect(this, redirectUrl); return; } else { // no redeirectUrl returned from provider //TODO: what? log it? WebUtils.SetupRedirect(this, lastResortRedirectUrl); return; } } else { // provider not found //log it PayPalLog unhandledLog = new PayPalLog(); unhandledLog.ProviderName = "unhandled"; unhandledLog.RawResponse = pdtResponse; unhandledLog.Save(); log.Info("invalid ptd request no valid provider found " + Request.Url.ToString()); WebUtils.SetupRedirect(this, lastResortRedirectUrl); return; } } else { // provider not specified on StandardCheckoutLog //TODO: what? log it? PayPalLog unhandledLog = new PayPalLog(); unhandledLog.ProviderName = "unhandled"; unhandledLog.RawResponse = pdtResponse; unhandledLog.Save(); log.Info("invalid ptd request no valid provider found " + Request.Url.ToString()); WebUtils.SetupRedirect(this, lastResortRedirectUrl); return; } } } catch (Exception ex) { log.Error(ex); //TODO: show generic error on the page } }
private void btnMakePayment_Click(object sender, EventArgs e) { if (store != null && cart != null && IsValidForCheckout()) { IPaymentGateway gateway = commerceConfig.GetDirectPaymentGateway(); if (gateway == null) { lblMessage.Text = WebStoreResources.PaymentGatewayNotConfiguredForDirectCardProcessing; btnMakePayment.Enabled = false; return; } gateway.MerchantInvoiceNumber = cart.CartGuid.ToString("N"); var cartItems = new List <string>(); foreach (var cartOffer in cart.CartOffers) { cartItems.Add($"({cartOffer.Quantity}x) {cartOffer.Name} {cartOffer.OfferPrice.ToString("c", currencyCulture)} (GUID: {cartOffer.OfferGuid:N})"); } gateway.MerchantTransactionDescription = string.Join("\n", cartItems); gateway.CardType = ddCardType.SelectedValue; gateway.CardNumber = txtCardNumber.Text; gateway.CardExpiration = ddExpireMonth.SelectedValue + ddExpireYear.SelectedValue; gateway.ChargeTotal = cart.OrderTotal; gateway.CardSecurityCode = txtCardSecurityCode.Text; gateway.CardOwnerFirstName = txtCardOwnerFirstName.Text; gateway.CardOwnerLastName = txtCardOwnerLastName.Text; gateway.CardOwnerCompanyName = cart.OrderInfo.BillingCompany; gateway.CardBillingAddress = cart.OrderInfo.BillingAddress1 + " " + cart.OrderInfo.BillingAddress2; gateway.CardBillingCity = cart.OrderInfo.BillingCity; gateway.CardBillingState = cart.OrderInfo.BillingState; gateway.CardBillingPostalCode = cart.OrderInfo.BillingPostalCode; gateway.CardBillingCountry = cart.OrderInfo.BillingCountry; gateway.CardBillingCountryCode = cart.OrderInfo.BillingCountry; gateway.CardBillingPhone = cart.OrderInfo.CustomerTelephoneDay; gateway.CustomerIPAddress = SiteUtils.GetIP4Address(); gateway.CurrencyCulture = currencyCulture; // this is where the actual request is made, it can timeout here bool executed; try { executed = gateway.ExecuteTransaction(); } catch (WebException ex) { if (commerceConfig.PaymentGatewayUseTestMode) { lblMessage.Text = ex.Message; } else { lblMessage.Text = WebStoreResources.PaymentGatewayCouldNotConnectMessage; } return; } var serializedCart = string.Empty; gateway.LogTransaction( siteSettings.SiteGuid, store.ModuleGuid, store.Guid, cart.CartGuid, cart.UserGuid, string.Empty, "WebStoreCheckout", serializedCart ); if (executed) { switch (gateway.Response) { case PaymentGatewayResponse.Approved: cart.LastUserActivity = DateTime.UtcNow; cart.OrderInfo.CompletedFromIP = SiteUtils.GetIP4Address(); cart.OrderInfo.Completed = DateTime.UtcNow; StoreHelper.EnsureUserForOrder(cart); cart.Save(); Order order = Order.CreateOrder(store, cart, gateway, siteSettings.GetCurrency().Code, "CreditCard"); StoreHelper.ClearCartCookie(cart.StoreGuid); // send confirmation email try { // this also happens in StoreHelper.ConfirmOrder StoreHelper.ConfirmOrder(store, order); PayPalLog.DeleteByCart(order.OrderGuid); GoogleCheckoutLog.DeleteByCart(order.OrderGuid); } catch (Exception ex) { log.Error("error sending confirmation email", ex); } // redirect to order details string redirectUrl = SiteRoot + "/WebStore/OrderDetail.aspx?pageid=" + pageId.ToInvariantString() + "&mid=" + moduleId.ToInvariantString() + "&orderid=" + order.OrderGuid.ToString(); //TODO: if we charged a card here we can safely delete any paypal log or googlecheckout logs // need methods to delete those by carguid if (WebStoreConfiguration.LogCardTransactionStatus) { log.Info("accepted transaction " + gateway.ChargeTotal.ToString("c") + " " + gateway.ResponseCode + " " + gateway.ResponseReason); } WebUtils.SetupRedirect(this, redirectUrl); return; case PaymentGatewayResponse.Declined: lblMessage.Text = WebStoreResources.TransactionDeclinedMessage; if (WebStoreConfiguration.LogCardTransactionStatus || WebStoreConfiguration.LogCardFailedTransactionStatus) { log.Info("declined transaction " + gateway.ChargeTotal.ToString("c") + " " + gateway.ResponseCode + " " + gateway.ResponseReason); } break; case PaymentGatewayResponse.Error: if (gateway.UseTestMode) { if (gateway.LastExecutionException != null) { lblMessage.Text = gateway.LastExecutionException.ToString(); } else { // TODO: should not show user real messages? Mask CCNumber and login credentials in the gateways RawResponse property ... those shouldn't be logged either lblMessage.Text = gateway.RawResponse; } } else { lblMessage.Text = WebStoreResources.TransactionErrorMessage; if (WebStoreConfiguration.LogCardTransactionStatus || WebStoreConfiguration.LogCardFailedTransactionStatus) { if (gateway.LastExecutionException != null) { log.Info("transaction error " + gateway.LastExecutionException.ToString()); } } } break; case PaymentGatewayResponse.NoRequestInitiated: lblMessage.Text = WebStoreResources.TransactionNotInitiatedMessage; break; } } else { lblMessage.Text = WebStoreResources.TransactionNotInitiatedMessage + (!string.IsNullOrEmpty(gateway.ResponseReason) ? "<br>" + gateway.ResponseReason : string.Empty); if (gateway.LastExecutionException != null) { if (commerceConfig.PaymentGatewayUseTestMode) { lblMessage.Text = gateway.LastExecutionException.ToString(); } } } } btnMakePayment.Text = WebStoreResources.PaymentButton; }
public abstract string HandleRequestAndReturnUrlForRedirect( HttpContext context, string payPalToken, string payPalPayerId, PayPalLog setExpressCheckoutLog);
private void DoPayPalExpressCeckout() { PayPalExpressGateway gateway = new PayPalExpressGateway( commerceConfig.PayPalAPIUsername, commerceConfig.PayPalAPIPassword, commerceConfig.PayPalAPISignature, commerceConfig.PayPalStandardEmailAddress); gateway.UseTestMode = commerceConfig.PaymentGatewayUseTestMode; gateway.MerchantCartId = cart.CartGuid.ToString(); gateway.ChargeTotal = cart.OrderTotal; string siteRoot = SiteUtils.GetNavigationSiteRoot(); gateway.ReturnUrl = siteRoot + "/Services/PayPalReturnHandler.ashx"; gateway.CancelUrl = siteRoot + Request.RawUrl; //Currency currency = new Currency(store.DefaultCurrencyId); gateway.CurrencyCode = siteSettings.GetCurrency().Code; gateway.OrderDescription = store.Name + " " + WebStoreResources.OrderHeading; gateway.BuyerEmail = cart.OrderInfo.CustomerEmail; gateway.ShipToFirstName = cart.OrderInfo.DeliveryFirstName; gateway.ShipToLastName = cart.OrderInfo.DeliveryLastName; gateway.ShipToAddress = cart.OrderInfo.DeliveryAddress1; gateway.ShipToAddress2 = cart.OrderInfo.DeliveryAddress2; gateway.ShipToCity = cart.OrderInfo.DeliveryCity; gateway.ShipToState = cart.OrderInfo.DeliveryState; gateway.ShipToCountry = cart.OrderInfo.DeliveryCountry; gateway.ShipToPostalCode = cart.OrderInfo.DeliveryPostalCode; gateway.ShipToPhone = cart.OrderInfo.CustomerTelephoneDay; // this tells paypal to use the shipping address we pass in // rather than what the customer has on file // when we implement shippable products we'll do shipping calculations before // sending the user to paypal //gateway.OverrideShippingAddress = true; //commented out the above, we want user to be able to populate shipping info from their paypal account bool executed = gateway.CallSetExpressCheckout(); if (executed) { //TODO: log the raw response if (gateway.PayPalExpressUrl.Length > 0) { // record the gateway.PayPalToken PayPalLog payPalLog = new PayPalLog(); payPalLog.RawResponse = gateway.RawResponse; payPalLog.ProviderName = WebStorePayPalReturnHandler.ProviderName; payPalLog.ReturnUrl = siteRoot + Request.RawUrl; payPalLog.Token = HttpUtility.UrlDecode(gateway.PayPalToken); payPalLog.RequestType = "SetExpressCheckout"; //payPalLog.PendingReason = gateway.PayPalExpressUrl; cart.SerializeCartOffers(); payPalLog.SerializedObject = SerializationHelper.SerializeToString(cart); payPalLog.CartGuid = cart.CartGuid; payPalLog.SiteGuid = store.SiteGuid; payPalLog.StoreGuid = store.Guid; payPalLog.UserGuid = cart.UserGuid; payPalLog.Save(); Response.Redirect(gateway.PayPalExpressUrl); } else { if (commerceConfig.PaymentGatewayUseTestMode) lblMessage.Text = gateway.RawResponse; } } else { lblMessage.Text = WebStoreResources.TransactionNotInitiatedMessage; if (gateway.LastExecutionException != null) { if (commerceConfig.PaymentGatewayUseTestMode) lblMessage.Text = gateway.LastExecutionException.ToString(); } else { if (commerceConfig.PaymentGatewayUseTestMode) lblMessage.Text = gateway.RawResponse; } } }
private static PayPalLog CreatePayPalStandardCheckoutLog( Cart cart, Store store, string siteRoot, int pageId, int moduleId) { PayPalLog payPalLog = new PayPalLog(); payPalLog.ProviderName = "WebStorePayPalHandler"; payPalLog.PDTProviderName = "WebStorePayPalPDTHandlerProvider"; payPalLog.IPNProviderName = "WebStorePayPalIPNHandlerProvider"; payPalLog.ReturnUrl = siteRoot + "/WebStore/OrderDetail.aspx?pageid=" + pageId.ToInvariantString() + "&mid=" + moduleId.ToInvariantString() + "&orderid=" + cart.CartGuid.ToString(); payPalLog.RequestType = "StandardCheckout"; cart.SerializeCartOffers(); payPalLog.SerializedObject = SerializationHelper.SerializeToString(cart); //Currency currency = new Currency(store.DefaultCurrencyId); payPalLog.CartGuid = cart.CartGuid; //Store store = new Store(cart.StoreGuid); payPalLog.SiteGuid = store.SiteGuid; payPalLog.StoreGuid = store.Guid; payPalLog.UserGuid = cart.UserGuid; payPalLog.CartTotal = cart.OrderTotal; //payPalLog.CurrencyCode = currency.Code; SiteSettings siteSettings = CacheHelper.GetCurrentSiteSettings(); payPalLog.CurrencyCode = siteSettings.GetCurrency().Code; payPalLog.Save(); return payPalLog; }
// we are using the paypal log with a different request type rather than making a new log specifically for WorldPay private static PayPalLog CreateWorldPayCheckoutLog( Cart cart, Store store, string siteRoot, string storePageUrl, int pageId, int moduleId) { PayPalLog worldPayLog = new PayPalLog(); worldPayLog.ProviderName = "WebStoreWorldPayResponseHandler"; worldPayLog.RequestType = "WorldPay"; worldPayLog.RawResponse = storePageUrl; worldPayLog.ReturnUrl = siteRoot + "/WebStore/OrderDetail.aspx?pageid=" + pageId.ToInvariantString() + "&mid=" + moduleId.ToInvariantString() + "&orderid=" + cart.CartGuid.ToString(); cart.SerializeCartOffers(); worldPayLog.SerializedObject = SerializationHelper.SerializeToString(cart); worldPayLog.CartGuid = cart.CartGuid; worldPayLog.SiteGuid = store.SiteGuid; worldPayLog.StoreGuid = store.Guid; worldPayLog.UserGuid = cart.UserGuid; worldPayLog.CartTotal = cart.OrderTotal; SiteSettings siteSettings = CacheHelper.GetCurrentSiteSettings(); worldPayLog.CurrencyCode = siteSettings.GetCurrency().Code; worldPayLog.Save(); return worldPayLog; }
public ActionResult ProcessPayment(UserPackageAddOnPaymentInformation model) { if (model.UserPackageID > 0) { return(RedirectToAction("ProcessPaypalPayment", "Paypal", new { userpackageid = model.UserPackageID })); } var userid = User.Identity.GetUserId(); if (ModelState.IsValid) { var userPackage = db.UserPackages.Where(a => a.Id == model.UserPackageID).FirstOrDefault(); var finalPrice = userPackage.TotalPrice + userPackage.TaxAmount + userPackage.TipAmount; IPaymentMethod _paymentMethod = new PayPalDirectPaymentProcessor(); ProcessPaymentRequest processPaymentRequest = new ProcessPaymentRequest(); processPaymentRequest.OrderTotal = finalPrice; processPaymentRequest.CreditCardName = model.NameOnCard; processPaymentRequest.CreditCardNumber = model.CardNumber; processPaymentRequest.CreditCardCvv2 = model.CardSecurityCode; processPaymentRequest.CreditCardExpireMonth = model.CardExpiryMonth; processPaymentRequest.CreditCardExpireYear = model.CardExpiryYear; processPaymentRequest.CustomerId = User.Identity.GetUserId();; if (processPaymentRequest.OrderGuid == Guid.Empty) { processPaymentRequest.OrderGuid = Guid.NewGuid(); } try { ProcessPaymentResult processPaymentResult = null; processPaymentResult = _paymentMethod.ProcessPayment(processPaymentRequest); if (processPaymentResult.Success) { PayPalLog log = new PayPalLog() { ACK = "SUCCESS", ApiSatus = string.Empty, BillingAggrementID = processPaymentResult.CaptureTransactionId, CorrelationID = string.Empty, ECToken = string.Empty, ResponseError = string.Empty, ResponseRedirectURL = string.Empty, ServerDate = DateTime.Now, TimeStamp = DateTime.Now.ToString(), UserId = userid, SubscriptionID = model.UserPackageID }; db.PayPalLogs.Add(log); db.SaveChanges(); //Save USer Logs UserTransaction _transaction = new UserTransaction() { Userid = userPackage.UserId, PaypalId = processPaymentResult.CaptureTransactionId, TransactionDate = DateTime.Now, Amount = finalPrice, PackageId = userPackage.Id, Details = "No Details", BillingAggrementID = processPaymentResult.CaptureTransactionId }; db.UserTransactions.Add(_transaction); db.SaveChanges(); //Logic to disable autorenew if Billingagreement is null //Logic to update Transaction status if (userPackage != null) { string message = string.Empty; string responseString = string.Empty; var package = db.Packages.FirstOrDefault(a => a.PackageId == userPackage.PackageId); PaypalAutoPayment paypalAutoPayment = new PaypalAutoPayment(); paypalAutoPayment.UserPackageID = userPackage.Id; paypalAutoPayment.UserID = userPackage.UserId; paypalAutoPayment.IsPaid = true; paypalAutoPayment.GrossAmount = String.Format("{0:0.00}", finalPrice); //Convert.ToString(finalPrice); paypalAutoPayment.PaymentStatus = "COMPLETED"; paypalAutoPayment.PaymentDate = DateTime.Now.ToString(); paypalAutoPayment.TrasactionID = processPaymentResult.CaptureTransactionId; paypalAutoPayment.BillingAggrementID = processPaymentResult.CaptureTransactionId; paypalAutoPayment.TransactionDate = DateTime.Now; DateTime currentDate = DateTime.Now; DateTime serviceDate = currentDate; if (userPackage.ServiceDay == currentDate.DayOfWeek.ToString()) { serviceDate = currentDate.AddDays(7); } else { DateTime nextServiceDate; for (int i = 1; i <= 6; i++) { if (i == 1) { nextServiceDate = currentDate.AddDays(i); if (userPackage.ServiceDay == nextServiceDate.DayOfWeek.ToString()) { if (userPackage.SubscriptionTypeId == 1) { serviceDate = nextServiceDate.AddDays(7); } else if (userPackage.SubscriptionTypeId == 2) { serviceDate = nextServiceDate.AddDays(14); } else if (userPackage.SubscriptionTypeId == 3) { serviceDate = nextServiceDate.AddDays(28); } else { serviceDate = nextServiceDate.AddDays(7); } break; } } else { nextServiceDate = currentDate.AddDays(i); if (userPackage.ServiceDay == nextServiceDate.DayOfWeek.ToString()) { serviceDate = currentDate.AddDays(i); break; } } } } paypalAutoPayment.ServiceDate = serviceDate; paypalAutoPayment.CreatedOn = DateTime.Now; db.PaypalAutoPayments.Add(paypalAutoPayment); db.SaveChanges(); if (paypalAutoPayment.IsPaid) { userPackage.PaymentRecieved = true; userPackage.IsActive = true; userPackage.NextServiceDate = serviceDate; userPackage.PaymentMethodName = "credit card"; db.Entry(userPackage).State = EntityState.Modified; db.SaveChanges(); var addOnsServices = userPackage.UserPackagesAddons.ToList(); foreach (var addOns in addOnsServices) { if (!addOns.NextServiceDate.HasValue) { addOns.NextServiceDate = serviceDate; db.SaveChanges(); } } } } Session["NewServiceCarTypeId"] = null; Session["SelectedCar"] = null; Session["NewServiceGarageId"] = null; var userInfo = userPackage.AspNetUser; // Send Notification Mail Admin for buy new subscrition. _workflowMessageService.SendNewSubscriptionNotificationToAdmin(userInfo.FirstName + " " + userInfo.LastName, userInfo.UserName, userPackage.Package.Package_Name, userPackage.SubscribedDate.ToString(), userPackage.CarUser.Garage.Garage_Name); return(RedirectToRoute("Completed", new { id = model.UserPackageID })); } foreach (var error in processPaymentResult.Errors) { model.Warnings.Add(error); } } catch (Exception exc) { model.Warnings.Add(exc.Message); } } model.UserPackge = db.UserPackages.Where(a => a.Id == model.UserPackageID).FirstOrDefault(); model.Addons = db.UserPackagesAddons.Where(a => a.UserPackageID == model.UserPackageID); //adding tax if (db.Taxes != null && db.Taxes.Count() > 0) { var taxPercentage = db.Taxes.Select(a => a.TaxPercentage).Sum(); model.UserPackge.TaxAmount = model.TaxAmount = model.UserPackge.TotalPrice * (taxPercentage / 100); model.TaxPercentage = taxPercentage; db.SaveChanges(); } //CC types model.CreditCardTypes.Add(new SelectListItem { Text = "Visa", Value = "Visa", }); model.CreditCardTypes.Add(new SelectListItem { Text = "Master card", Value = "MasterCard", }); model.CreditCardTypes.Add(new SelectListItem { Text = "Discover", Value = "Discover", }); model.CreditCardTypes.Add(new SelectListItem { Text = "Amex", Value = "Amex", }); //years model.ExpireYears.Add(new SelectListItem { Text = "Year", Value = "", }); for (int i = 0; i < 25; i++) { string year = Convert.ToString(DateTime.Now.Year + i); model.ExpireYears.Add(new SelectListItem { Text = year, Value = year, }); } //months //months model.ExpireMonths.Add(new SelectListItem { Text = "Month", Value = "", }); for (int i = 1; i <= 12; i++) { string text = (i < 10) ? "0" + i : i.ToString(); model.ExpireMonths.Add(new SelectListItem { Text = text, Value = i.ToString(), }); } return(View(model)); }
public override string HandleRequestAndReturnUrlForRedirect( HttpContext context, string payPalToken, string payPalPayerId, PayPalLog setExpressCheckoutLog) { string redirectUrl = string.Empty; if ((payPalToken == null) || (payPalToken.Length == 0)) { log.Error("WebStorePayPalReturnHandler received empty payPalToken"); return(redirectUrl); } if (setExpressCheckoutLog == null) { log.Error("WebStorePayPalReturnHandler received null setExpressCheckoutLog for payPalToken " + payPalToken); return(redirectUrl); } if (setExpressCheckoutLog.SerializedObject.Length == 0) { log.Error("WebStorePayPalReturnHandler cart was not previously serialized for payPalToken " + payPalToken); return(redirectUrl); } if (setExpressCheckoutLog.CreatedUtc.AddHours(4) < DateTime.UtcNow) { log.Error("payPalToken " + payPalToken + " was more than 4 hours old, it should expire after 3 hours "); return(redirectUrl); } CommerceConfiguration commerceConfig = SiteUtils.GetCommerceConfig(); PayPalExpressGateway gateway = new PayPalExpressGateway( commerceConfig.PayPalAPIUsername, commerceConfig.PayPalAPIPassword, commerceConfig.PayPalAPISignature, commerceConfig.PayPalStandardEmailAddress); gateway.UseTestMode = commerceConfig.PaymentGatewayUseTestMode; gateway.PayPalToken = payPalToken; gateway.PayPalPayerId = payPalPayerId; Cart savedCart = (Cart)SerializationHelper.DeserializeFromString(typeof(Cart), setExpressCheckoutLog.SerializedObject); savedCart.DeSerializeCartOffers(); string siteRoot = SiteUtils.GetNavigationSiteRoot(); gateway.MerchantCartId = savedCart.CartGuid.ToString(); gateway.ChargeTotal = savedCart.OrderTotal; gateway.ReturnUrl = siteRoot + "/Services/PayPalReturnHandler.ashx"; gateway.CancelUrl = siteRoot; //gateway.PayPalPayerId = payPalPayerId; gateway.CallGetExpressCheckoutDetails(); PayPalLog payPalLog = new PayPalLog(); payPalLog.ProviderName = WebStorePayPalReturnHandler.ProviderName; payPalLog.SerializedObject = setExpressCheckoutLog.SerializedObject; payPalLog.ReturnUrl = setExpressCheckoutLog.ReturnUrl; payPalLog.RawResponse = gateway.RawResponse; payPalLog.TransactionId = gateway.TransactionId; payPalLog.CurrencyCode = gateway.CurrencyCode; // TODO: add versions to gateways //log.ApiVersion = gateway. payPalLog.CartGuid = savedCart.CartGuid; Store store = new Store(savedCart.StoreGuid); payPalLog.Token = payPalToken; payPalLog.PayerId = payPalPayerId; payPalLog.RequestType = "GetExpressCheckoutDetails"; payPalLog.SiteGuid = store.SiteGuid; payPalLog.StoreGuid = store.Guid; payPalLog.UserGuid = savedCart.UserGuid; // update the order with customer shipping info savedCart.OrderInfo.DeliveryCompany = gateway.ShipToCompanyName; savedCart.OrderInfo.DeliveryAddress1 = gateway.ShipToAddress; savedCart.OrderInfo.DeliveryAddress2 = gateway.ShipToAddress2; savedCart.OrderInfo.DeliveryCity = gateway.ShipToCity; savedCart.OrderInfo.DeliveryFirstName = gateway.ShipToFirstName; savedCart.OrderInfo.DeliveryLastName = gateway.ShipToLastName; savedCart.OrderInfo.DeliveryPostalCode = gateway.ShipToPostalCode; savedCart.OrderInfo.DeliveryState = gateway.ShipToState; savedCart.OrderInfo.DeliveryCountry = gateway.ShipToCountry; //Note that PayPal only returns a phone number if your Merchant accounts is configured to require the // buyer to provide it. if (gateway.ShipToPhone.Length > 0) { savedCart.OrderInfo.CustomerTelephoneDay = gateway.ShipToPhone; } if (gateway.BuyerEmail.Length > 0) { savedCart.OrderInfo.CustomerEmail = gateway.BuyerEmail; } // if customer and billing aren't populated already, user was anonymous when checkout began, make them the same as shipping //if (savedCart.UserGuid == Guid.Empty) //{ //2013-12-23 since all we get is shipping address this can be considered as the same thing as billing address for paypal purposes so always use it // especially because we may need to calculate tax for express checkout // based on the address provided by paypal savedCart.CopyShippingToBilling(); savedCart.CopyShippingToCustomer(); //} GeoCountry country = new GeoCountry(savedCart.OrderInfo.DeliveryCountry); GeoZone taxZone = GeoZone.GetByCode(country.Guid, savedCart.OrderInfo.DeliveryState); savedCart.OrderInfo.TaxZoneGuid = taxZone.Guid; savedCart.OrderInfo.Save(); // refresh totals to calculate tax or shipping now that we have an address savedCart.RefreshTotals(); savedCart.Save(); savedCart.SerializeCartOffers(); payPalLog.SerializedObject = SerializationHelper.SerializeToString(savedCart); payPalLog.Save(); if (gateway.Response == PaymentGatewayResponse.Error) { redirectUrl = siteRoot + "/WebStore/PayPalGatewayError.aspx?plog=" + payPalLog.RowGuid.ToString(); return(redirectUrl); } if (gateway.PayPalPayerId.Length == 0) { redirectUrl = siteRoot + "/WebStore/PayPalGatewayError.aspx?plog=" + payPalLog.RowGuid.ToString(); return(redirectUrl); } int pageId = -1; List <PageModule> pageModules = PageModule.GetPageModulesByModule(store.ModuleId); foreach (PageModule pm in pageModules) { // use first pageid found, really a store should only // be on one page pageId = pm.PageId; break; } // after the CallGetExpressCheckoutDetails // we have the option of directing to a final review page before // calling CallDoExpressCheckoutPayment redirectUrl = siteRoot + "/WebStore/PayPalExpressCheckout.aspx?pageid=" + pageId.ToString(CultureInfo.InvariantCulture) + "&mid=" + store.ModuleId.ToString(CultureInfo.InvariantCulture) + "&plog=" + payPalLog.RowGuid.ToString(); return(redirectUrl); }
private void DoPayPalExpressCeckout() { PayPalExpressGateway gateway = new PayPalExpressGateway( commerceConfig.PayPalAPIUsername, commerceConfig.PayPalAPIPassword, commerceConfig.PayPalAPISignature, commerceConfig.PayPalStandardEmailAddress); gateway.UseTestMode = commerceConfig.PaymentGatewayUseTestMode; gateway.MerchantCartId = cart.CartGuid.ToString(); gateway.ChargeTotal = cart.OrderTotal; string siteRoot = SiteUtils.GetNavigationSiteRoot(); gateway.ReturnUrl = siteRoot + "/Services/PayPalReturnHandler.ashx"; gateway.CancelUrl = siteRoot + Request.RawUrl; //Currency currency = new Currency(store.DefaultCurrencyId); //gateway.CurrencyCode = currency.Code; gateway.CurrencyCode = siteSettings.GetCurrency().Code; gateway.OrderDescription = store.Name + " " + WebStoreResources.OrderHeading; gateway.BuyerEmail = cart.OrderInfo.CustomerEmail; gateway.ShipToFirstName = cart.OrderInfo.DeliveryFirstName; gateway.ShipToLastName = cart.OrderInfo.DeliveryLastName; gateway.ShipToAddress = cart.OrderInfo.DeliveryAddress1; gateway.ShipToAddress2 = cart.OrderInfo.DeliveryAddress2; gateway.ShipToCity = cart.OrderInfo.DeliveryCity; gateway.ShipToState = cart.OrderInfo.DeliveryState; gateway.ShipToCountry = cart.OrderInfo.DeliveryCountry; gateway.ShipToPostalCode = cart.OrderInfo.DeliveryPostalCode; gateway.ShipToPhone = cart.OrderInfo.CustomerTelephoneDay; // this tells paypal to use the shipping address we pass in // rather than what the customer has on file // when we implement shippable products we'll do shipping calculations before // sending the user to paypal //gateway.OverrideShippingAddress = true; //commented out the above, we want user to be able to populate shipping info from their paypal account bool executed = gateway.CallSetExpressCheckout(); if (executed) { //TODO: log the raw response if (gateway.PayPalExpressUrl.Length > 0) { // record the gateway.PayPalToken PayPalLog payPalLog = new PayPalLog(); payPalLog.RawResponse = gateway.RawResponse; payPalLog.ProviderName = "WebStorePayPalHandler"; payPalLog.ReturnUrl = siteRoot + Request.RawUrl; payPalLog.Token = HttpUtility.UrlDecode(gateway.PayPalToken); payPalLog.RequestType = "SetExpressCheckout"; cart.SerializeCartOffers(); payPalLog.SerializedObject = SerializationHelper.SerializeToString(cart); payPalLog.CartGuid = cart.CartGuid; payPalLog.SiteGuid = store.SiteGuid; payPalLog.StoreGuid = store.Guid; payPalLog.UserGuid = cart.UserGuid; payPalLog.Save(); Response.Redirect(gateway.PayPalExpressUrl); } } }
public override string HandleRequestAndReturnUrlForRedirect( HttpContext context, string payPalToken, string payPalPayerId, PayPalLog setExpressCheckoutLog) { string redirectUrl = string.Empty; if ((payPalToken == null) || (payPalToken.Length == 0)) { log.Error("WebStorePayPalReturnHandler received empty payPalToken"); return redirectUrl; } if (setExpressCheckoutLog == null) { log.Error("WebStorePayPalReturnHandler received null setExpressCheckoutLog for payPalToken " + payPalToken); return redirectUrl; } if (setExpressCheckoutLog.SerializedObject.Length == 0) { log.Error("WebStorePayPalReturnHandler cart was not previously serialized for payPalToken " + payPalToken); return redirectUrl; } if (setExpressCheckoutLog.CreatedUtc.AddHours(4) < DateTime.UtcNow) { log.Error("payPalToken " + payPalToken + " was more than 4 hours old, it should expire after 3 hours "); return redirectUrl; } CommerceConfiguration commerceConfig = SiteUtils.GetCommerceConfig(); PayPalExpressGateway gateway = new PayPalExpressGateway( commerceConfig.PayPalAPIUsername, commerceConfig.PayPalAPIPassword, commerceConfig.PayPalAPISignature, commerceConfig.PayPalStandardEmailAddress); gateway.UseTestMode = commerceConfig.PaymentGatewayUseTestMode; gateway.PayPalToken = payPalToken; gateway.PayPalPayerId = payPalPayerId; Cart savedCart = (Cart)SerializationHelper.DeserializeFromString(typeof(Cart), setExpressCheckoutLog.SerializedObject); savedCart.DeSerializeCartOffers(); string siteRoot = SiteUtils.GetNavigationSiteRoot(); gateway.MerchantCartId = savedCart.CartGuid.ToString(); gateway.ChargeTotal = savedCart.OrderTotal; gateway.ReturnUrl = siteRoot + "/Services/PayPalReturnHandler.ashx"; gateway.CancelUrl = siteRoot; //gateway.PayPalPayerId = payPalPayerId; gateway.CallGetExpressCheckoutDetails(); PayPalLog payPalLog = new PayPalLog(); payPalLog.ProviderName = WebStorePayPalReturnHandler.ProviderName; payPalLog.SerializedObject = setExpressCheckoutLog.SerializedObject; payPalLog.ReturnUrl = setExpressCheckoutLog.ReturnUrl; payPalLog.RawResponse = gateway.RawResponse; payPalLog.TransactionId = gateway.TransactionId; payPalLog.CurrencyCode = gateway.CurrencyCode; // TODO: add versions to gateways //log.ApiVersion = gateway. payPalLog.CartGuid = savedCart.CartGuid; Store store = new Store(savedCart.StoreGuid); payPalLog.Token = payPalToken; payPalLog.PayerId = payPalPayerId; payPalLog.RequestType = "GetExpressCheckoutDetails"; payPalLog.SiteGuid = store.SiteGuid; payPalLog.StoreGuid = store.Guid; payPalLog.UserGuid = savedCart.UserGuid; // update the order with customer shipping info savedCart.OrderInfo.DeliveryCompany = gateway.ShipToCompanyName; savedCart.OrderInfo.DeliveryAddress1 = gateway.ShipToAddress; savedCart.OrderInfo.DeliveryAddress2 = gateway.ShipToAddress2; savedCart.OrderInfo.DeliveryCity = gateway.ShipToCity; savedCart.OrderInfo.DeliveryFirstName = gateway.ShipToFirstName; savedCart.OrderInfo.DeliveryLastName = gateway.ShipToLastName; savedCart.OrderInfo.DeliveryPostalCode = gateway.ShipToPostalCode; savedCart.OrderInfo.DeliveryState = gateway.ShipToState; savedCart.OrderInfo.DeliveryCountry = gateway.ShipToCountry; //Note that PayPal only returns a phone number if your Merchant accounts is configured to require the // buyer to provide it. if (gateway.ShipToPhone.Length > 0) { savedCart.OrderInfo.CustomerTelephoneDay = gateway.ShipToPhone; } if (gateway.BuyerEmail.Length > 0) { savedCart.OrderInfo.CustomerEmail = gateway.BuyerEmail; } // if customer and billing aren't populated already, user was anonymous when checkout began, make them the same as shipping //if (savedCart.UserGuid == Guid.Empty) //{ //2013-12-23 since all we get is shipping address this can be considered as the same thing as billing address for paypal purposes so always use it // especially because we may need to calculate tax for express checkout // based on the address provided by paypal savedCart.CopyShippingToBilling(); savedCart.CopyShippingToCustomer(); //} GeoCountry country = new GeoCountry(savedCart.OrderInfo.DeliveryCountry); GeoZone taxZone = GeoZone.GetByCode(country.Guid, savedCart.OrderInfo.DeliveryState); savedCart.OrderInfo.TaxZoneGuid = taxZone.Guid; savedCart.OrderInfo.Save(); // refresh totals to calculate tax or shipping now that we have an address savedCart.RefreshTotals(); savedCart.Save(); savedCart.SerializeCartOffers(); payPalLog.SerializedObject = SerializationHelper.SerializeToString(savedCart); payPalLog.Save(); if (gateway.Response == PaymentGatewayResponse.Error) { redirectUrl = siteRoot + "/WebStore/PayPalGatewayError.aspx?plog=" + payPalLog.RowGuid.ToString(); return redirectUrl; } if (gateway.PayPalPayerId.Length == 0) { redirectUrl = siteRoot + "/WebStore/PayPalGatewayError.aspx?plog=" + payPalLog.RowGuid.ToString(); return redirectUrl; } int pageId = -1; List<PageModule> pageModules = PageModule.GetPageModulesByModule(store.ModuleId); foreach (PageModule pm in pageModules) { // use first pageid found, really a store should only // be on one page pageId = pm.PageId; break; } // after the CallGetExpressCheckoutDetails // we have the option of directing to a final review page before // calling CallDoExpressCheckoutPayment redirectUrl = siteRoot + "/WebStore/PayPalExpressCheckout.aspx?pageid=" + pageId.ToString(CultureInfo.InvariantCulture) + "&mid=" + store.ModuleId.ToString(CultureInfo.InvariantCulture) + "&plog=" + payPalLog.RowGuid.ToString(); return redirectUrl; }
private void btnMakePayment_Click(object sender, System.EventArgs e) { //Page.Validate(); if ( (store != null) && (cart != null) && (IsValidForCheckout()) ) { IPaymentGateway gateway = commerceConfig.GetDirectPaymentGateway(); if (gateway == null) { lblMessage.Text = WebStoreResources.PaymentGatewayNotConfiguredForDirectCardProcessing; btnMakePayment.Enabled = false; return; } //if (gateway is PlugNPayPaymentGateway) //{ gateway.MerchantInvoiceNumber = cart.CartGuid.ToString("N"); string CartItems = ""; int itemnum = 0; foreach (CartOffer coffer in cart.CartOffers) { itemnum++; CartItems += string.Format("&item{1}={0}&cost{1}={2}&description{1}={3}&quantity{1}={4}", coffer.OfferGuid, itemnum, coffer.OfferPrice, coffer.Name, coffer.Quantity); } gateway.MerchantTransactionDescription = CartItems; //not sure if this is the intended purpose or not //} gateway.CardType = ddCardType.SelectedValue; gateway.CardNumber = txtCardNumber.Text; gateway.CardExpiration = ddExpireMonth.SelectedValue + ddExpireYear.SelectedValue; gateway.ChargeTotal = cart.OrderTotal; gateway.CardSecurityCode = txtCardSecurityCode.Text; gateway.CardOwnerFirstName = txtCardOwnerFirstName.Text; gateway.CardOwnerLastName = txtCardOwnerLastName.Text; gateway.CardOwnerCompanyName = cart.OrderInfo.BillingCompany; gateway.CardBillingAddress = cart.OrderInfo.BillingAddress1 + " " + cart.OrderInfo.BillingAddress2; gateway.CardBillingCity = cart.OrderInfo.BillingCity; gateway.CardBillingState = cart.OrderInfo.BillingState; gateway.CardBillingPostalCode = cart.OrderInfo.BillingPostalCode; gateway.CardBillingCountry = cart.OrderInfo.BillingCountry; gateway.CardBillingCountryCode = cart.OrderInfo.BillingCountry; gateway.CardBillingPhone = cart.OrderInfo.CustomerTelephoneDay; gateway.CustomerIPAddress = SiteUtils.GetIP4Address(); gateway.CurrencyCulture = currencyCulture; // this is where the actual request is made, it can timeout here bool executed = false; try { executed = gateway.ExecuteTransaction(); } catch (WebException ex) { if (commerceConfig.PaymentGatewayUseTestMode) { lblMessage.Text = ex.Message; } else { lblMessage.Text = WebStoreResources.PaymentGatewayCouldNotConnectMessage; } return; } string serializedCart = string.Empty; gateway.LogTransaction( siteSettings.SiteGuid, store.ModuleGuid, store.Guid, cart.CartGuid, cart.UserGuid, string.Empty, "WebStoreCheckout", serializedCart); //if (gateway is PayPalDirectPaymentGateway) //{ // // this is capturing of the serialized cart is not needed for other providers and I'm not sure its even needed for PayPal Direct // // it was needed for other paypal solutions. I just don't want to remove it until I'm sure // cart.SerializeCartOffers(); // serializedCart = SerializationHelper.SerializeToString(cart); // gateway.LogTransaction( // siteSettings.SiteGuid, // store.ModuleGuid, // store.Guid, // cart.CartGuid, // cart.UserGuid, // "WebStorePayPalDirect", // "DirectPayment", // serializedCart); //} //else //{ // gateway.LogTransaction( // siteSettings.SiteGuid, // store.ModuleGuid, // store.Guid, // cart.CartGuid, // cart.UserGuid, // string.Empty, // "WebStoreCheckout", // serializedCart); //} if (executed) { switch (gateway.Response) { case PaymentGatewayResponse.Approved: cart.LastUserActivity = DateTime.UtcNow; cart.OrderInfo.CompletedFromIP = SiteUtils.GetIP4Address(); cart.OrderInfo.Completed = DateTime.UtcNow; StoreHelper.EnsureUserForOrder(cart); cart.Save(); //Order order = Order.CreateOrder(store, cart, gateway, store.DefaultCurrency, "CreditCard"); Order order = Order.CreateOrder(store, cart, gateway, siteSettings.GetCurrency().Code, "CreditCard"); StoreHelper.ClearCartCookie(cart.StoreGuid); // send confirmation email try { // this also happens in StoreHelper.ConfirmOrder //Module m = new Module(store.ModuleId); //Order.EnsureSalesReportData(m.ModuleGuid, pageId, moduleId); StoreHelper.ConfirmOrder(store, order); PayPalLog.DeleteByCart(order.OrderGuid); GoogleCheckoutLog.DeleteByCart(order.OrderGuid); } catch (Exception ex) { log.Error("error sending confirmation email", ex); } // redirect to order details string redirectUrl = SiteRoot + "/WebStore/OrderDetail.aspx?pageid=" + pageId.ToInvariantString() + "&mid=" + moduleId.ToInvariantString() + "&orderid=" + order.OrderGuid.ToString(); //TODO: if we charged a card here we can safely delete any paypal log or googlecheckout logs // need methods to delete those by carguid if (WebStoreConfiguration.LogCardTransactionStatus) { log.Info("accepted transaction " + gateway.ChargeTotal.ToString("c") + " " + gateway.ResponseCode + " " + gateway.ResponseReason); } WebUtils.SetupRedirect(this, redirectUrl); return; case PaymentGatewayResponse.Declined: lblMessage.Text = WebStoreResources.TransactionDeclinedMessage; if ((WebStoreConfiguration.LogCardTransactionStatus) || (WebStoreConfiguration.LogCardFailedTransactionStatus)) { log.Info("declined transaction " + gateway.ChargeTotal.ToString("c") + " " + gateway.ResponseCode + " " + gateway.ResponseReason); } break; case PaymentGatewayResponse.Error: if (gateway.UseTestMode) { if (gateway.LastExecutionException != null) { lblMessage.Text = gateway.LastExecutionException.ToString(); } else { // TODO: should not show user real messages? Mask CCNumber and login credentials in the gateways RawResponse property ... those shouldn't be logged either lblMessage.Text = gateway.RawResponse; } } else { lblMessage.Text = WebStoreResources.TransactionErrorMessage; if ((WebStoreConfiguration.LogCardTransactionStatus) || (WebStoreConfiguration.LogCardFailedTransactionStatus)) { if (gateway.LastExecutionException != null) { log.Info("transaction error " + gateway.LastExecutionException.ToString()); } } } break; case PaymentGatewayResponse.NoRequestInitiated: lblMessage.Text = WebStoreResources.TransactionNotInitiatedMessage; break; } } else { lblMessage.Text = WebStoreResources.TransactionNotInitiatedMessage; if (gateway.LastExecutionException != null) { if (commerceConfig.PaymentGatewayUseTestMode) { lblMessage.Text = gateway.LastExecutionException.ToString(); } } } } btnMakePayment.Text = WebStoreResources.PaymentButton; }
/// <summary> /// return true if the transaction was processed with no problems /// </summary> /// <param name="context"></param> /// <param name="transactionId"></param> /// <param name="orderId"></param> /// <param name="grossAmount"></param> /// <param name="standardCheckoutLog"></param> /// <returns></returns> public override bool HandleRequest( string transactionId, NameValueCollection form, PayPalLog standardCheckoutLog) { bool result = false; if (standardCheckoutLog.SerializedObject.Length == 0) { return result; } Cart cart = (Cart)SerializationHelper.DeserializeFromString(typeof(Cart), standardCheckoutLog.SerializedObject); Store store = new Store(cart.StoreGuid); SiteSettings siteSettings = new SiteSettings(store.SiteGuid); bool debugPayPal = WebConfigSettings.DebugPayPal; //mc_gross=5.00 //&address_status=confirmed //&item_number1=d28a6bed-7e51-4f18-a893-77b4d5665a64 //&payer_id=zzzzzz //&tax=0.00 //&address_street=nnnn //&payment_date=10%3A08%3A08+Jul+29%2C+2008+PDT //&payment_status=Completed //&charset=windows-1252 //&address_zip=92843 //&mc_shipping=0.00 //&mc_handling=0.00 //&first_name=zz //&mc_fee=0.45 //&address_country_code=US //&address_name=zzzz //¬ify_version=2.4 //&custom=d9ef5324-2201-4749-b06a-9bba7a9dce61 //&payer_status=verified //&business=sales%40mojoportal.com //&address_country=United+States //&num_cart_items=1 //&mc_handling1=0.00 //&address_city=nnnn //&verify_sign= //&payer_email=zzzzzz //&mc_shipping1=0.00 //&tax1=0.00 //&txn_id=81Y88484JA1416221 //&payment_type=instant //&payer_business_name=EBShoes //&last_name=Ngo //&address_state=CA //&item_name1=Buy+Joe+a+Beer //&receiver_email=sales%40mojoportal.com //&payment_fee=0.45 //&quantity1=1 //&receiver_id=nnnn //&txn_type=cart //&mc_gross_1=5.00 //&mc_currency=USD //&residence_country=US //&payment_gross=5.00 string firstName = string.Empty; if (form["first_name"] != null) { firstName = form["first_name"].ToString(); } string lastName = string.Empty; if (form["last_name"] != null) { lastName = form["last_name"].ToString(); } string paymentStatus = string.Empty; if (form["payment_status"] != null) { paymentStatus = form["payment_status"].ToString(); } string payerEmail = string.Empty; if (form["payer_email"] != null) { payerEmail = form["payer_email"].ToString(); } string paymentGross = string.Empty; if (form["mc_gross"] != null) { paymentGross = form["mc_gross"].ToString(); } string payPalFee = string.Empty; if (form["mc_fee"] != null) { payPalFee = form["mc_fee"].ToString(); } string payPalTax = string.Empty; if (form["tax"] != null) { payPalTax = form["tax"].ToString(); } string payPalShipping = string.Empty; if (form["mc_shipping"] != null) { payPalShipping = form["mc_shipping"].ToString(); } string currencyUsed = string.Empty; if (form["mc_currency"] != null) { currencyUsed = form["mc_currency"].ToString(); } string pendingReason = string.Empty; if (form["pending_reason"] != null) { pendingReason = form["pending_reason"].ToString(); } string reasonCode = string.Empty; if (form["reason_code"] != null) { reasonCode = form["reason_code"].ToString(); } string paymentType = string.Empty; if (form["txn_type"] != null) { paymentType = form["txn_type"].ToString(); } string payPalSettlement = "0"; if (form["settle_amount"] != null) { payPalSettlement = form["settle_amount"].ToString(); } string customerAddress = string.Empty; if (form["address_street"] != null) { customerAddress = form["address_street"].ToString(); } string customerCity = string.Empty; if (form["address_city"] != null) { customerCity = form["address_city"].ToString(); } string customerState = string.Empty; if (form["address_state"] != null) { customerState = form["address_state"].ToString(); } string customerPostalCode = string.Empty; if (form["address_zip"] != null) { customerPostalCode = form["address_zip"].ToString(); } string customerCountry = string.Empty; if (form["address_country"] != null) { customerCountry = form["address_country"].ToString(); } string customerPhone = string.Empty; if (form["contact_phone"] != null) { customerPhone = form["contact_phone"].ToString(); } string customerBusinessName = string.Empty; if (form["payer_business_name"] != null) { customerBusinessName = form["payer_business_name"].ToString(); } // TODO: we need to store this somewhere on the cart/order // its the message the user enters in special instructions on paypal checkout string customerMemo = string.Empty; if (form["memo"] != null) { customerMemo = form["memo"].ToString(); } if (debugPayPal) { log.Info("PayPal currencyUsed was " + currencyUsed); } //Regardless of the specified currency, the format will have decimal point //with exactly two digits to the right and an optional thousands separator to the left, //which must be a comma; for example, EUR 2.000,00 must be specified as 2000.00 or 2,000.00 // So we want to parse it with US Culture CultureInfo currencyCulture = new CultureInfo("en-US"); //if (currencyUsed.Length > 0) //{ // currencyCulture = ResourceHelper.GetCurrencyCulture(currencyUsed); //} //else //{ // //Currency currency = new Currency(store.DefaultCurrencyId); // //currencyCulture = ResourceHelper.GetCurrencyCulture(currency.Code); // Currency currency = siteSettings.GetCurrency(); // currencyCulture = ResourceHelper.GetCurrencyCulture(currency.Code); // currencyUsed = currency.Code; //} //if (debugPayPal) { log.Info("PayPal final currency culture was " + currencyUsed); } decimal grossAmount = 0; decimal.TryParse(paymentGross, NumberStyles.Currency, currencyCulture, out grossAmount); decimal feeAmount = 0; decimal.TryParse(payPalFee, NumberStyles.Currency, currencyCulture, out feeAmount); decimal taxAmount = 0; decimal.TryParse(payPalTax, NumberStyles.Currency, currencyCulture, out taxAmount); decimal shippingAmount = 0; decimal.TryParse(payPalShipping, NumberStyles.Currency, currencyCulture, out shippingAmount); decimal settleAmount = 0; decimal.TryParse(payPalSettlement, NumberStyles.Currency, currencyCulture, out settleAmount); if (debugPayPal) { log.Info("PayPal paymentGross was " + paymentGross + " which was parsed as " + grossAmount.ToString()); log.Info("PayPal payPalFee was " + payPalFee + " which was parsed as " + feeAmount.ToString()); log.Info("PayPal payPalTax was " + payPalTax + " which was parsed as " + taxAmount.ToString()); log.Info("PayPal payPalShipping was " + payPalShipping + " which was parsed as " + shippingAmount.ToString()); log.Info("PayPal payPalSettlement was " + payPalSettlement + " which was parsed as " + settleAmount.ToString()); } PayPalLog payPalLog = new PayPalLog(); payPalLog.PDTProviderName = standardCheckoutLog.PDTProviderName; payPalLog.IPNProviderName = standardCheckoutLog.IPNProviderName; payPalLog.ReturnUrl = standardCheckoutLog.ReturnUrl; payPalLog.ProviderName = standardCheckoutLog.ProviderName; payPalLog.SiteGuid = standardCheckoutLog.SiteGuid; payPalLog.StoreGuid = standardCheckoutLog.StoreGuid; payPalLog.UserGuid = standardCheckoutLog.UserGuid; payPalLog.ApiVersion = standardCheckoutLog.ApiVersion; payPalLog.CartGuid = standardCheckoutLog.CartGuid; payPalLog.SerializedObject = standardCheckoutLog.SerializedObject; payPalLog.CartTotal = grossAmount; payPalLog.PayPalAmt = feeAmount; if (settleAmount > 0) { payPalLog.SettleAmt = settleAmount; } else { payPalLog.SettleAmt = (grossAmount - feeAmount); } payPalLog.TaxAmt = taxAmount; payPalLog.CurrencyCode = currencyUsed; payPalLog.TransactionId = transactionId; payPalLog.RawResponse = form.ToString(); payPalLog.Response = "IPNSuccess"; payPalLog.RequestType = "IPN"; payPalLog.PayerId = payerEmail; payPalLog.PaymentType = paymentType; payPalLog.PaymentStatus = paymentStatus; payPalLog.PendingReason = pendingReason; payPalLog.ReasonCode = reasonCode; payPalLog.Save(); // see if this cart has already been proceesed Order existingOrder = new Order(cart.CartGuid); // order already exists if (existingOrder.OrderGuid != Guid.Empty) { // lookup order status if needed make it fullfillable // then redirect to order detail page if (existingOrder.StatusGuid == OrderStatus.OrderStatusReceivedGuid) { if (paymentStatus == "Completed") { existingOrder.StatusGuid = OrderStatus.OrderStatusFulfillableGuid; existingOrder.Save(); try { StoreHelper.ConfirmOrder(store, existingOrder); GoogleCheckoutLog.DeleteByCart(existingOrder.OrderGuid); } catch (Exception ex) { log.Error("error sending confirmation email", ex); } } } result = true; payPalLog.ReasonCode = "existing order found"; payPalLog.Save(); return result; } // if we get here the cart has not yet been processed into an order cart.DeSerializeCartOffers(); Guid orderStatus; if (paymentStatus == "Completed") { orderStatus = OrderStatus.OrderStatusFulfillableGuid; } else { orderStatus = OrderStatus.OrderStatusReceivedGuid; } // update the order with customer shipping info cart.OrderInfo.DeliveryCompany = customerBusinessName; cart.OrderInfo.DeliveryAddress1 = customerAddress; cart.OrderInfo.DeliveryCity = customerCity; cart.OrderInfo.DeliveryFirstName = firstName; cart.OrderInfo.DeliveryLastName = lastName; cart.OrderInfo.DeliveryPostalCode = customerPostalCode; cart.OrderInfo.DeliveryState = customerState; cart.OrderInfo.DeliveryCountry = customerCountry; if (customerPhone.Length > 0) { cart.OrderInfo.CustomerTelephoneDay = customerPhone; } if (payerEmail.Length > 0) { cart.OrderInfo.CustomerEmail = payerEmail; } cart.CopyShippingToBilling(); cart.CopyShippingToCustomer(); cart.TaxTotal = taxAmount; cart.OrderTotal = grossAmount; if (shippingAmount > 0) { cart.ShippingTotal = shippingAmount; } StoreHelper.EnsureUserForOrder(cart); cart.Save(); cart.SerializeCartOffers(); payPalLog.SerializedObject = SerializationHelper.SerializeToString(cart); payPalLog.Save(); Order order = Order.CreateOrder( store, cart, transactionId, transactionId, string.Empty, currencyUsed, "PayPal", orderStatus); if (orderStatus == OrderStatus.OrderStatusFulfillableGuid) { try { StoreHelper.ConfirmOrder(store, order); GoogleCheckoutLog.DeleteByCart(order.OrderGuid); } catch (Exception ex) { log.Error("error sending confirmation email", ex); } } if (orderStatus == OrderStatus.OrderStatusReceivedGuid) { StoreHelper.ConfirmOrderReceived(store, order); } result = true; return result; }