1,安装阿里大于服务
composer require iscms/alisms-for-laravel
2,注册服务(config/app.php)
iscms/Alisms/AlidayuServiceProvider::class
3,生成阿里大于(鱼)配置文件(config文件夹)
php artisan vendor:publish
4,修改阿里大于(鱼)配置文件(alisms.php)文件为:
<?php
return [
'KEY' =>env('ALISMS_KEY',null),
'SECRETKEY'=>env('ALISMS_SECRETKEY',null)
];
5,laravel根目录下找到.env文件
ALISMS_KEY=234*****3
ALISMS_SECRETKEY=****************
控制器里写方法:
use App\Api\BaseController;
use Dingo\Api\Http\Request;
use Illuminate\Support\Facades\Validator;
use iscms\Alisms\SendsmsPusher as Sms;
class CommonController extends BaseController {
public function sendVerifyMessage(Request $request, Sms $sms)
{
$inputData = $request->only(['phone']);
$validator = Validator::make($request->all(), [ 'phone' => 'required|regex:/^1[34578][0-9]{9}$/', ]);
if ($validator->fails())
{
return response()->json([ 'errcode' => -4001, 'msg' => 'Param error', 'data' => $validator->errors(), ]);
} // 已发送未过期不再发送短信验证码
if (get_phone_verify_code($inputData['phone']))
{
xlogger('info', 'request phone number:'.$inputData['phone'], 'sys');
return response()->json([ 'errcode' => '-4001', 'msg' => 'msg already send', ]);
}
$verifycode = random_num_generator(4);
$content = json_encode([ 'code' => $verifycode ]);
$result=$sms->send($inputData['phone'],'上信科技', $content,"SMS_55110001");
set_phone_verify_code($inputData['phone'], $verifycode);
xlogger('info', 'send phone verify code for '.$inputData['phone']. " ---> result: ".json_encode($result));
return response()->json($result);
}
}
公共方法里面:
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
if (!function_exists('get_phone_verify_code'))
{
/** * 获取存储的验证码
* * @param $phone
* * @return mixed
* * @throws Exception
*/
function get_phone_verify_code($phone)
{
if (strlen($phone) != 11)
{
throw new Exception('Param error: param length must 11');
}
return Cache::get('verifycode:'.$phone, false);
}
}
if (!function_exists('set_phone_verify_code'))
{ /** * 存储验证码
* @param string $phone 手机号
* @param int $expire 单位minute
*/
function set_phone_verify_code($phone, $expire = 1)
{
Cache::put('verifycode:'.$phone, $expire);
}
}
if (!function_exists('random_num_generator'))
{ /** * 生成指定数量的随机数字符串
* @param $length
* @return string
* @throws Exception
*/
function random_num_generator($length)
{
if (!is_int($length)) {
throw new Exception('Type error: param need ini');
} $numbers = [ 0,1,2,3,4,5,6,7,8,9 ];
$result = ""; for ($i = 0; $i < $length; $i++)
{
$result.=$numbers[rand(0, 9)];
}
return $result;
}
}