1. Home
  2. WordPress
  3. APi Development
  4. REST API Endpoint for Registration

REST API Endpoint for Registration

Step 1: Setup Your WordPress Environment

Before you begin, ensure you have a WordPress installation where you can add custom code. You can either add this code to your theme’s functions.php file or create a custom plugin.

Step 2: Add REST API Endpoint for Registration

  1. Open your theme’s functions.php file or create a new plugin file (e.g., custom-registration.php).
  2. Add the following code to define the custom REST API endpoint:
<?php
// Register custom REST API endpoint for user registration
function custom_user_registration_endpoint() {
    register_rest_route('custom/v1', '/register', array(
        'methods' => 'POST',
        'callback' => 'handle_user_registration',
        'permission_callback' => '__return_true',
        'args' => array(
            'username' => array(
                'required' => true,
                'type' => 'string',
                'description' => 'The username for the new user',
            ),
            'email' => array(
                'required' => true,
                'type' => 'string',
                'description' => 'The email for the new user',
            ),
            'password' => array(
                'required' => true,
                'type' => 'string',
                'description' => 'The password for the new user',
            ),
            'first_name' => array(
                'required' => false,
                'type' => 'string',
                'description' => 'The first name of the user',
            ),
            'last_name' => array(
                'required' => false,
                'type' => 'string',
                'description' => 'The last name of the user',
            ),
            'marital_status' => array(
                'required' => false,
                'type' => 'string',
                'description' => 'The marital status of the user',
            ),
            'nid' => array(
                'required' => false,
                'type' => 'string',
                'description' => 'The National ID of the user',
            ),
            'contact_number' => array(
                'required' => true,
                'type' => 'string',
                'description' => 'The contact number for the new user',
            ),
        ),
        'schema' => array(
            'type' => 'object',
            'properties' => array(
                'message' => array(
                    'type' => 'string',
                    'description' => 'A message indicating the result of the registration process',
                ),
            ),
        ),
    ));
}

add_action('rest_api_init', 'custom_user_registration_endpoint');
?>

Step 3: Handle User Registration and Send Confirmation Email

  1. Below the previous code, add the function to handle user registration:
<?php
function handle_user_registration($request) {
    $email = sanitize_email($request->get_param('email'));
    $password = sanitize_text_field($request->get_param('password'));
    $username = sanitize_user($request->get_param('username'));
    $contact_number = sanitize_text_field($request->get_param('contact_number'));
    $nid = sanitize_text_field($request->get_param('nid'));
    $first_name = sanitize_text_field($request->get_param('first_name'));
    $last_name = sanitize_text_field($request->get_param('last_name'));
    $marital_status = sanitize_text_field($request->get_param('marital_status'));

    // Validate email
    if (!is_email($email)) {
        return new WP_Error('invalid_email', 'Invalid email format', array('status' => 400));
    }

    // Check if email already exists
    if (email_exists($email)) {
        return new WP_Error('email_exists', 'Email already registered', array('status' => 400));
    }

    // Validate contact number (assuming it's numeric and specific format)
    if (!preg_match('/^[0-9]{11}$/', $contact_number)) {
        return new WP_Error('invalid_contact_number', 'Invalid contact number format (should be 11 digits)', array('status' => 400));
    }

    // Check if username is already taken
    if (username_exists($username)) {
        return new WP_Error('username_exists', 'Username already taken', array('status' => 400));
    }

    // Create user
    $user_id = wp_create_user($username, $password, $email);

    if (is_wp_error($user_id)) {
        return new WP_Error('registration_failed', 'Registration failed', array('status' => 400));
    }

    // Update additional user meta if provided
    if (!empty($nid)) {
        update_user_meta($user_id, 'nid', $nid);
    }
    if (!empty($first_name)) {
        update_user_meta($user_id, 'first_name', $first_name);
    }
    if (!empty($last_name)) {
        update_user_meta($user_id, 'last_name', $last_name);
    }
    if (!empty($marital_status)) {
        update_user_meta($user_id, 'marital_status', $marital_status);
    }

    // Update mandatory user meta
    update_user_meta($user_id, 'contact_number', $contact_number);
    update_user_meta($user_id, 'account_status', 'pending');

    // Generate activation key
    $activation_key = wp_generate_password(20, false);
    update_user_meta($user_id, 'activation_key', $activation_key);

    // Send confirmation email
    $activation_link = add_query_arg(array('key' => $activation_key, 'user' => $user_id), get_site_url(null, 'wp-json/custom/v1/activate'));
    wp_mail($email, 'Confirm your registration', 'Click on the following link to activate your account: ' . $activation_link);

    return new WP_REST_Response(array('message' => 'Registration successful. Please check your email to activate your account.'), 200);
}
?>

Step 4: Create the Activation Endpoint

  1. Add the following code to create the activation endpoint:
<?php
function custom_user_activation_endpoint() {
    register_rest_route('custom/v1', '/activate', array(
        'methods' => 'GET',
        'callback' => 'handle_user_activation',
        'permission_callback' => '__return_true',
        'args' => array(
            'key' => array(
                'required' => true,
                'type' => 'string',
                'description' => 'The activation key',
            ),
            'user' => array(
                'required' => true,
                'type' => 'integer',
                'description' => 'The user ID',
            ),
        ),
        'schema' => array(
            'type' => 'object',
            'properties' => array(
                'message' => array(
                    'type' => 'string',
                    'description' => 'A message indicating the result of the activation process',
                ),
            ),
        ),
    ));
}

add_action('rest_api_init', 'custom_user_activation_endpoint');

function handle_user_activation($request) {
    $activation_key = sanitize_text_field($request->get_param('key'));
    $user_id = intval($request->get_param('user'));

    // Retrieve the stored activation key
    $stored_activation_key = get_user_meta($user_id, 'activation_key', true);

    if ($activation_key !== $stored_activation_key) {
        return new WP_Error('invalid_key', 'Invalid activation key', array('status' => 400));
    }

    // Activate the user
    delete_user_meta($user_id, 'activation_key');
    update_user_meta($user_id, 'account_status', 'active');

    return new WP_REST_Response(array('message' => 'Account activated successfully.'), 200);
}
?>

Step 5: Testing the API

You can test the API endpoints using tools like Postman or by making HTTP requests using a programming language of your choice.

  1. Register a New User: Make a POST request to https://wp.kreatech.ca/wp-json/custom/v1/register/ with the following JSON body:
{
    "username": "john_doe",
    "email": "john.doe@example.com",
    "password": "securepassword123",
    "contact_number": "1234567890"
}
  1. Activate the User Account: After receiving the confirmation email, click on the activation link or make a GET request to https://wp.kreatech.ca/wp-json/custom/v1/activate with the appropriate key and user parameters.

Summary

This tutorial provides a complete guide to creating custom REST API endpoints in WordPress for user registration and account activation with email confirmation. The provided code handles user creation, validation, and email confirmation, ensuring a seamless registration process.

How can we help?