首页> 实战笔录 >PHP开发笔记 >Hyperf Hyperf
Hyperf3.1实现国内短信发送(多平台集合包)
作者:小萝卜 2025-04-05 【 PHP Hyperf 功能 短信 】 浏览 83
简介支持目前市面多家服务商,一套写法兼容所有平台,简单配置即可灵活增减服务商,内置多种服务商轮询策略、支持自定义轮询策略,统一的返回值格式,便于日志与监控,自动轮询选择可用的服务商,更多等你去发现与改进...
文档地址:前往查看
安装:
composer require xyzj91/hyperf-sms
php bin/hyperf.php vendor:publish xyzj91/hyperf-sms
在config/autoload/sms.php中定义配置
return [
// HTTP 请求的超时时间(秒)
'timeout' => 5.0,
// 默认发送配置
'default' => [
// 网关调用策略,默认:顺序调用
'strategy' => \HyperfLibraries\Sms\Strategy\OrderStrategy::class,
// 默认可用的发送网关
'gateways' => [
'aliyun',
],
],
// 可用的网关配置
'gateways' => [
//阿里云
'aliyun' => [
'access_key_id' => '',
'access_key_secret' => '',
'sign_name' => '',
],
//阿里云国际
'alibaba' => [
'access_key_id' => '',
'access_key_secret' => '',
],
//聚合数据
'juhe' => [
'app_key' => '',
],
//华为云 SMS
'huawei' => [
'endpoint' => '', // APP接入地址
'app_key' => '', // APP KEY
'app_secret' => '', // APP SECRET
'from' => [
'default' => '1069012345', // 默认使用签名通道号
'custom' => 'csms12345', // 其他签名通道号 可以在 data 中定义 from 来指定
'abc' => 'csms67890', // 其他签名通道号
...
],
'callback' => '' // 短信状态回调地址
],
...
],
];
代码:
declare(strict_types=1);
namespace App\Repository\Remote;
use App\Repository\crm\CountryRepository;
use App\Repository\crm\MsgLogRepository;
use Hyperf\AsyncQueue\Annotation\AsyncQueueMessage;
use Hyperf\Collection\Arr;
use HyperfLibraries\Sms\Contract\SmsInterface;
use HyperfLibraries\Sms\PhoneNumber;
class SmsRepository
{
/**
* @var SmsInterface
*/
public $sms;
public function __construct(SmsInterface $sms, public $platform = 'aliyun')
{
$this->sms = $sms;
}
#[AsyncQueueMessage(pool: 'fast')]
public function _sendMobile($mobile = '', $title = '', $content = [], $sms_arr = [] )
{
if (empty($mobile)) {
logger('msg')->info('短信发送失败,手机号为空');
return false;
}
$mobile = new PhoneNumber($mobile, $phone_code);
$data['phone'] = $mobile;
//发送国内短信
try {
$result = $this->sms->send($mobile, [
'content' => $param['content'], // 短信内容
'template' => $param['template'], // 模板ID
'data' => [
'code' => $sms_arr['param']['code'], // 验证码
],
], [$this->platform]);
$res = ['res_code' => 'ok'];
} catch (\Exception $e) {
$res = ['res_code' => 'error', 'message' => $e->getException($this->platform)->getMessage()];
//var_dump($e->getException($this->platform)->getMessage());
}
}
if(Arr::get($res,'res_code')=='ok'){
// 插入短信发送记录
MsgLogRepository::instance()->updateOrCreateMsgLog($data);
}else{
logger('msg')->info('短信发送失败,收信人地址为:' . $mobile . ',错误信息为:' . $res['message']);
$data['status'] = 0;
$data['error_info'] = $res['message'];
// 插入短信发送失败记录
MsgLogRepository::instance()->updateOrCreateMsgLog($data);
}
}
很赞哦! (0)