Set OTPMOCK_URL=https://api.otpmock.com in your test environment, point the Plivo client at it, and use your otpmock API key as the Plivo credential. Your application code doesn't change, and production keeps sending real SMS through Plivo.
Setup
The Plivo SDK accepts a url option that replaces its account base URL. It works but isn't documented by Plivo.
import plivo from "plivo";
const authId = process.env.PLIVO_AUTH_ID;
export const plivoClient = new plivo.Client(
authId,
process.env.PLIVO_AUTH_TOKEN, // otpmock API key in tests
process.env.OTPMOCK_URL ? { url: `${process.env.OTPMOCK_URL}/v1/Account/${authId}` } : {},
);import os
from urllib.parse import urlparse
import plivo
plivo_client = plivo.RestClient(
os.environ["PLIVO_AUTH_ID"],
os.environ["PLIVO_AUTH_TOKEN"], # otpmock API key in tests
)
otpmock = os.environ.get("OTPMOCK_URL")
if otpmock: # the SDK has no host option: rewrite the host of each request
_send = plivo_client.session.send
def _send_to_otpmock(request, *args, **kwargs):
u = urlparse(request.url)
request.url = otpmock.rstrip("/") + u.path + ("?" + u.query if u.query else "")
return _send(request, *args, **kwargs)
plivo_client.session.send = _send_to_otpmockimport com.fasterxml.jackson.databind.module.SimpleModule;
import com.plivo.api.PlivoClient;
import com.plivo.api.models.base.LogLevel;
import okhttp3.OkHttpClient;
String otpmock = System.getenv("OTPMOCK_URL");
String authToken = System.getenv("PLIVO_AUTH_TOKEN"); // otpmock API key in tests
PlivoClient plivo = otpmock == null
? new PlivoClient(authId, authToken)
: new PlivoClient(authId, authToken, new OkHttpClient.Builder(), otpmock + "/v1/", new SimpleModule(), LogLevel.NONE);
// Message.creator(src, dst, text).client(plivo).create();
// VerifySession.creator(...).client(plivo).create();// The Plivo .NET SDK has no base URL option; in apps that must be testable, call the REST API.
var plivoUrl = Environment.GetEnvironmentVariable("OTPMOCK_URL") ?? "https://api.plivo.com";
var authId = Environment.GetEnvironmentVariable("PLIVO_AUTH_ID");
var authToken = Environment.GetEnvironmentVariable("PLIVO_AUTH_TOKEN"); // otpmock API key in tests
var http = new HttpClient { BaseAddress = new Uri(plivoUrl) };
http.DefaultRequestHeaders.Authorization = new("Basic",
Convert.ToBase64String(Encoding.UTF8.GetBytes($"{authId}:{authToken}")));
await http.PostAsJsonAsync($"/v1/Account/{authId}/Message/",
new { src = "+15550000001", dst = phone, text = $"Your code is {code}" });use GuzzleHttp\Client;
// plivo/plivo-php hard-codes api.plivo.com, so call the REST path directly.
$plivoUrl = getenv('OTPMOCK_URL') ?: 'https://api.plivo.com';
$authId = getenv('PLIVO_AUTH_ID');
(new Client())->post("$plivoUrl/v1/Account/$authId/Message/", [
'auth' => [$authId, getenv('PLIVO_AUTH_TOKEN')], // auth token = otpmock API key in tests
'json' => ['src' => '+15550000001', 'dst' => '+15550142', 'text' => "Your code is $code"],
]);require "net/http"
require "json"
PLIVO_URL = ENV.fetch("OTPMOCK_URL", "https://api.plivo.com")
auth_id = ENV["PLIVO_AUTH_ID"]
uri = URI("#{PLIVO_URL}/v1/Account/#{auth_id}/Message/")
req = Net::HTTP::Post.new(uri, "Content-Type" => "application/json")
req.basic_auth(auth_id, ENV["PLIVO_AUTH_TOKEN"]) # otpmock API key in tests
req.body = { src: "+15550000001", dst: "+15550142", text: "Your code is #{code}" }.to_json
res = Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |h| h.request(req) }// otpmockTransport sends SDK requests to otpmock, keeping path, query and auth.
type otpmockTransport struct{ base *url.URL }
func (t otpmockTransport) RoundTrip(r *http.Request) (*http.Response, error) {
r = r.Clone(r.Context())
r.URL.Scheme, r.URL.Host, r.Host = t.base.Scheme, t.base.Host, t.base.Host
return http.DefaultTransport.RoundTrip(r)
}
func newPlivo() (*plivo.Client, error) {
opts := &plivo.ClientOptions{}
if base, err := url.Parse(os.Getenv("OTPMOCK_URL")); err == nil && base.Host != "" {
opts.HttpClient = &http.Client{Transport: otpmockTransport{base}}
}
return plivo.NewClient(os.Getenv("PLIVO_AUTH_ID"), os.Getenv("PLIVO_AUTH_TOKEN"), opts) // token = otpmock API key in tests
}Each language is tested in CI against otpmock with the provider's official SDK, or its plain HTTP API where no SDK can be pointed at another host.
Credentials. In the test environment, set PLIVO_AUTH_TOKEN to your otpmock API key. The Auth ID can stay as it is.
What otpmock emulates
| Endpoint | What it does |
|---|---|
POST /v1/Account/{auth_id}/Message/ | Send an SMS (multiple recipients separated by <) |
POST /v1/Account/{auth_id}/Verify/Session/ | Verify: create a session (otpmock generates the OTP; code_length 4–8, default 6; brand_name used in the text) |
POST /v1/Account/{auth_id}/Verify/Session/{uuid}/ | Verify: validate the otp (400 on a wrong OTP, up to 10 attempts) |
GET /v1/Account/{auth_id}/Verify/Session/{uuid}/ | Verify: get the session (status in-progress, verified or expired) |
Responses and errors follow Plivo's own format, so the SDK parses them as usual. Authentication failures and an exhausted monthly allowance also come back in Plivo's error shape.
Phone numbers
Send in E.164 (+15550142) or without +.
How to tell your app uses Plivo
Look for any of these in your codebase to confirm where the SMS is sent, and therefore where the otpmock option has to be set:
plivoin package.jsonclient.messages.create(client.verify_session.
Read the code in your tests
const phone = otp.randomPhone();
const since = Date.now() - 5_000;
await page.getByRole("button", { name: "Send code" }).click(); // your app calls Plivo
const { code } = await otp.waitForCode(phone, { since });The otp helper is a single file: get it from the docs. Full walkthroughs: Playwright, Cypress.
FAQ
Does otpmock send real SMS through Plivo?
No. In the test environment your app's Plivo requests go to otpmock, which stores the message for 10 minutes and never contacts Plivo or any carrier. Production keeps using Plivo because otpmock is only enabled when OTPMOCK_URL is set.
Is the official plivo SDK supported?
Yes. otpmock's Plivo endpoints are tested end to end with the official plivo package for Node.js. Other languages work too if their Plivo client lets you change the API host.
Which Plivo APIs does otpmock support?
POST /v1/Account/{auth_id}/Message/ (Send an SMS (multiple recipients separated by <)); POST /v1/Account/{auth_id}/Verify/Session/ (Verify: create a session (otpmock generates the OTP; code_length 4–8, default 6; brand_name used in the text)); POST /v1/Account/{auth_id}/Verify/Session/{uuid}/ (Verify: validate the otp (400 on a wrong OTP, up to 10 attempts)); GET /v1/Account/{auth_id}/Verify/Session/{uuid}/ (Verify: get the session (status in-progress, verified or expired)).
The free plan includes 300 messages a month. Using an AI coding assistant? Point it at otpmock.com/llms-full.txt.
Get a free API key