mane-olawale/laravel-termii

用于Termii SMS API的Laravel包。

v1.0.6 2023-11-19 12:42 UTC

This package is auto-updated.

Last update: 2024-09-19 14:44:19 UTC


README

Github Total Downloads Latest Stable Version License

Termii Laravel包

用于将termii服务与您的Laravel应用程序集成的包。

使用Termii客户端

要求

安装

通过Composer

要获取最新版本的Laravel Termii,只需在您的laravel项目根目录下运行。

composer require mane-olawale/laravel-termii

Composer安装Laravel termii包后,您可以运行termii:install Artisan命令。此命令会发布名为termii.php的包配置文件。

php artisan termii:install

设置

打开您的.env文件,并添加您的API密钥、发送者ID、通道等。

TERMII_API_KEY=xxxxxxxxxxxxx
TERMII_SENDER_ID=xxxxxxx
TERMII_CHANNEL=generic
TERMII_MESSAGE_TYPE=ALPHANUMERIC
TERMII_TYPE=plain

# Pin Configurations
TERMII_PIN_ATTEMPTS=10
TERMII_PIN_TIME_TO_LIVE=20
TERMII_PIN_LENGTH=6
TERMII_PIN_PLACEHOLDER="{pin}"
TERMII_PIN_TYPE=NUMERIC

# Extra
TERMII_SMS_NAME="${APP_NAME}"
TERMII_USER_AGENT="${APP_NAME}"

基本用法

使用Termii门面类发送短信

<?php

use ManeOlawale\Laravel\Termii\Facades\Termii;

Termii::send('2347041945964', 'Hello World!');

# With sender id and channel

Termii::send('2347041945964', 'Hello World!', 'Olawale', 'generic');

服务

您可以通过将它们作为门面类上的函数直接调用客户端服务来访问客户端服务。

<?php

use ManeOlawale\Laravel\Termii\Facades\Termii;

// @return \ManeOlawale\Termii\Api\Sender
Termii::sender();
// @return \ManeOlawale\Termii\Api\Sms
Termii::sms();
// @return \ManeOlawale\Termii\Api\Token
Termii::token();
// @return \ManeOlawale\Termii\Api\Insights
Termii::insights();

// On the client
$client->sender->request('Olawale', 'Friendship based notification', 'Olawale INC');

// On the facade class
Termii::sender()->request('Olawale', 'Friendship based notification', 'Olawale INC');

通知频道

此包为您提供了一个通知频道,使您可以通过Laravel的通知功能发送短信,如下所示:

创建通知类

php artisan make:notification WelcomeText

将termii频道添加到通知

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use ManeOlawale\Laravel\Termii\Messages\Message as TermiiMessage;

class WelcomeText extends Notification
{
    use Queueable;

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['termii'];
    }

    /**
     * Get the termii sms representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \ManeOlawale\Laravel\Termii\Messages\Message
     */
    public function toTermii($notifiable)
    {
        return (new TermiiMessage)
                    ->line('The introduction to the notification.')
                    ->line('Thank you for using our application!');
    }
}

为用户添加路由 以便通知频道可以获取用户的电话号码。

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable //implements MustVerifyEmail
{
    use HasFactory, Notifiable;

    public function routeNotificationForTermii()
    {
        return $this->phone;
    }
}

更多关于TermiiMessage

处理消息内容

# Using constructor
$message = new TermiiMessage('Olawale wants to connect with you.');

# Using the line method
$message = (new TermiiMessage)
    ->line('Debit Alert!')
    ->line('Acct: *******324')
    ->line('Amt: 21,500.00')
    ->line('DESC: squander am!')
    ->line('Trx: 37373-3843-4')
    ->line('Time: 22/02/2022|4:32 PM')
    ->line('Avail Bal: 3,642,873.00')
    ->line('Total Bal: 3,742,873.00');

# Overwriting the content
$message->content('Olawale is your first contributor.');

# Getting the content
$message->getContent();

您可以通过对TermiiMessage对象链式调用方法来配置通过通知频道发送的短信,如下所示:

    /**
     * Get the termii sms representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \ManeOlawale\Laravel\Termii\Messages\Message
     */
    public function toTermii($notifiable)
    {
        return (new TermiiMessage('Someone wants to connect with you.'))
            ->from('sender_id')
            ->channel('generic')
            ->type('unicode')
            ->unicode()
            ->line('Thank you for using our application!');
    }

注意

  • 默认消息类型为unicode,但您可以使用TermiiMessage::type()方法设置任何可能后来引入的类型。

  • 如果没有完成这些配置,将使用默认配置。

处理OTP

此包为您提供适当的工具,在无状态或状态请求中发送和验证OTP。

状态OTP

此包可以在状态请求中发送OTP,它依赖于会话通过使用类似这样的标签来存储pin_id和其他数据。

use ManeOlawale\Laravel\Termii\Facades\Termii;

$otp = Termii::OTP('login_account');

# Set Number
$otp->to('2347041945964');

# Set text
$otp->text('{pin} is your account activation code');

# Send the OTP
$otp->start();

注意

  • 您可以将这些方法链接在一起。
  • Token::start()方法将发送OTP并返回self

无状态OTP

此包可以在无状态请求中发送OTP,它依赖于JWT以安全地将数据加密为字符串。

use ManeOlawale\Laravel\Termii\Facades\Termii;

$otp = Termii::OTP('login_account');

# Set Number
$otp->to('2347041945964');

# Set text
$otp->text('{pin} is your account activation code');

# Send the OTP
$otp->start();

$encrypted = $otp->signature(); // eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQi...

验证OTP

状态OTP

use ManeOlawale\Laravel\Termii\Facades\Termii;

$otp = Termii::OTP('login_account');

if ($otp->verify('1234')) {
    return redirect()->back()->with([
        'success' => 'Account verified'
    ]);
} else {
    return redirect()->back()->with([
        'error' => 'Invalid OTP'
    ]);
}

无状态OTP

use ManeOlawale\Laravel\Termii\Facades\Termii;

$otp = Termii::OTP('login_account', 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQi.........');

if ($otp->verify('1234')) {
    return response()->json([
        'success' => 'Account verified'
    ], 200);
} else {
    return response()->json([
        'error' => 'Invalid OTP'
    ], 422);
}

应用内OTP

您可以通过将Token::inApp()方法链接到您的令牌来创建应用内令牌,如下所示:

use ManeOlawale\Laravel\Termii\Facades\Termii;

$otp = Termii::OTP('login_account');

# Set Number
$otp->to('2347041945964');

# Set text
$otp->text('{pin} is your account activation code');


# Set text
$otp->inApp();

# Send the OTP
$otp->start();

关于OTP的更多信息

在调用Token::start()方法后,您可以检索一些令牌属性。

# Send the OTP
$otp->start();

# Get the pin id
$otp->id();

# Get the tag
$otp->tag();

# Check if the OTP has expired
$otp->isValid();

# Get the pin only for in app tokens
$otp->pin();

链式方法

use ManeOlawale\Laravel\Termii\Facades\Termii;

// Regular
$otp = Termii::OTP('login_account')->to('2347041945964')
    ->text('{pin} is your account activation code')->start();

// In App
$otp = Termii::OTP('login_account')->to('2347041945964')
    ->text('{pin} is your account activation code')->inApp()->start();

测试

此包支持TDD,因此您可以有信心快速构建。

端点别名

端点用别名表示,便于模拟和断言。以下是可以用的别名:

模拟和序列

序列 序列允许您创建一个响应集合,当列表执行完毕时,将从第一个元素开始。

use GuzzleHttp\Psr7\Response;
use ManeOlawale\Laravel\Termii\Testing\Sequence;

    $sequence = Sequence::create(
        new Response(200),
        new Response(300),
        new Response(400)
    );

    $sequence->next(); // new Response(200);
    $sequence->next(); // new Response(300);
    $sequence->next(); // new Response(400);
    $sequence->next(); // new Response(200);

    $sequence->count(); // int: 3

    # This is the number of times the sequence start all over.
    $sequence->rotation(); // int: 1

使用序列模拟

下面的示例将使用响应模拟send端点。

use GuzzleHttp\Psr7\Response;
use ManeOlawale\Laravel\Termii\Facades\Termii;
use ManeOlawale\Laravel\Termii\Testing\Sequence;

Termii::fake();

Termii::mock('send', Sequence::create(new Response(
    200,
    ['Content-Type' => 'application/json'],
    json_encode($data = [
        'message_id' => '9122821270554876574',
        'message' => 'Successfully Sent',
        'balance' => 9,
        'user' => 'Peter Mcleish'
    ])
)));

$this->get('/send_text'); // Let us assume message was sent twice

Termii::assertSent('send');

# Assert the message was sent twice
Termii::assertSentTimes('send', 2);

注意:模拟适用于所有别名,而不仅仅是send

断言

断言未发送

use GuzzleHttp\Psr7\Response;
use ManeOlawale\Laravel\Termii\Facades\Termii;
use ManeOlawale\Laravel\Termii\Testing\Sequence;

Termii::fake();

$this->get('/send_text'); // Let us assume no message was sent

Termii::assertNotSent('send');

# Assert the message was sent twice
Termii::assertSentTimes('send', 0);

注意:这适用于所有别名,而不仅仅是send

断言成功和失败的请求

在这个例子中,我们将断言端点返回的状态码在100 - 299范围内或未返回。

use GuzzleHttp\Psr7\Response;
use ManeOlawale\Laravel\Termii\Facades\Termii;
use ManeOlawale\Laravel\Termii\Testing\Sequence;

Termii::fake();

Termii::mock('send', Sequence::create(new Response(
    200,
    ['Content-Type' => 'application/json'], '{}'
), new Response(
    200,
    ['Content-Type' => 'application/json'], '{}'
), new Response(
    422,
    ['Content-Type' => 'application/json'], '{}'
)));

/** 
 * Let us assume message was sent three times.
 * This means one wont be successful
*/
$this->get('/send_text');

# For successful requests
Termii::assertSentSuccessful('send');
# Assert the message was sent successfully twice
Termii::assertSentSuccessfulTimes('send', 2);

# For failed requests
Termii::assertSentFailed('send');
# Assert the message failed once
Termii::assertSentFailedTimes('send', 1);

注意:这适用于所有别名,而不仅仅是send

深度断言

您可以使用Termii::assert()方法更深入地断言请求和响应对象。

使用闭包

use GuzzleHttp\Psr7\Response;
use ManeOlawale\Laravel\Termii\Facades\Termii;
use ManeOlawale\Laravel\Termii\Testing\Sequence;

Termii::fake();

Termii::mock('send', Sequence::create(new Response(
    200,
    ['Content-Type' => 'application/json'],
    json_encode([
        'message_id' => '9122821270554876574',
        'message' => 'Successfully Sent',
        'balance' => 9,
        'user' => 'Peter Mcleish'
    ])
)));

$this->get('/send_text'); // Let us assume message was sent once

Termii::assert('send', function ($pair) {
    //Correct alias
    $this->assertSame('send', $pair['alias']);

    //Check if what happened between the request and response was successful
    $this->assertTrue($pair['successful']);
});

注意

  • 这适用于所有别名,而不仅仅是send
  • 这仅断言第一对请求和响应,如果您需要更多的断言,请使用下面的序列。

使用序列

use GuzzleHttp\Psr7\Response;
use ManeOlawale\Laravel\Termii\Facades\Termii;
use ManeOlawale\Laravel\Termii\Testing\Sequence;

Termii::fake();

Termii::mock('send', Sequence::create(new Response(
    200,
    ['Content-Type' => 'application/json'], '{}'
), new Response(
    422,
    ['Content-Type' => 'application/json'], '{}'
)));

$this->get('/send_text'); // Let us assume message was sent twice

Termii::assert('send', Sequence::create(
    function ($pair) {
        //Correct alias
        $this->assertSame('send', $pair['alias']);

        //Check if what happened between the request and response was successful
        $this->assertTrue($pair['successful']);
    },
    function ($pair) {
        //Correct alias
        $this->assertSame('send', $pair['alias']);

        //Check if what happened between the request and response was not successful
        $this->assertNotTrue($pair['successful']);
    }
));

后备响应

如果您没有指定应用程序中要调用的端点,将使用默认的后备响应,这是一个空的成功的JSON响应。但您可以使用Termii::fallbackResponse()来更改它。

use GuzzleHttp\Psr7\Response;
use ManeOlawale\Laravel\Termii\Facades\Termii;

Termii::fake();

Termii::fallbackResponse(new Response(
    400,
    ['Content-Type' => 'application/json'],
    json_encode([
        'message' => 'Error'
    ])
));

$this->get('/send_text'); // Let us assume message was sent once

# Assert the failed request
Termii::assertSentFailed('send');
# Assert the message failed once
Termii::assertSentFailedTimes('send', 1);

注意 测试在您的应用程序中非常重要。您的应用程序的每个部分都应该经过测试,尤其是那些您不维护的与其他系统集成部分。这就是我费尽心思提供这个具有TDD支持的包的原因,这样您就可以创建并断言Laravel应用程序的行为,以确保一切按预期工作。 **~ Olawale**