承接 kaydee123/msg91-php 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

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

kaydee123/msg91-php

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

kaydee123/msg91-php 适用场景与选型建议

kaydee123/msg91-php 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 81 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 12 月 02 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「api」 「sms」 「messaging」 「otp」 「msg91」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 kaydee123/msg91-php 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 kaydee123/msg91-php 我们能提供哪些服务?
定制开发 / 二次开发

基于 kaydee123/msg91-php 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

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

GitHub 信息

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

其他信息

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