When we install WordPress with Softaculous, a Login button appears and we log in to the site without entering the username and password we pressed.
We have a site where we sell digital subscriptions. We manage subscriptions for various websites here. Now we need to integrate a site made with WordPress here.
When our customer receives a site subscription, we plan to create a user for the WordPress site with the code below.
add_action('rest_api_init', 'wp_rest_user_endpoints');
/**
* Register a new user
*
* @param WP_REST_Request $request Full details about the request.
* @return array $args.
**/
function wp_rest_user_endpoints($request) {
/**
* Handle Register User request.
*/
register_rest_route('wp/v2', 'users/register', array(
'methods' => 'POST',
'callback' => 'wc_rest_user_endpoint_handler',
));
}
function wc_rest_user_endpoint_handler($request = null) {
$response = array();
$parameters = $request->get_json_params();
$username = sanitize_text_field($parameters['username']);
$email = sanitize_text_field($parameters['email']);
$password = sanitize_text_field($parameters['password']);
$error = new WP_Error();
if (empty($username)) {
$error->add(400, __("Username field 'username' is required.", 'wp-rest-user'), array('status' => 400));
return $error;
}
if (empty($email)) {
$error->add(401, __("Email field 'email' is required.", 'wp-rest-user'), array('status' => 400));
return $error;
}
if (empty($password)) {
$error->add(404, __("Password field 'password' is required.", 'wp-rest-user'), array('status' => 400));
return $error;
}
$user_id = username_exists($username);
if (!$user_id && email_exists($email) == false) {
$user_id = wp_create_user($username, $password, $email);
if (!is_wp_error($user_id)) {
$user = get_user_by('id', $user_id);
$user->set_role('subscriber');
$response['code'] = 200;
$response['message'] = __("User '" . $username . "' Registration was Successful", "wp-rest-user");
} else {
return $user_id;
}
} else {
$error->add(406, __("Email already exists, please try 'Reset Password'", 'wp-rest-user'), array('status' => 400));
return $error;
}
return new WP_REST_Response($response, 123);
}
Then, we want to put a Login button on our site, as I mentioned above in the Softaculous structure, and direct it to the WordPress website as a member login.
Q1. How can we do this login event? Can we login via API or do we need something different? I'm asking because I've seen ways to log in with a cookie.
We also put a member login form on the WordPress website. This form triggers an API that checks whether the membership we have written on our site is active or not.
Q2. When it gets Ok result from API, it will return to WordPress site and log in. How can we make this turn?