Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • iand123 23 posts 53 karma points
    Apr 22, 2018 @ 08:12
    iand123
    0

    PayPal IPN - SurfaceController or APIController

    Hi

    I am doing a custom ecommerce for a small umbraco site (v7). I have the passing to paypal working but now need to write my IPN (Instant Payment Notification)

    PayPal's code samples are on Github so i have that covered.

    What is the best way for me to do this in Umbraco? It wont need to show a page and i provide a URL for Paypal who tells me when a payment has been made (which then i pretty much just updated the database to mark it as paid).

    WHich type of controller is best for me to create in my Umbraco project? Ive used surface controllers to handle the addition to basket etc but as i dont need to do anything after handling the response (not like how i currently use a surface controller to redirect to the current umbraco page) i am not sure.

    ANyone done anything similar?

  • iand123 23 posts 53 karma points
    Apr 22, 2018 @ 08:29
    iand123
    0

    Code sample

    Forgot to say earlier but this is the code sample. I basically want to recreate this in Umbraco using one of the custom controllers, please help :)

  • John Sharp 4 posts 74 karma points
    Apr 22, 2018 @ 19:21
    John Sharp
    0

    Hi iand1234,

    I've done something like this in the past with a simple ASPX page. If you're not needing to get "into Umbraco" then don't.

    If you do, the do a simple handler and use Controller as a base class and handle your routing with an ApplicationEventHandler module or use the standard UmbracoApiController which will do routing for you.

    John

  • Ben Norman 166 posts 272 karma points
    Apr 22, 2018 @ 21:24
    Ben Norman
    0
    public class ContactFormForBasicECommerceSurfaceController : Umbraco.Web.Mvc.SurfaceController
    {
        public ActionResult Index(int NodeID)
        {
            var model = new ContactFormForBasicECommerceViewModel();
            model.CurrentNodeID = NodeID;
            var currentNode = Umbraco.TypedContent(model.CurrentNodeID);
            var globalSettings = currentNode.GetGlobalSettings(Umbraco);
            model.ClientId = globalSettings.UseProduction ? globalSettings.ProductionClientId : globalSettings.SandboxClientId;
            model.EnvironmentName = globalSettings.UseProduction ? EnvironmentNames.production.ToString() : EnvironmentNames.sandbox.ToString();
            return PartialView("Feature/BasicECommerce/ContactFormForBasicECommerce", model);
        }
    
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult HandleContactSubmit(ContactFormForBasicECommerceViewModel model)
        {
            string returnValue = "";
    
            var messageInfo = umbraco.library.GetDictionaryItem("USN Contact Form General Error");
            if (!ModelState.IsValid)
            {
                return JavaScript(String.Format("$(ContactError{0}).show();$(ContactError{0}).html('{1}');", model.CurrentNodeID, messageInfo));
            }
    
            //Need to get NodeID from hidden field. CurrentPage does not work with Ajax.BeginForm
            var currentNode = new Usn_Sc_ContactFormForBasicEcommerce_AN(Umbraco.TypedContent(model.CurrentNodeID));
            var websiteConfigurationSection = currentNode.GetWebsiteConfigurationSection(Umbraco);
            var globalSettings = currentNode.GetGlobalSettings(Umbraco);
    
            string websiteName = globalSettings.WebsiteName;
            string pageName = currentNode.Parent.Parent.Name;
    
            try
            {
                var voucherPaidService = new VoucherPaidService(Services.ContentService, Umbraco, websiteConfigurationSection);
                var voucher = voucherPaidService.Save(model);
                var replacements = GetReplacements(model, voucher, websiteName, pageName);
                replacements.Add("%% host %%", Request.Url.GetLeftPart(UriPartial.Authority));
    
                Stream pdf = null;
                if (voucher.Variant != null)
                {
                    var voucherData = ApplyReplacements(replacements, currentNode.VoucherTemplate.ToString());
                    pdf = HtmlToPdfService.Instance.ConvertFromHtmlString(voucherData);
                }
    
                messageInfo = umbraco.library.GetDictionaryItem("USN Contact Form Mail Send Error");
                SendContactFormMail(model, websiteName, pageName, replacements, currentNode, pdf, globalSettings);
    
                messageInfo = umbraco.library.GetDictionaryItem("USN Contact Form Signup Error");
                var newsletterService = new NewsletterService(globalSettings);
                newsletterService.Subscribe(model.NewsletterSignup, model.Email, model.FirstName, model.LastName, currentNode);
            }
            catch (Exception ex)
            {
                return JavaScript(String.Format("$(ContactError{0}).show();$(ContactError{0}).html('<div class=\"info\"><p>{1}</p><p>{2}</p></div>');",
                    model.CurrentNodeID, messageInfo, (ex.InnerException ?? ex).Message));
            }
    
            returnValue = String.Format("<div class=\"spc alert alert-success alert-dismissible fade in\" role=\"alert\"><div class=\"info\">{0}</div></div>",
                currentNode.GetPropertyValue<string>("submissionMessage"));
    
            return Content(returnValue);
        }
    
        private static string ApplyReplacements(ListDictionary replacements, string voucherData)
        {
            if (replacements != null && !string.IsNullOrEmpty(voucherData))
            {
                foreach (object key in replacements.Keys)
                {
                    string str = key as string;
                    string item = replacements[key] as string;
                    if (str == null || item == null)
                    {
                        throw new ArgumentException("Invalid Replacements");
                    }
                    item = item.Replace("$", "$$");
                    voucherData = Regex.Replace(voucherData, WebUtility.HtmlDecode(str), item, RegexOptions.IgnoreCase);
                    voucherData = Regex.Replace(voucherData, str, item, RegexOptions.IgnoreCase);
                }
            }
            return voucherData;
        }
    
        public ListDictionary GetReplacements(ContactFormForBasicECommerceViewModel model,
            BasicEcommerceVoucher voucher, string websiteName, string pageName)
        {
            //Build replacement collection to replace fields in template 
            var replacements = new ListDictionary();
            replacements.Add("%% WebsitePage %%", pageName);
            replacements.Add("%% WebsiteName %%", websiteName);
            replacements.Add("%% formFirstName %%", model.FirstName ?? "");
            replacements.Add("%% formLastName %%", model.LastName ?? "");
            replacements.Add("%% formEmail %%", model.Email ?? "");
            replacements.Add("%% formPhone %%", model.Telephone ?? "");
            replacements.Add("%% formMessage %%", umbraco.library.ReplaceLineBreaks(model.Message ?? ""));
            replacements.Add("%% paymentID %%", model.PaymentId ?? "");
            replacements.Add("%% payerID %%", model.PayerId ?? "");
            var productContent = new Usn_Ac_ProductPod(voucher.Product);
            if (productContent != null)
            {
                var product = new Usn_Ac_ProductPod(productContent);
                replacements.Add("%% orderNumber %%", voucher.Id.ToString() ?? "");
                replacements.Add("%% orderCreated %%", voucher.CreateDate.ToString("f") ?? "");
                replacements.Add("%% productName %%", product.PodTitle ?? "");
                replacements.Add("%% productDescription %%", product.PodText.ToString() ?? "");
            }
            var variantContent = voucher.Variant;
            if (variantContent != null)
            {
                var variant = new ProductPodVariant(variantContent);
                replacements.Add("%% quantity %%", variant.Quantity.ToString() ?? "");
                replacements.Add("%% amount %%", variant.Price.ToString("N0") ?? "");
            }
    
            return replacements;
        }
    
        public static void SendContactFormMail(ContactFormForBasicECommerceViewModel model,
            string websiteName, string pageName, ListDictionary replacements,
            Usn_Sc_ContactFormForBasicEcommerce_AN currentNode, Stream voucher,
            UsnglobalSettings globalSettings)
        {
            //Create MailDefinition 
            var md = new MailDefinition();
            var websiteOwnerTo = currentNode.GetPropertyValue<string>("recipientEmailAddress");
    
            //specify the location of template 
            md.IsBodyHtml = true;
    
            //this uses SmtpClient in 2.0 to send email, this can be configured in web.config file.
            var smtp = new System.Net.Mail.SmtpClient();
    
            //now create mail message using the mail definition object
            var msgToWebsiteOwner = md.CreateMailMessage(websiteOwnerTo, replacements, currentNode.EmailNotificationTemplate.ToString(), new System.Web.UI.Control());
    
            //msgToWebsiteOwner.ReplyToList.Add(new System.Net.Mail.MailAddress(model.Email, string.Concat(model.FirstName, " ", model.LastName)));
            msgToWebsiteOwner.Subject = websiteName + " Website: " + pageName + " Page Enquiry from " + model.FirstName + " " + model.LastName;
            smtp.Send(msgToWebsiteOwner);
    
            if (voucher != null && voucher.Length > 0)
            {
                var pdfAttachment = new System.Net.Mail.Attachment(voucher, string.Format("Voucher-{0}.pdf", currentNode.Id), "application/pdf");
    
                var msgToWebsiteUser = md.CreateMailMessage(model.Email, replacements, currentNode.VoucherTemplate.ToString(), new System.Web.UI.Control());
                msgToWebsiteUser.ReplyToList.Add(new System.Net.Mail.MailAddress(websiteOwnerTo, websiteName));
                msgToWebsiteUser.Bcc.Add(new System.Net.Mail.MailAddress(websiteOwnerTo, websiteName));
                msgToWebsiteUser.Subject = websiteName + " Website: " + pageName + " Page Enquiry";
                msgToWebsiteUser.Attachments.Add(pdfAttachment);
                smtp.Send(msgToWebsiteUser);
            }
    
        }
    }
    
  • iand123 23 posts 53 karma points
    Apr 23, 2018 @ 07:22
    iand123
    0

    thanks for the replies chaps

    Ben Norman - thanks for the code example, how would you then access this?

    Guessing at /ContactFOrmFOrBasicEcommerceSurface/Index (or even without the index)?

  • Ben Norman 166 posts 272 karma points
    Apr 23, 2018 @ 10:29
    Ben Norman
    0

    The url for the controller is /umbraco/Surface/ContactFormForBasicECommerceSurface/HandleContactSubmit

Please Sign in or register to post replies

Write your reply to:

Draft