PHP code example of otp-com / sdk-php

1. Go to this page and download the library: Download otp-com/sdk-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

otp-com / sdk-php example snippets




use OtpCom\Sdk\Api\OTPApi;
use OtpCom\Sdk\Configuration;
use OtpCom\Sdk\Model\SendRequest;
use OtpCom\Sdk\Model\VerifyRequest;

$config = Configuration::getDefaultConfiguration()
    ->setAccessToken(getenv('OTP_API_KEY'));

$otp = new OTPApi(new GuzzleHttp\Client(), $config);

// 1. Send. You pass the recipient; your account routing picks the channel.
// client_ip = the END USER's IP from your request context, not your server's:
// requests without it share a much tighter rate limit.
$sent = $otp->sendOtp(new SendRequest([
    'recipient' => '+14155552671',
    'locale' => 'en',
    'client_ip' => '81.2.69.142',
]));

$sent->getOtpId();           // keep this: you verify against it
$sent->getChannel();         // 'sms' | 'whatsapp' | 'email' | 'telegram'
$sent->getMaskedRecipient(); // '+14****71', safe to show the user
$sent->getActionUrl();       // WhatsApp only, see below

// 2. Verify whatever the user typed in.
$result = $otp->verifyOtp(new VerifyRequest([
    'otp_id' => $sent->getOtpId(),
    'code' => '123456',
]));

if ($result->getMatched()) {
    // The code was correct; $result->getStatus() is 'approved'.
}

$otp->sendOtp(new SendRequest(['recipient' => $recipient]), "signup:{$userId}");

$sent = $otp->sendOtp(new SendRequest(['recipient' => $recipient]));

if ($sent->getActionUrl() !== null) {
    // Open it for the user. They send us the prefilled message from their own WhatsApp,
    // we reply with the code, and the OTP stays 'pending' until they enter it.
    redirect($sent->getActionUrl());
}

use OtpCom\Sdk\Model\ResendRequest;

// Advance to the next channel in your routing order.
$otp->resendOtp(new ResendRequest(['otp_id' => $sent->getOtpId()]));

// Or move it onto a specific channel, e.g. the user has no WhatsApp.
$otp->resendOtp(new ResendRequest(['otp_id' => $sent->getOtpId(), 'channel' => 'sms']));

$current = $otp->getOtpStatus($sent->getOtpId());
$current->getStatus(); // 'pending' | 'approved' | 'failed' | 'expired'

use OtpCom\Sdk\ApiException;

try {
    $otp->sendOtp(new SendRequest(['recipient' => $recipient]));
} catch (ApiException $e) {
    $error = json_decode($e->getResponseBody(), true)['error'];
    error_log("{$e->getCode()} {$error['type']} {$error['message']}");
    throw $e;
}

$config = Configuration::getDefaultConfiguration()
    ->setAccessToken(getenv('OTP_API_KEY'))          // $client = new GuzzleHttp\Client(['timeout' => 10]);
$otp = new OTPApi($client, $config);