Subscribe to the Newsletter Endpoint

Updated on Oct 01, 2024

Introduction

WP SMS provides a REST API endpoint that allows you to subscribe users to your SMS newsletter programmatically. This is especially useful for integrating with custom forms or form builders that aren’t directly supported.

The Endpoint

POST https://site.com/wp-json/wpsms/v1/newsletter

Replace site.com with your actual website URL.

Request

Authenticating the Requests

As of version 6.9.4, authentication is required for all requests made to the /newsletter/* endpoints along with the wpsms_subscribers capability. This ensures secure access to the API when subscribing users.
You can learn more about WordPress authentication here.

<?php
// Your WordPress username (with wpsms_subscribers capability) and Application Password
$username = 'your-username';
$password = 'your-application-password';

// Encode credentials for Basic Authentication
$auth = base64_encode("$username:$password");

// Subscriber's information
$postData = array(
    'name'   => 'User Name',
    'mobile' => '912345678'
);

// The endpoint URL
$url = 'https://site.com/wp-json/wpsms/v1/newsletter';

// Set up the arguments for wp_remote_post
$args = array(
    'headers' => array(
        'Authorization' => 'Basic ' . $auth,
        'Content-Type'  => 'application/x-www-form-urlencoded',
    ),
    'body' => $postData,
);

// Make the request
$response = wp_remote_post($url, $args);

// Check for errors
if (is_wp_error($response)) {
    $error_message = $response->get_error_message();
    echo "Error: $error_message";
} else {
    // Get the response body
    $body = wp_remote_retrieve_body($response);
    echo "Response: $body";
}

Response

{
  "message": "Your mobile number has been successfully subscribed.",
  "error": [],
  "data": []
}