craftsys/msg91-php

使用 Msg91 API 发送 OTP、验证 OTP、重发 OTP、发送 SMS(短信)等功能的 PHP 客户端。

v0.15.3 2023-01-17 07:39 UTC

README

赞助商

Total Downloads Latest Stable Version License Status

此库需要 PHP 7.1 或更高版本。

这是一个用于Msg91 APIsPHP 客户端。在使用之前,请确保您在Msg91 上有账户并且拥有 Authkey(Msg91 控制台 > API > 配置)。

目录

安装

该包可在Packagist上获取,可以通过在 shell 中执行以下命令通过 Composer 安装。

composer require craftsys/msg91-php

使用

如果您使用 Composer,请确保自动加载器包含在项目的引导文件中

require_once "vendor/autoload.php";

现在可以通过将配置对象传递给构造函数来初始化客户端。

$config = [
  'key' => "123456789012345678901234",
];
$client = new Craftsys\Msg91\Client($config);

该包在 Craftsys\Msg91 命名空间下分发,如果在命名空间环境中工作,可以使用。

<?php
// in your use statement sections
use Craftsys\Msg91\Client;

// somewhere in this source file where you need the client
$client = new Client($config);

// send OTP using the otp service on client
$client->otp()->to(919999999999)->send();

// verify an OTP (1234)
$client->otp(1234)->to(919999999999)->verify();

// send SMS using the sms service on client
$client->sms()->to(919999999999)->flow("<flow_id>")->send();

继续阅读以了解配置和 optsms 服务上可用的方法,并查看示例。

创建客户端

客户端负责与 Msg91 API 交互。

$client =  new Craftsys\Msg91\Client($config);

也可以不配置而初始化客户端,可以通过在客户端实例上调用 setConfig($config) 方法来设置配置。

$client =  new Craftsys\Msg91\Client();
$client->setConfig($config);

您还可以将自定义的 GuzzleHttp\Client 作为客户端构造函数的第二个参数传递。

$client = new Craftsys\Msg91\Client($config, new GuzzleHttp\Client());

配置

该模块可配置以满足您的特定需求,您需要为 API 设置默认选项,如默认 OTP 消息格式、重试方法等。

一个示例配置可能看起来像这样

$config = [
	'key' => "123456789012345678901234",
	'otp_message' => "G: ##OTP## is your verification code".
];

以下配置选项可用

注意:将任何这些值设置为 null 将覆盖默认值到 null。因此,将使用 Msg91 API 的默认值。例如,将 otp_message 设置为 null 将允许使用来自 APIS 的默认消息 "您的验证码是 ##OTP##"。

OTP 和 SMS 服务

客户端创建后,可以访问 otpsms 服务来分别发送 OTP 和 SMS。

注意:在使用客户端上的任何其他服务之前,必须设置配置。

// send otp
$client->otp()->to(919999999999)->send()

// verify a given otp
$client->otp(<otp_to_be_verified>)->to(919999999999)->verify()

// resend otp via voice channel
$client->otp()->to(919999999999)->viaVoice()->resend()

// send sms
$client->sms()->to(919999999999)->flow("<flow_id>")->send();

接下来,通过 示例 了解更多

示例

管理 OTP

通过客户端实例上的 otp 方法可以访问发送、验证和重发等 OTP 服务,例如 $client->otp()。所有 Msg91 API 中的可用参数都有一个相应的直观方法名称,例如,要设置发送 OTP 请求中的 OTP 的数字,您可以在服务上调用 digits 方法。您可以通过 \Craftsys\Msg91\Options 类创建它们。请参阅以下示例以了解更多信息。

发送 OTP

基本用法

$otp = $client->otp();
// an OTP (optional) can be passed to service if you are generating otp on your end
// $otp = $client->otp(4657);

$otp->to(912343434312) // phone number with country code
	->send(); // send the otp

高级用法

您可以通过服务上的options助手来传递所有由Msg91 API接受的自定义选项,而不是依赖于Msg91或客户端的默认设置。此方法接受一个将在下划线\Craftsys\Msg91\OTP\Options实例上被调用的close,并允许您添加所需的所有选项。

$otp->to(91123123123)
    ->from("SENDER_ID") // sender id
    ->template("AFH") // template id for otps
    ->options(function (\Craftsys\Msg91\OTP\Options $options) {
        $options->digits(6) // set the number of digits in generated otp
          ->message("##OTP## is your verification code") // custom template
          ->expiresInMinutes(60); // set the expiry
    })
	->send() // finally send

注意:如果您在自己的端生成OTP并将其传递给服务,同时附带自定义消息,您必须在消息中包含##OTP##或OTP的实际值。未这样做将导致错误。

// OK
$client->otp(123242)->message('Your OTP is: 123242')->send();

// NOT OK!
$client->otp(123123)->message("Use this for verification")->send();
// This will result in error with "Message doesn't contain otp"

验证 OTP

由于验证不发送任何消息,您只需要提供验证OTP所需的字段,例如发送的OTP和电话号码。

$otp = $client->otp(12345);  // OTP to be verified

$otp->to(912343434312) // phone number with country code
	->verify(); // Verify

重发 OTP

要重新发送OTP,访问otp服务并调用resend来重新发送OTP。在发送OTP之前,可以通过调用viaVoiceviaText来更改通信方法。默认值可以在配置中设置。

$otp = $client->otp();

$otp->to(912343434312) // set the mobile with country code
	->viaText() // or ->viaVoice()
	->resend(); // resend otp

发送 SMS

要发送短信,通过在客户端实例上调用->sms()方法访问SMSService

$sms = $client->sms();

$sms->to(912343434312) // set the mobile with country code
    ->flow('flow_id_here') // set the flow id
	->message("You have 10 pending tasks for the end of the day") // message content
	->send(); // send the message

要向消息添加更多选项,您可以在发送消息之前调用options方法。选项方法接受一个调用,该调用将接收一个\Craftsys\Msg91\SMS\Options实例。使用它,您可以修改任何所需的选项。

$client->sms()
    ->to(919999999999)
    ->flow('flow_id_here') // set the flow id
    ->options(function ($options) {
        $options->transactional() // set that it is a transactional message
            ->from('CMPNY') // set the sender
            ->unicode(); // handle unicode as the message contains unicode characters
    })
    ->message("I ❤️ this package. Thanks.")
    ->send();

消息变量

要发送短信,您创建一个Flow,在其中您可以提供用于短信的模板。此模板可能包含一些变量,您可以将它们用作每条消息数据的占位符。您可以使用recipients方法在发送短信时为每个接收者设置这些变量的值,如下所示。

假设您已创建以下消息模板的Flow:

Hi ##name##, Your reward credits will expire on ##date##.
Claim them to get exclusive benefits

我们将为每个接收者更新namedate变量。

$client->sms()
    ->flow('flow_id_here') // set the flow id
    ->recipients([
        ['mobiles' => '919999999999', 'name' => 'Sudhir M', 'date' => '20 Jan, 2022'],
        ['mobiles' => '919898912312', 'name' => 'Craft Sys', 'date' => '25 Jan, 2022']
    ])
    ->options(function ($options) {
        $options->receiverKey('mobiles'); // set your receiver key
    })
    ->send();

recipients数组中的mobiles键来自创建新Flow时设置的receiver字段值。它默认为mobiles。如果您已提供不同的receiver键,请相应地更新recipients键

如果您想要为所有接收者设置变量的相同值,您可以使用以下方法使用variable

$client->sms()
    ->flow('flow_id_here') // set the flow id
    ->to([919898912312, 912343434312]) // you can pass an array of mobile numbers
    ->variable('overdue', 'Yes') // set the "overdue" variable's value to "Yes"
    ->variable('url', 'https://domain.com') // set the "url" variable's value to "https://domain.com"
    ->send();

// you can also combine this with existing variables if you want e.g.
$client->sms()
    ->flow('flow_id_here') // set the flow id
    ->recipients([
        ['mobiles' => '919999999999', 'name' => 'Sudhir M', 'date' => '20 Jan, 2022'],
        ['mobiles' => '919898912312', 'name' => 'Craft Sys', 'date' => '25 Jan, 2022']
    ])
    ->variable('overdue', 'Yes') // will set the "overdue" for all recipients
    ->send();

注意:您应该在设置接收者之后调用variable方法。

接收者密钥

在创建MSG91上的Flow时,您可以创建一个自定义的receiver键,默认为##mobiles##。此默认值也在此包中使用。如果您已使用不同的receiver键配置了您的flow,您可以通过以下方法设置它:

假设您已将receiver字段设置为##contact##

$client->sms()
    ->to(919999999999)
    ->flow('flow_id_here') // set the flow id
    ->options(function ($options) {
        $options->receiverKey('contact'); // your receiver key
    })
    ->send();

处理响应

所有服务都将为所有成功响应返回\Craftsys\Msg91\Support\Response实例,并在以下情况下抛出异常:

  • \Craftsys\Msg91\Exceptions\ValidationException: 请求验证失败
  • \Craftsys\Msg91\Exceptions\ResponseErrorException: 响应中存在错误
try {
    $response = $client->otp()->to(919999999999)->send();
    // response data
    // $response->getData();
    // response message
    // $response->getMessage();
    // response status code
    // $response->getStatusCode();
} catch (\Craftsys\Msg91\Exceptions\ValidationException $e) {
    // issue with the request e.g. token not provided
} catch (\Craftsys\Msg91\Exceptions\ResponseErrorException $e) {
    // error thrown by msg91 apis or by http client
} catch (\Exception $e) {
    // something else went wrong
    // please report if this happens :)
}

相关

致谢

我们对现有相关项目的作者表示感谢,感谢他们的想法和合作。