定制 kaydee123/msg91-php 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

kaydee123/msg91-php

最新稳定版本:v1.0.0

Composer 安装命令:

composer require kaydee123/msg91-php

包简介

A PHP client library for MSG91 SMS and OTP services. Compatible with PHP 8.0 through 8.5.

README 文档

README

A PHP client library for MSG91 SMS and OTP services. Compatible with PHP 8.0 through 8.5.

Features

  • Send SMS messages (single and bulk)
  • Send OTP via SMS
  • Verify OTP codes
  • Retry/Resend OTP (text or voice)
  • Template-based SMS support
  • DLT compliance support for India
  • Comprehensive error handling
  • Framework-agnostic (works with any PHP project)

Requirements

  • PHP 8.0 to 8.5
  • Composer
  • MSG91 account with API credentials

Installation

Install the package via Composer:

composer require kaydee123/msg91-php

Configuration

First, you need to get your MSG91 Auth Key from your MSG91 Dashboard.

Usage

Basic Setup

<?php

require 'vendor/autoload.php';

use Kaydee123\Msg91\Msg91Client;

// Initialize the client
$client = new Msg91Client('YOUR_AUTH_KEY');

Chainable API

The package provides a fluent, chainable interface for easy and intuitive usage:

SMS Examples

Send SMS using Template (Recommended):

$response = $client->sms()
    ->template('YOUR_TEMPLATE_ID')
    ->variables(['number' => '3', 'date' => '22-12-2025'])
    ->numbers('919876543210')
    ->send();

Send SMS to Multiple Recipients with Variables:

$response = $client->sms()
    ->template('YOUR_TEMPLATE_ID')
    ->numbers(['919876543210', '919876543211'])
    ->variables(['number' => '3', 'date' => '22-12-2025'])
    ->send();

Send SMS with Individual Recipient Variables:

$response = $client->sms()
    ->template('YOUR_TEMPLATE_ID')
    ->recipients([
        ['mobiles' => '919876543210', 'number' => '3', 'date' => '22-12-2025'],
        ['mobiles' => '919876543211', 'number' => '5', 'date' => '23-12-2025'],
    ])
    ->send();

Send DLT SMS (Promotional):

$response = $client->sms()
    ->promotional()
    ->sender_id('YOUR_SENDER_ID')
    ->mobiles("9876543210,9876543211")
    ->dlt_template_id("YOUR_DLT_TEMPLATE_ID")
    ->message("Your promotional message here")
    ->send();
// Country code 91 is automatically added

Send DLT SMS (Transactional):

$response = $client->sms()
    ->transactional()
    ->sender_id('YOUR_SENDER_ID')
    ->mobiles("9876543210")
    ->dlt_template_id("YOUR_DLT_TEMPLATE_ID")
    ->message("Your transactional message here")
    ->send();
// Country code 91 is automatically added

OTP Examples

Send OTP (Template ID required, especially for India):

// Template ID is mandatory for Indian numbers (91) due to DLT compliance
$response = $client->otp()
    ->template('YOUR_OTP_TEMPLATE_ID')
    ->number('919876543210')
    ->send();

Send OTP with Custom Options:

$response = $client->otp()
    ->template('YOUR_OTP_TEMPLATE_ID')
    ->number('919876543210')
    ->length(6)        // OTP length (optional)
    ->expiry(10)      // Expiry in minutes (optional)
    ->send();

Send Custom OTP:

$response = $client->otp('123456')
    ->template('YOUR_OTP_TEMPLATE_ID')
    ->number('919876543210')
    ->send();

Verify OTP:

$response = $client->otp('565656')
    ->number('919876543210')
    ->verify();

Retry/Resend OTP:

// Retry as text SMS
$response = $client->otp()
    ->number('919876543210')
    ->viaText()
    ->retry();

// Retry as voice call
$response = $client->otp()
    ->number('919876543210')
    ->viaVoice()
    ->retry();

// Or use resend (text by default)
$response = $client->otp()
    ->number('919876543210')
    ->resend();

DLT Compliance for India

DLT (Distributed Ledger Technology) is mandatory for sending commercial SMS in India. TRAI requires all SMS messages to be DLT-compliant.

Recommended Method: Register Template with MSG91

The recommended approach is to register your SMS templates with MSG91, which includes the DLT template ID. Once registered, you can use the template-based methods above, and MSG91 will automatically handle DLT compliance:

// Using template-based SMS (v5 API) - DLT handled automatically
$response = $client->sms()
    ->template('YOUR_MSG91_TEMPLATE_ID')  // This template includes DLT template ID
    ->variables(['var1' => 'value1'])
    ->numbers('919876543210')
    ->send();

DLT Requirements Summary

  1. Entity Registration: Register your business on a DLT platform
  2. Sender ID Registration: Register your Sender ID (Header) on DLT platform
  3. Template Registration: Register your SMS templates on DLT platform to get Template IDs
  4. MSG91 Integration: Register templates with MSG91 (includes DLT template ID)

OTP Template ID Requirement for India

Important: For Indian mobile numbers (country code 91), a Template ID is mandatory when sending OTP due to DLT compliance requirements. The package will automatically validate this requirement and throw an error if template ID is missing for Indian numbers.

// ✅ Correct - Template ID provided for India
$response = $client->otp()
    ->template('YOUR_DLT_TEMPLATE_ID')  // Required for India
    ->number('919876543210')  // Indian number (starts with 91)
    ->send();

// ❌ Will throw error - Template ID missing for Indian number
$response = $client->otp()
    ->number('919876543210')  // Indian number
    ->send();  // Missing template() - will throw InvalidArgumentException

Note: The template ID must be a DLT-registered template in your MSG91 dashboard. For non-Indian numbers, template ID is still required by MSG91 v5 API, but the DLT compliance validation is specific to India.

Advanced Configuration

Custom Client Options

$client = new Msg91Client('YOUR_AUTH_KEY', [
    'base_url' => 'https://control.msg91.com/api/',  // Custom base URL (default)
    'timeout' => 60,                                  // Request timeout in seconds
    'debug' => true,                                  // Enable debug logging
]);

Troubleshooting

Common Error Codes

Error 400: Flow ID Missing or Invalid Flow

If you receive error code 400 when sending OTP, it usually means:

  1. Invalid Template ID: The template_id you're using might not be a valid OTP template or might not be approved in your MSG91 dashboard.

    • Solution: Verify your template ID in the MSG91 dashboard and ensure it's an OTP template (not a flow template).
    • Check that the template is approved and active.
  2. Template Not Approved: The template might be pending approval or rejected.

    • Solution: Log into your MSG91 dashboard and check the template status.
  3. Wrong Template Type: You might be using a Flow template ID instead of an OTP template ID.

    • Solution: Ensure you're using an OTP template ID, not a Flow ID.
  4. DLT Compliance Issues (India): For Indian numbers, the template must be DLT-compliant.

    • Solution: Ensure your OTP template is registered with DLT and linked in MSG91 dashboard.

Example Error Handling:

try {
    $response = $client->otp()
        ->template('YOUR_TEMPLATE_ID')
        ->number('919876543210')
        ->send();
} catch (\Kaydee123\Msg91\Exceptions\ApiException $e) {
    if ($e->getStatusCode() === 400) {
        echo "Error 400: " . $e->getMessage();
        echo "\nPlease verify your template_id is correct and is an OTP template.";
        // Check response data for more details
        print_r($e->getResponse());
    }
}

Error 211: DLT Template Id Missing

This error occurs when sending SMS to Indian numbers without a DLT template ID.

  • Solution: Use a DLT-registered template or provide dlt_template_id when using the DLT SMS method.

Error 203: Invalid sender ID or DLT Entity Id Missing

This error indicates an invalid sender ID or missing DLT entity ID.

  • Solution: Verify your sender ID is registered and DLT-compliant (for India).

For more error codes, refer to MSG91 Error Codes Documentation.

Error Handling

The package provides custom exception classes for better error handling:

use Kaydee123\Msg91\Exceptions\Msg91Exception;
use Kaydee123\Msg91\Exceptions\ApiException;

try {
    $response = $client->sms()
        ->template('YOUR_TEMPLATE_ID')
        ->to('919876543210')
        ->send();
} catch (ApiException $e) {
    // API-specific errors
    echo "API Error: " . $e->getMessage();
    echo "Status Code: " . $e->getStatusCode();
    print_r($e->getResponse());
} catch (Msg91Exception $e) {
    // General MSG91 errors
    echo "Error: " . $e->getMessage();
} catch (\Exception $e) {
    // Other errors
    echo "Unexpected error: " . $e->getMessage();
}

API Reference

Chainable API Methods

SMSBuilder Methods

  • template($templateId) - Set template ID for template-based SMS (required)
  • numbers($mobiles) - Set recipient mobile number(s) - string or array (alias for to())
  • to($mobile) - Set recipient mobile number(s) - string or array
  • variables(array $variables) - Set multiple template variables (optional)
  • variable($key, $value) - Set a single template variable (optional)
  • recipients(array $recipients) - Set recipients with individual variables (array of objects)
  • promotional() - Set route to promotional (route 1)
  • transactional() - Set route to transactional (route 4, default)
  • sender_id($id) - Set sender ID (alias for from(), required for DLT SMS)
  • mobiles($mobiles) - Set mobiles for DLT SMS - comma-separated string or array
  • dlt_template_id($id) - Set DLT Template ID (alias for dltTemplateId(), India only)
  • message($message) - Set SMS message content (required for DLT SMS)
  • short_url($url) - Set short URL (optional, default: '0')
  • short_url_expiry($expiry) - Set short URL expiry (optional, default: '0')
  • send() - Send the SMS

OTPBuilder Methods

  • template($templateId) - Set template ID (required)
  • number($mobile) - Set mobile number (alias for to())
  • to($mobile) - Set mobile number
  • length($digits) - Set OTP length/digits (optional, alias for digits(), default: 4)
  • expiry($minutes) - Set OTP expiry in minutes (optional, alias for expiresInMinutes(), default: 1)
  • digits($digits) - Set number of OTP digits (default: 4)
  • expiresInMinutes($minutes) - Set OTP expiry in minutes (default: 1)
  • variable($key, $value) - Set a template variable (optional)
  • variables(array $variables) - Set multiple template variables (optional)
  • viaText() - Set retry type to text
  • viaVoice() - Set retry type to voice
  • send() - Send OTP
  • verify($otp) - Verify OTP code
  • retry() - Retry/resend OTP
  • resend() - Resend OTP (text by default)

Route Types

  • '4' - Transactional SMS (default)
  • '1' - Promotional SMS

Country Codes

Common country codes:

  • '91' - India (default)
  • '1' - USA/Canada
  • '44' - UK
  • '61' - Australia

For a complete list, refer to MSG91 documentation.

PHP Version Compatibility

This package is tested and compatible with:

  • PHP 8.0
  • PHP 8.1
  • PHP 8.2
  • PHP 8.3
  • PHP 8.4
  • PHP 8.5

Testing

Unit Tests

The package includes comprehensive PHPUnit tests. To run the tests:

# Install dependencies
composer install

# Run all tests
vendor/bin/phpunit

# Run tests with coverage
vendor/bin/phpunit --coverage-text

For testing across multiple PHP versions, see the Testing Guide.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This package is open-sourced software licensed under the MIT license.

Support

For MSG91 API documentation, visit https://docs.msg91.com/

For issues related to this package, please open an issue on GitHub.

Changelog

1.0.0

  • Initial release
  • SMS sending (single and bulk)
  • OTP sending, verification, and retry
  • Template and Flow-based SMS support
  • Comprehensive error handling
  • Full test coverage with PHPUnit

统计信息

  • 总下载量: 3
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 0
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-12-02