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;
}
}