parSilver/laravel-sms

laravel 框架的 SMS 服务提供商

1.2.0 2022-04-23 07:47 UTC

This package is auto-updated.

Last update: 2024-09-23 12:45:51 UTC


README

发送 SMS 从此不再困难,只需

<?php

\SMS::send('0899991111', 'This is message');

系统需求

PHP 7.1 ขึ้นไป
Laravel 5.x หรือสูงกว่า

安装

使用 composer 命令安装

composer require parsilver/laravel-sms

或者,在 composer 中添加依赖

{
  "require": {
    "parsilver/laravel-sms": "^1.0"
  },
}

然后运行命令

php artisan vendor:publish --provider="Parsilver\SMS\SMSServiceProvider" --tag="config"

您将获得配置文件

/config/sms.php

短信服务提供商

目前我们只有 smartcomm 的服务,如果您想添加其他服务,可以发起 pull request

Smartcomm 提供商

更多信息请访问 Net-Innova

请在使用前安装 guzzlehttp

composer require guzzlehttp/guzzle
# .env
SMS_PROVIDER=smartcomm
SMS_SMARTCOMM_USERNAME=xxxxxx
SMS_SMARTCOMM_PASSWORD=xxxxxx

Null 提供商

完全不发送短信

# .env
SMS_PROVIDER=null

基本使用

您可以通过 SMS 类发送短信,或者通过 DI 方法,以下示例中我们在 Controller 中实现了 DI

<?php

\SMS::send('0899991111', 'This is message');

以下是我们需要导入的类以使用它

<?php
use Parsilver\SMS\Contract\SMSProvider;
<?php

use App\Http\Controllers\Controller;
use Parsilver\SMS\Contract\SMSProvider;

class UserController extends Controller
{
    /**
    * @var SMSProvider 
     */
    private $sms;
    
    public function __construct(SMSProvider $sms) 
    {
        $this->sms = $sms;
    }
    
    public function handle()
    {
        //...
        $this->sms->send('0999999999', 'This is message');
        //...
    }
}

创建自己的提供商

有时您可能已经有自己的服务提供商,但想要进行自定义,可以这样做

<?php App\SMS;

use Parsilver\SMS\Provider\AbstractSMSProvider;

class MyProvider extends AbstractSMSProvider
{
    /**
     * @param string $phoneNumber
     * @param string $message
     */
    public function send($phoneNumber, $message)
    {
        // Process your provider here...
    }
}

然后,在 app\Providers\AppServiceProvider.php 中进行注册

<?php namespace App\Providers;

use Parsilver\SMS\Facade\SMS;

class AppServiceProvider extends ServiceProvider
{
    //....
    
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        SMS::extend('myProvider', function() {
            return new MyProvider();
        });
    }
}

并开始使用

\SMS::driver('myProvider')->send('0999999999', 'This is message');

PHPUnit 测试

您可以通过更改服务提供商进行测试

<?php 
use Parsilver\SMS\Facade\SMS;

SMS::fake();

例如

<?php

namespace Tests\Feature;

use Tests\TestCase;
use Parsilver\SMS\Facade\SMS;

class ExampleTest extends TestCase
{
    
    public function testShouldSuccess()
    {
        // Set SMS Provider to Fake SMS
        SMS::fake();
        
        $phoneNumber = '0989999999';
        $message = 'This is message';
        
        // Try to send
        SMS::send($phoneNumber, $message);
        
        // Assert
        SMS::assertSent($phoneNumber, $message);
    }
}

贡献

如果您想在此 repository 中进一步开发,请按照以下说明操作

更多信息请访问 CONTRIBUTING.md