12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- <?php
- namespace plugin\ali_sms\service;
- use AlibabaCloud\Client\AlibabaCloud;
- use AlibabaCloud\Client\Exception\ClientException;
- use AlibabaCloud\Client\Exception\ServerException;
- use app\service\ConfServiceFacade;
- use laytp\traits\Error;
- class AliSms
- {
- use Error;
- //发送手机短信
- public function send($mobile, $event, $templateParam){
- try {
- AlibabaCloud::accessKeyClient(ConfServiceFacade::get('plugin.ali_sms.accessKeyId'), ConfServiceFacade::get('plugin.ali_sms.accessKeySecret'))
- ->regionId('cn-hangzhou')
- ->asDefaultClient();
- $mobile_msg_template = ConfServiceFacade::get('plugin.ali_sms.template');
- $result = AlibabaCloud::rpc()
- ->product('Dysmsapi')
- // ->scheme('https') // https | http
- ->version('2017-05-25')
- ->action('SendSms')
- ->method('POST')
- ->host('dysmsapi.aliyuncs.com')
- ->options([
- 'query' => [
- 'RegionId' => "cn-hangzhou",
- 'PhoneNumbers' => $mobile,
- 'SignName' => ConfServiceFacade::get('plugin.ali_sms.sign'),
- 'TemplateCode' => $mobile_msg_template[$event],
- 'TemplateParam' => json_encode($templateParam, JSON_UNESCAPED_UNICODE),
- ],
- ])
- ->request()->toArray();
- if($result['Code'] == 'OK'){
- //插入短信表
- $data = [
- 'template_code' => $mobile_msg_template[$event],
- 'event' => $event,
- 'mobile' => $mobile,
- 'expire_time' => ConfServiceFacade::get('plugin.ali_sms.expireTime') ? time() + ConfServiceFacade::get('plugin.ali_sms.expireTime') : 0,
- 'params' => json_encode($templateParam, JSON_UNESCAPED_UNICODE),
- ];
- \plugin\ali_sms\model\AliSms::create($data);
- return true;
- }else{
- $this->setError($result['Message']);
- return false;
- }
- } catch (ClientException $e) {
- $this->setError($e->getErrorMessage());
- return false;
- } catch (ServerException $e) {
- $this->setError($e->getErrorMessage());
- return false;
- }
- }
- //检测验证码
- public function checkCode($mobile, $event, $code){
- if(!env('APP_DEBUG')) {
- $message = \plugin\ali_sms\model\AliSms::where([['mobile', '=', $mobile], ['event', '=', $event], ['params', '=', json_encode(['code' => $code], JSON_UNESCAPED_UNICODE)]])->find();
- if (!$message) {
- $this->setError('验证码错误');
- return false;
- }
- if ($message->status == 2) {
- $this->setError('验证码已使用');
- return false;
- }
- if ($message->status == 3) {
- $this->setError('验证码已过期');
- return false;
- }
- if ($message->expire_time && $message->expire_time < time()) {
- \plugin\ali_sms\model\AliSms::where('id', '=', $message->id)->update(['status' => 3]);
- $this->setError('验证码已过期');
- return false;
- }
- \plugin\ali_sms\model\AliSms::where('id', '=', $message->id)->update(['status' => 2]);
- }
- return true;
- }
- }
|