Im looking at this guide https://www.pirenko.com/creating-wordpress-auto-login-links/ and Im trying to adjust it to a quote mail that uses the customer-invoice.php template.
Problems:
- how do I fetch the correct key for the order?
- How do I update current users with a secret key so I can call it for the url?
$secret_string=wp_generate_password( 8, false );
$login_link ='http://website.com/wp-json/sand_login/prk_route?username='.$username.'&secret='.$user_info->secret_key;
I started with removing the check for secret key, just to see if i could get it to work with email-adress to start with and added a redirect to checkout. I will add the check for the security key once I can get this updated on current user meta.
Added to functions.php
add_action( 'rest_api_init', function () {
register_rest_route(
'sand_login',
'prk_route',
array(
'methods' => 'GET',
'callback' => 'pirenko_login_user',
)
);
});
function pirenko_login_user() {
// Validate input
if (isset($_GET['username']) && $_GET['username']!="") {
$username = $_GET['username'];
$user = get_user_by('email', $username );
if ($user) {
//Check if secret key matches
$check_user = get_user_by( 'id', $user->ID );
//Login info is correct - let's proceed
// Manage login cookies
wp_clear_auth_cookie();
wp_set_current_user ( $user->ID );
wp_set_auth_cookie ( $user->ID );
// Finally redirect user
$order = new WC_Order($order_id);
$payment_page = $order->get_checkout_payment_url($order->ID);
wp_safe_redirect( $payment_page );
exit();
}
else {
echo "Could not find user!";
exit();
}
}
else {
echo "Parameters are missing!";
exit();
}
}
The email function in customer-invoice.php looks like this:
if ($order && $order->has_status('enquiry')) {
$email_text = str_replace('{betaallink}', '<a class="payment" href="' . esc_url($order->get_checkout_payment_url()) . '">', $email_text);
$email_text = str_replace('{/betaallink}', '</a>', $email_text);
}
And I updated it to this, without the secret key to start with:
if ($order && $order->has_status('enquiry')) {
$user = $order->get_user();
$username = $user ? $user->__get('user_email') : '';
$login_link ='http://website.com/wp-json/sand_login/prk_route?username='.$username;
$email_text = str_replace('{betaallink}', '<a class="payment" href="'. $login_link .'">', $email_text);
$email_text = str_replace('{/betaallink}', '</a>', $email_text);
}
This works. The user gets logged in and redirected to cart with this url with all open orders registered on the user:
https://website.com/afrekenen/order-pay/?pay_for_order=true&key
Do I go about this totally wrong?