Email Notification when a new review has been added - Magento - php

This is probably a feature which any one might be looking for. I would like to send an email notification to my store's contact email address every time a new review has been added.
I am planning to do this by making a custom module which on its own as soon as the new review is posted should notify the store owner (on its contact email address).
Now the few things I am stuck with is whether this needs to be run on a cron job or is it capable of running on its own as soon as a new review has been posted.
Also what exactly would be the condition which would check for new reviews and send email alerts. This are just things off the top of my head, but if any one has got a better outline on how to do this, is more than welcome to drop in their suggestions.
Thanks in advance

As Dick Laurent suggested you can use an observer to notify you by email when a product review is placed.
Looking to see if there is an event after a review is saved I checked:
app/code/core/Mage/Review/etc/config.xml
and there is already someone using this event:
<events>
<review_save_after>
<observers>
<rss>
<class>rss/observer</class>
<method>reviewSaveAfter</method>
</rss>
</observers>
</review_save_after>
</events>
So this is the event you are looking for: review_save_after
See this Magento wiki link for more information about Customizing Magento using Event/Observer
This works if you only want to get notified when a review is posted. If you want more specific/usefull links you might want to override a Magento class from Mage_Review (the controller or the model to store review id and stuff in session.
If you want to include some details about the posted review you can get it from session:
$session = Mage::getSingleton('core/session');
$data = $session->getFormData(true);

What i understood from your description is "You want to send a mail confirmation, when a new review is posted".
In each review there will be a form post with review data.
Then you can save review data in db and asynchromously send email notification.
To send email , you can setup SMTP server connection (either in config or via code) and just send mail.
It is all you wanted?
Else post in detail what you need..

For a quick and very dirty fix you can add a
mail(to,subject,message) line to
app/code/core/Mage/Review/controllers/ProductController.php
after the line $session->addSuccess($this->__('Your review has been accepted for moderation.'));.

//after $rating = $this->getRequest()->getParam('ratings', array()); add
$ratingmsg='';
foreach($data as $key => $value){
$ratingmsg.='<b>'.$key.':</b> '.$value.'<br/>';
}
//and after $session->addSuccess($this->__('Your review has been accepted for moderation.'));
//add
$mail = Mage::getModel('core/email');
$body='<b>Produit :</b> '.$product->getName().'<br/>'.$ratingmsg.'<br/><br/>Pour valider ce commantaire rendez vous dans <br/>catalogue > commentaires > commentaires en attente';
$mail->setToName('name');
$mail->setToEmail('mail#gmail.com');
$mail->setBody($body);
$mail->setSubject('Un nouveau commentaire sur XX');
$mail->setFromEmail('contact#site.com');
$mail->setFromName("Name");
$mail->setType('html');// YOu can use Html or text as Mail format
try {
$mail->send();
//Mage::getSingleton('core/session')->addSuccess('Your request has been sent');
}
catch (Exception $e) {
Mage::log($e->getMessage(), null, 'mail.log');
}

Related

Wordpress: Output custom user_meta data in registration notification

In WordPress, I have custom registration site for new users. Upon registration, there is an optional checkbox to subscribe to our newsletter. As far as I understand it, it adds the value of the checkbox to the user_meta table (the whole thing has been coded by a company in India, which I woould very much prefer to not involve again, since they delayed their work time and time again and didn't do good work after all).
The corresponding code snippet in my child theme's functions.php looks like this:
<?php echo '<div class="form-row form-row-wide">
<input type="checkbox" name="inter_offers" value="yes"> '; _e('I would like to subscribe to the Kurth Electronic newsletter.','kurth-child'); echo '<br></div>';
return $fields; ?>
add_action('woocommerce_created_customer','adding_extra_reg_fields');
function adding_extra_reg_fields($user_id) {
extract($_POST);
update_user_meta($user_id, 'billing_inter_offers',$inter_offers);
} ?>
(I have left out lines irrelevant to this issue.)
Now, this value is saved internally, but not displayed to me. I would like to show the value in an E-Mail or notification generated by WordPress when the user completes registration, so that we can manually add them to our newsletter list whenever someone chooses to subscribe to the newsletter. The problem is that I only have a limited knowledge of PHP and I don't know where to start.
I should also note that this is not done via the standard WorPress registration form, but by a WooCommerce registration form (I have disabled the standard WordPress registration for security reasons).
I tried using the "Better Notifications" plugin (https://wordpress.org/plugins/bnfw/) for custom notifications whenever a new user completes their registration, but it ignores any php code that I add to the custom notifications body to display the user_meta data.
Any help would be appreciated.
Because the registration is done via woocomerce you may have to look for a notification PlugIN that works with woocomerce, the one you have may just work properly with wordpress core version!
You also could generate a mail via php in the function, so that you get a message with the user mail adress, but i think without php knowledge it is not that easy to use the built in php mailer... (You may need an api there!)
But wouldn't it be better to automatically sign them into your newsletter software? For example for Mailchimp or other systems like that there are quite good wordpress plugins!
You may also be able to include the forms of these PlugIns in your registration form, but without a closer look at this woocomerce registration i can't tell for sure!
I think this will do the trick, it will notify you every time a new user is created and also tell you if they subscribed or not.
function new_customer_registered_send_email_admin($user_login, $user_email) {
ob_start();
do_action('woocommerce_email_header', 'New customer registered');
$email_header = ob_get_clean();
ob_start();
do_action('woocommerce_email_footer');
$email_footer = ob_get_clean();
$user = get_user_by( 'email', $user_email );
$subscribed = get_user_meta( $user->ID, 'billing_inter_offers', true );
woocommerce_mail(
get_bloginfo('admin_email'),
get_bloginfo('name').' - New customer registered',
$email_header.'<p>The user '.esc_html( $user_login ).' created an account ' . ( $subscribed ? ' and subscribed to the newsletter.' : '.' ) . '<br>Email:'.esc_html( $user_email ).'</p>'.$email_footer
);
}
add_action('new_customer_registered', 'new_customer_registered_send_email_admin', 10, 2);
I ended up using the plugin amr users to generate a userlist of all users who had a certain metadata tag set to a certain value (in my case, if they want to recieve a newsletter - the previous developers never bothered to make the data actually readable without extra effort). It is a little clunky to use and not what I originally intended, but it got the job done.

Magento only sends order confirmation emails when manually prompted to

A Magento website I'm maintaining stopped sending order confirmations and/or invoices all of a sudden.
Nothing has been changed in the email settings and they're all complying with common Magento guidelines. I've tried sending a test email through the following php script to make sure it's not caused by any server settings:
<?php
$to = "me#domain.com";
$subject = "Test email";
$message = "This is a test email.";
$from = "testing#anothertest.test";
$headers = "From:" . $from;
if (mail($to, $subject, $message, $headers)) {
echo("Your message has been sent successfully");
} else {
echo("Sorry, your message could not be sent");
}
?>
The test message got delivered flawlessly.
I installed the SMTP Pro Email plugin to see if changing settings there would manage a result; nothing. The plugin offers the ability to send a test email, which again gets delivered without flaw.
Even stranger, clicking the 'Send Email' button in the Magento backend for an order does deliver the email. Signing up for a newsletter does result in a subscription confirmation request email. Clearly, the website can send mails, it just somehow doesn't get triggered to do so for order order confirmations and invoices.
And yes, both
System > Configuration > Sales > Sales Emails > Order > Enabled
and
System > Configuration > Sales > Sales Emails > Invoice > Enabled
are set to Yes and include a BCC address.
Similarly,
System > Configuration > Advanced > System > Mail Sending Settings > Disable Email Communications
is set to No.
I'm running Magento CE 1.6.2 on this site, so it's not the common cron job problem version 1.9 seems to cause for a lot of folk.
I'm racking my brain here, does anybody have a clue?
Still haven't found what causes the problem, but added some code to succes.phtml to force the mail to be sent upon loading that page:
<?php
$order = new Mage_Sales_Model_Order();
$incrementId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
$order->loadByIncrementId($incrementId);
try
{
$order->sendNewOrderEmail();
} catch (Exception $ex) { }
?>
It's not the most elegant solution, but at least the customers get their order confirmation through this workaround.
I am using version 1.8.1. I have been fighting with this same problem for 2 weeks now. The simple solution came by me "enabling" every option in System > Configuration > Advanced. All the new order confirmations get sent out immediately now to the person placing the order.
Background: After installing and configuring the new Magento Cart, I noticed that emails were only going through if I manually sent them through the admin screens. This told me that the server SMTP settings were correct, but I was wondering why a person placing an order would not receive the confirmation email...ever. After much searching and reading I thought that it had to do with one of the other functions of the Magento cart. So I went into the system confuration under the advanced tab (System > Configuration > Advanced) and found that I had disabled certain things like Sendtofrined, Newsletter, etc. Not wanting to waste time at the moment, I simply went through the entire list and enabled everything. Now I have the coupon function, add to wish list function and newsletter stuff that I do not want to see in the cart, but the emails are going through immediately and reliably. I will now attempt to find which function is related to the order confirmation email by process of elimination. But this did the trick for me and I hope it helps someone else out there, without having to add code to the php files.

Magento Order Emails

I am using magento 1.7.Can anyone help/advise on this??
Also using EPDQ Barclaycard module.
Everything seems ok with capturing payments, however when I go to checkout fill in all the details up to Payment Information select card type and hit continue, then place order a new order email has been sent but it hasnt been paid for yet!
Is there anyway that this can be prevented till payment has been captured via Barclaycard?
Have I missed something?
Thanks in advance
Magento sends email order confirmations as soon as the order is placed. If you are redirecting the user to a payment gateway after the order has been placed but not paid for you will need to modify your payment module to use magento's payment redirect setup to get it to ignore the confirmation email (See Mage_Checkout_Model_Type_Onepage class saveOrder() method).
You should see some code like;
/**
* a flag to set that there will be redirect to third party after confirmation
* eg: paypal standard ipn
*/
$redirectUrl = $this->getQuote()->getPayment()->getOrderPlaceRedirectUrl();
/**
* we only want to send to customer about new order when there is no redirect to third party
*/
if (!$redirectUrl && $order->getCanSendNewEmailFlag()) {
try {
$order->sendNewOrderEmail();
} catch (Exception $e) {
Mage::logException($e);
}
}
So this gives you a few options. Extend your payment module so that it sets the order place redirect url, but this might mess up your payment module depending on how it was coded or you could extend the above class into your own module (do not mod the core), override the saveOrder() method and check the payment method in the if statement shown above a bit like;
if (!$redirectUrl && $order->getPayment()->getMethod() != 'your_payment_method' && $order->getCanSendNewEmailFlag()) {
try {
$order->sendNewOrderEmail();
} catch (Exception $e) {
Mage::logException($e);
}
}
You would then to handle IPN notification to get it to send the email when a successful payment IPN is received, I would suggest you take a look at the PayPal Standard module that ships with Magento for some pointers as this is exactly how it works. I am surprised the EPDQ module you have does not work like this already, might be worth contacting them and highlighting the issue.

Magento sending SMS upon creating shipment

Banging my head for the last two days but unable to achieve this. Help!!
Whenever a shipment email is communicated I want to trigger a code which will send a SMS to the customer informing him/her that his order has been dispatched and also communicate the tracking number.
The code will be something like this:
<?php
$url = "http://www.abcde.in/binapi/pushsms.php?usr=xyz&pwd=abc&sndr=MEGYTR&ph=8888829554&text=This is test. MegaYtr&rpt=1";
$result = file_get_contents($url);
?>
Questions:
1) From where do I run this code?
2) How do I get additional info like Order Number, Customer Name, Grand Total & Tracking Number. I had done something similar for sending SMS when customer places order at that I used this code:
$order_id = Mage::getSingleton('checkout/session')->getLastRealOrderId();
$order_details = Mage::getModel('sales/order')->loadByIncrementId($order_id);
$shipping_address_data = $order_details->getShippingAddress();
$first_name = $shipping_address_data['firstname'];
$telephone = $shipping_address_data['telephone'];
$amount_paid = $order_details->total_paid;
$message = 'Dear '.$first_name.' thank you for shopping at abc.com. Your order'.$this->getOrderId().' amounting to Rs.'.$amount_paid.'is being processed.';
echo '<b>'.$message.' Please check your email for further details.</b>';
I am using Magento Community 1.7.0.1.
try this
i would like to give you an simple solution without need of modifying core files.
for that you need to create an observer for SuccessAction below is the event that will trigger your code when an order is successfull
checkout_onepage_controller_success_action
this will help you in creating observer for the above event create observer using this
one more thing i would like to add is in the controller at location Mage/Checkout/OnepageController search for successAction, this is the Action which is processed on the succes of order. Here on line 240 if you comment $session->clear(); than you would not require to place order again and again, just by refreshing the page you can check your changes.
And lastly FYI above event will dispatch orderId by using that you can load the order object, for doing that the below is the code
//load order object
$_order = Mage::getModel('sales/order')->loadByIncrementId($order_id_from_observer);

Set subscriber status in Magento programmatically

I am trying to write a module that syncs my newsletter subscribers in Magento with a external database. I need to be able to update the subscription status in Magento programmatically but I am having diffuculty getting the "setStatus" method in Magento to work. It does not throw any errors but the code does not seem to have any effect. Below is the code where I call the method:
$collection = Mage::getResourceModel('newsletter/subscriber_collection')->showStoreInfo()->showCustomerInfo();
foreach ($collection as $cust) {
$cust->setStatus(1);
}
In theory, this should set the status of all of my subscribers to "subscribed". I could optionally change the argument sent to "setStatus" to any of the below ints for a different status.
1: Subscribed
2: Status Not Active
3: Unsubscribed
How to best change the subscriber status or get this code working?
Here an import script:
<?php
require_once("./app/Mage.php");
Mage::app();
$subscribers = array('email1#server1.com', 'email2#server2.com');
foreach ($subscribers as $email) {
# create new subscriber without send an confirmation email
Mage::getModel('newsletter/subscriber')->setImportMode(true)->subscribe($email);
# get just generated subscriber
$subscriber = Mage::getModel('newsletter/subscriber')->loadByEmail($email);
# change status to "subscribed" and save
$subscriber->setStatus(Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED);
$subscriber->save();
}
?>
It seems that newsletter subscribers are also stored elsewhere. What you are setting is just a check in the customer base for some other use.
You need to do the following for each customer as well.
Mage::getModel('newsletter/subscriber')->subscribe($email);
See this link for a complete reference.
Thanks to the link #Ozair shared I was able to figure out what I needed to do.
I was successfully setting the status of the subscriber in the Magento subscriber object but I was not saving the object. I needed to call Magento's save method so it would call the ORM and write it to the database. All I need to do was add
$cust->save();
in the for loop. Below is the whole code snippet.
$collection = Mage::getResourceModel('newsletter/subscriber_collection')->showStoreInfo()->showCustomerInfo();
foreach ($collection as $cust) {
$cust->setStatus(1);
$cust->save();
}
I Hope this helps someone in the future. I needed it for a Constant Contact - Magento Synchronization extension I was making: http://www.freelunchlabs.com/store/constant-contact-and-magento-sync.html

Categories