引入短信包
集成短信都是一样的,找到合适的短信接口提供商,然后对接他们的接口。我这次的项目因为主要是面向国外客户,所以用了vonage的短信接口。
首先引用包到Laravel项目中,如果失败的话,composer update看看是什么错误,一般是php.ini的配置限制了内存大小。
引用:composer require vonage/client
当这个包引入到项目中后就可以写接口调用了。
接口代码:
<?php
namespace App\Lib\Sms;
class Vonage {
static private $_un = '****'; //账号
static private $_pw = '****'; //密码
/* ========== 业务模块 ========== */
public function send($phone,$code){
$basic = new \Vonage\Client\Credentials\Basic($this::$_un, $this::$_pw);
$client = new \Vonage\Client($basic);
// $client = new \Vonage\Client($basic, ['base_rest_url' => 'https://rest.nexmocn.com']);
$response = $client->sms()->send(
new \Vonage\SMS\Message\SMS($phone, 'JCZN', '您的短信验证码为:'.$code)
);
$message = $response->current();
return $message;
}
}
其他文件调用接口代码的方法:
public function sendMobileCode()
{
$data = $this->request->input();
$code= rand(1000,9999);
// todo 发送短信
$sms = new \App\Lib\Sms\vonage();
$res = $sms->send($data['phone'],$code);
if ($res->getStatus()==0){
\App\Lib\AjaxApp\Result::OutPut(1, '100001',$res->getMessageId(),'验证码发送成功');
}else{
\App\Lib\AjaxApp\Result::OutPut(0, '100002',$res->getMessageId(),'验证码发送失败');
}
}
这个是精简的代码,其他限制可以在方法里慢慢添加,例如这个发送短信是合着注册或者找回密码用的,收集这个手机号的发送次数,IP地址的发送限制,短时间多次发送限制等等。