I have setup Woocommerce to automatically register a new customer when the order is completed.
Now I want to send the password and other things that has been generated to a third party using a API POST request to create the same user account.
Things I need to send from the Woocommerce generated account:
Email address (used for email and login on third party website)
First name
Last name
Password (Needs to be unhashed, same as used in new account email)
Can someone show me an example how to get this done? Or point me in to the right direction? I just can't find anything to start with.
I thought by adding Curl to the Woocommerce thank you page webhook. But this won't send the password unhashed, it just stay blank.
Hope someone knows an easy way to get this done.
Thanks!
Latest UPDATE: CODE USING IN MY FUNCTIONS.PHP
class NewCustomerRegistration
{
private $credentials;
public function __construct()
{
// Use PHP_INT_MAX so that it is the last filter run on this data
// in case there are other filter changing the password, for example
add_filter(
'woocommerce_new_customer_data',
[$this, 'when_user_is_created'],
1,
PHP_INT_MAX
);
add_action('woocommerce_new_customer', [$this, 'when_customer_is_created']);
}
public function when_user_is_created($customerData)
{
$this->credentials = [
'email' => $customerData['user_email'],
'password' => $customerData['user_pass'],
];
return $customerData;
}
public function when_customer_is_created($customerId)
{
$customer = get_userdata($customerId);
/**
* Perform the required actions with collected data
*
* Email: $this->credentials['email']
* Password: $this->credentials['password']
* First Name: $customer->first_name
* Last Name: $customer->last_name
*/
// Testing sending email function
$subject = "Test Email with data";
$email = "info#mydomain.com";
$message = "Hello, {$customer->first_name}\n\n";
$message .= "Here are your login details for {$customer->first_name} {$customer->last_name}\n\n";
$message .= "Your company is: {$customer->company}\n\n";
$message .= "Your username is: {$this->credentials['email']}\n\n";
$message .= "Your password is: {$this->credentials['password']}\n\n";
$message .= "Your email is: {$this->credentials['email']}\n\n";
$message .= "Your role is: {$customer->role}\n\n";
$headers = array();
add_filter( 'wp_mail_content_type', function( $content_type ) {return 'text/html';});
$headers[] = 'From: My Wordpress Website <info#mydomain.com>'."\r\n";
wp_mail( $email, $subject, $message, $headers);
// Reset content-type to avoid conflicts
remove_filter( 'wp_mail_content_type', 'set_html_content_type' );
}
}
It looks like the combining the actions woocommerce_created_customer (for email and password) and woocommerce_new_customer (for other customer details) could do the job for you.
My thinking is that you could do something like..
class NewCustomerRegistration
{
private $credentials;
public function __construct()
{
add_action('woocommerce_created_customer', [$this, 'when_user_is_created']);
add_action('woocommerce_new_customer', [$this, 'when_customer_is_created']);
}
public function when_user_is_created($customerId, $customerData)
{
$this->credentials = [
'email' => $customerData['user_email'],
'password' => $customerData['user_pass'],
];
}
public function when_customer_is_created($customerId)
{
$customer = get_userdata($customerId);
/**
* Send email with collected data
*
* Email: $this->credentials['email']
* Password: $this->credentials['password']
* First Name: $customer->first_name
* Last Name: $customer->last_name
*/
wp_mail(...);
}
}
NOTE You should probably clear the credentials after sending so that, if the woocommerce_new_customer action is called with a different user for some reason, the credentials aren't sent out to a different user. You should probably add some error checks in too, just for your own sanity.
UPDATE
As you are getting an error with the woocommerce_created_customer action you might get better results listening for the woocommerce_new_customer_data filter.
class NewCustomerRegistration
{
private $credentials;
public function __construct()
{
// Use PHP_INT_MAX so that it is the last filter run on this data
// in case there are other filter changing the password, for example
add_filter(
'woocommerce_new_customer_data',
[$this, 'when_user_is_created'],
1,
PHP_INT_MAX
);
add_action('woocommerce_new_customer', [$this, 'when_customer_is_created']);
}
public function when_user_is_created($customerData)
{
$this->credentials = [
'email' => $customerData['user_email'],
'password' => $customerData['user_pass'],
];
return $customerData;
}
public function when_customer_is_created($customerId)
{
$customer = get_userdata($customerId);
/**
* Perform the required actions with collected data
*
* Email: $this->credentials['email']
* Password: $this->credentials['password']
* First Name: $customer->first_name
* Last Name: $customer->last_name
*/
}
}
Related
We added new fields with new variables for the registration form, and we want to receive in our email all the data in the fields listed for the new client account at the moment of the account creation.
add_action('woocommerce_created_customer',
'woocommerce_created_customer_admin_notification');
function woocommerce_created_customer_admin_notification($customer_id)
{
wp_send_new_user_notifications($customer_id, 'admin');
}
The part of the code that I have attached to this email is only sending us the email and username of the account that has been created. However, we want to receive all the data as mentioned before.
/**
* Filters the contents of the new user notification email sent to the site admin.
*
* #since 4.9.0
*
* #param array $wp_new_user_notification_email_admin {
* Used to build wp_mail().
*
* #type string $to The intended recipient - site admin email address.
* #type string $subject The subject of the email.
* #type string $message The body of the email.
* #type string $headers The headers of the email.
* }
* #param WP_User $user User object for new user.
* #param string $blogname The site title.
*/
$wp_new_user_notification_email_admin = apply_filters( 'wp_new_user_notification_email_admin', $wp_new_user_notification_email_admin, $user, $blogname );
Use this wp_new_user_notification_email_admin filter and add the details to the message parameter.
$wp_new_user_notification_email_admin['message'].= "Test data";
See below for an implementation sample.
add_action('login_init', 'set_wp_new_user_notification_email_admin_init');
function set_wp_new_user_notification_email_admin_init() {
add_filter('wp_new_user_notification_email_admin', 'set_wp_new_user_notification_email_admin', 10, 3);
}
function set_wp_new_user_notification_email_admin($wp_new_user_notification_email, $user, $blogname) {
$wp_new_user_notification_email['subject'] = sprintf('[%s] New user %s registered.', $blogname, $user->user_login);
$wp_new_user_notification_email['message'] = sprintf("%s ( %s ) has registerd to your blog %s.", $user->user_login, $user->user_email, $blogname);
return $wp_new_user_notification_email;
}
I am trying to send two emails at the same time when the user submits contact form. One email to the website owner and other to the user as autoresponse. I have been trying to do this for about last 4 hours and tried different solutions on internet but I am totally lost. Here is my code to send an email
public function contactForm(Request $request)
{
$parameters = Input::get();
$email = Input::get('email');
$inquiryType = Input::get('type_inquiry');
foreach ([
'contactmessage' => 'Message',
'email' => 'Email',
'phone' => 'Phone',
'first_name' => 'Contact Name',
'g-recaptcha-response' => 'Captcha',
] as $key => $label) {
if (!isset($parameters[$key]) || empty($parameters[$key])) {
return response()->json(
[
'success' => false,
'error' => "{$label} cannot be empty",
]
);
}
}
$recipients = 'abc#gmail.com';
// if page set, try to get recipients from the page settings
if (Input::get('page_id')) {
$page = Page::find(Input::get('page_id'));
if ($page && !empty($page->recipients)) {
$recipients = explode(',', $page->recipients);
}
}
try {
$res = Mail::send(
'emails.contact',
$parameters,
function (Message $message) use ($recipients) {
$message->subject('Contact message');
if (is_array($recipients)) {
// email to first address
$message->to(array_shift($recipients));
// cc others
$message->cc($recipients);
} else {
$message->to($recipients);
}
}
);
} catch (\Exception $e) {
return response()->json(
[
'success' => false,
'error' => $e->getMessage(),
]
);
}
if($inquiryType == 'Rental Inquiry'){
Mail::send(
'emails.autoresponse',
'',
function (Message $message) use ($email) {
$message->subject('Thank you for inquiring');
if (is_array($email) {
// email to first address
$message->to(array_shift($email);
// cc others
$message->cc($email);
} else {
$message->to($email);
}
}
);
}
return response()->json(
[
'success' => $res,
]
);
}
I have tried to do the same thing by different methods but none of them are working. Please help me. This is the first time I am sending multiple emails using laravel. I think I am doing a big and silly mistake somewhere.
Thank you.
You have a missing closing parenthesis near is_array($email)
$message->subject('Thank you for inquiring');
if (is_array($email)) {
Also i would you use laravel's validator to check for required input. Another suggestion would be to use queues for mails. Sending two mails in a single request might cause your page load time to increase significantly.
The best way is create one Laravel Jobs
php artisan queue:table
php artisan migrate
php artisan make:job SendEmail
Edit your .env
QUEUE_DRIVER=database
Edit your app /Jobs/SendEmail.php
namespace App\Jobs;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Contracts\Mail\Mailer;
class SendEmail extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;
protected $subject;
protected $view;
protected $data;
protected $email;
/**
* SendEmail constructor.
* #param $subject
* #param $data
* #param $view
* #param $email
*/
public function __construct($subject, $data, $view, $email)
{
$this->subject = $subject;
$this->data = $data;
$this->email = $email;
$this->view = $view;
}
/**
* Execute the job.
* #param $mailer
* #return void
*/
public function handle(Mailer $mailer)
{
$email = $this->email;
$subject = $this->subject;
$view = $this->view;
$mailer->send($view, $this->data,
function ($message) use ($email, $subject) {
$message->to($email)
->subject($subject);
}
);
}
}
And handle in your controller
use App\Jobs\SendEmail;
public function contactForm(Request $request) {
//TODO Configure Subject
$subjectOwner = 'Your Email Subject For Owner';
$subjectUser = 'Your Email Subject For User';
//TODO Configure Email
$ownerEmail = 'ownerEmail#gmail.com';
$userEmail = 'userEmail#gmail.com';
//TODO Configure Data Email send to email blade viewer
$dataEmail = [
'lang' => 'en',
'user_name' => 'User Name'
];
//emails.owner mean emails/owner.blade.php
//emails.admin mean emails/admin.blade.php
$jobOwner = (new SendEmail($subjectOwner, $dataEmail, "emails.owner" , $ownerEmail))->onQueue('emails');
dispatch($jobOwner);
$jobUser = (new SendEmail($subjectUser, $dataEmail, "emails.admin" , $userEmail))->onQueue('emails');
dispatch($jobUser);
}
And try command
//IF You using Laravel 5.2
php artisan queue:listen --queue=emails
//IF You using Laravel >5.3
php artisan queue:work
I have implemented reset password functionality with Laravel 5 and getting email. Now how to pass some variable data to my email template to display more information about user.
/**
* Send a reset link to the given user.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function postEmail(Request $request)
{
//echo Input::get('ID'); die;
$this->validate($request, ['ID' => 'required|email']);
$UserProduct = "Sample 1"; // I want to pass this variable to my password.blade.php
$response = Password::sendResetLink($request->only('ID'), function (Message $message) {
$message->subject($this->getEmailSubject());
});
switch ($response) {
case Password::RESET_LINK_SENT:
return redirect()->back()->with('status', trans($response));
case Password::INVALID_USER:
return redirect()->back()->withErrors(['ID' => trans($response)]);
}
}
I want to print $UserProduct = "Sample 1"; to my email template but don't know how to pass to the password.blade page.
Any idea?
Thanks.
The sendResetLink doesn't have a proper way to send more data like a regular email in laravel.
You can kinda hack around this using a view composer, something like this:
$UserProduct = "Sample 1";
$infoArray = [1,2,3,4];
view()->composer('emails.auth.password', function($view) use ($UserProduct, $infoArray) {
$view->with([
'UserProduct' => $UserProduct,
'info' => $infoArray,
'more' => 'Even more info',
]);
});
$response = Password::sendResetLink($request->only('ID'), function (Message $message) {
$message->subject($this->getEmailSubject());
});
So in my UsersAdmin I want to send an email to that user if I confirm his account.(in my case, making Enabled = true). I do this in the configureListFields function
/**
* {#inheritdoc}
*/
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->addIdentifier('username')
->add('email')
->add('groups')
->add('enabled', null, array('editable' => true)) //here
->add('locked', null, array('editable' => true))
->add('createdAt')
;
}
By reading the documentation I think i need to use the batchAction function yes? So I made this:
public function getBatchActions()
{
// retrieve the default batch actions (currently only delete)
$actions = parent::getBatchActions();
$container = $this->getConfigurationPool()->getContainer();
$user = //how to get the user that i am editing right now?
if ($this->hasRoute('edit') && $this->isGranted('EDIT')) {
$body = $container->get('templating')->render('MpShopBundle:Registration:registrationEmail.html.twig', array('user'=> $user));
$message = Swift_message::newInstance();
$message->setSubject($container->get('translator')->trans('registration.successful'))
->setFrom($container->getParameter('customer.care.email.sender'))
->setTo('email#contact.lt')
->setBody($body, 'text/html');
$container->get('mailer')->send($message);
}
return $actions;
}
Now I am stuck with two unclear thing with this function:
How can I get the current user data hat I want to edit?
Am I even going in the right direction? Do I need to override edit or maybe some other function?
THE SOLUTION
The best way is to do your login in the postUpdate event, so that everytime you update an object it initiates the functions you want.
public function postUpdate($user)
{
if($user->getEnabled() == true) {
$container = $this->getConfigurationPool()->getContainer();
$body = $container->get('templating')->render('MpShopBundle:Registration:registrationEmail.html.twig', array('user' => $user));
$message = Swift_message::newInstance();
$message->setSubject($container->get('translator')->trans('registration.successful'))
->setFrom($container->getParameter('customer.care.email.sender'))
->setTo('email#contact.lt')
->setBody($body, 'text/html');
$container->get('mailer')->send($message);
}
}
you can use Saving hooks.
public function postUpdate($user)
{
//code to check if enabled
// code to send email
}
I am new to Magento and PHP. I use the following line to get the email, which works fine except in the case a customer just registered. Any suggestions? Thanks.
$userEmail = Mage::getSingleton('customer/session')->getCustomer()->getEmail();
I assume that this code runs before the customer object data was saved propperly.
There is a line of code callled: in the OnePageCheckout and it does the following:
/**
* Involve new customer to system
*
* #return Mage_Checkout_Model_Type_Onepage
*/
protected function _involveNewCustomer()
{
$customer = $this->getQuote()->getCustomer();
if ($customer->isConfirmationRequired()) {
$customer->sendNewAccountEmail('confirmation', '', $this->getQuote()->getStoreId());
$url = Mage::helper('customer')->getEmailConfirmationUrl($customer->getEmail());
$this->getCustomerSession()->addSuccess(
Mage::helper('customer')->__('Account confirmation is required. Please, check your e-mail for confirmation link. To resend confirmation email please click here.', $url)
);
} else {
$customer->sendNewAccountEmail('registered', '', $this->getQuote()->getStoreId());
$this->getCustomerSession()->loginById($customer->getId());
}
return $this;
}
If the customer is just registering, not using the checkout process, then there is a different function using the request parameters like Anton said:
/app/code/core/Mage/Customer/Block/Form/Register.php
/**
* Restore entity data from session
* Entity and form code must be defined for the form
*
* #param Mage_Customer_Model_Form $form
* #return Mage_Customer_Block_Form_Register
*/
public function restoreSessionData(Mage_Customer_Model_Form $form, $scope = null)
{
if ($this->getFormData()->getCustomerData()) {
$request = $form->prepareRequest($this->getFormData()->getData());
$data = $form->extractData($request, $scope, false);
$form->restoreData($data);
}
return $this;
}
you can get it from request parameters directly?