• 注册
  • thinkphp6 关注:2 内容:16

    ThinkPHP5.1接入阿里云短信验证码

  • 查看作者
  • 打赏作者
  • 拉黑名单
    • 1composer安装阿里云短信SDK

      composer  require  alibabacloud/clien

      2 配置信息写入config/app.php中

       //阿里云短信配置
          'aliyunsms'=>[
              'AccesKeyId'=>'LTAIia9oCz8Ac80E',
              'AccessKeySecret'=>'6MCtr5X1Dssqh4hfJTKULGUXATqHn1',
              'SignName'=>'万金速达',
              'SMS_ID'=>'SMS_144165271'
          ]

      3 短信发送方法写在公共文件 common.php中

      // 应用公共文件
      use AlibabaCloud\Client\AlibabaCloud;
      use AlibabaCloud\Client\Exception\ClientException;
      use AlibabaCloud\Client\Exception\ServerException;
      /**
       * 验证码(阿里云短信)
       */
      function smsVerify($mobile, $code, $tempId)
      {
          AlibabaCloud::accessKeyClient(config('app.aliyunsms.AccesKeyId'), config('app.aliyunsms.AccessKeySecret')) 
              ->regionId('cn-hangzhou') //replace regionId as you need(这个地方是发短信的节点,默认即可,或者换成你想要的)
              ->asGlobalClient();
          $data = [];
          try {
              $result = AlibabaCloud::rpcRequest()
                  ->product('Dysmsapi')
                  //->scheme('https') //https | http(如果域名是https,这里记得开启)
                  ->version('2017-05-25')
                  ->action('SendSms')
                  ->method('POST')
                  ->options([
                      'query'                 => [
                          'PhoneNumbers'      => $mobile,
                          'SignName'          => config('app.aliyunsms.SignName'),
                          'TemplateCode'      => $tempId,
                          'TemplateParam'     => json_encode(['code'=>$code]),
                      ],
                  ])
                  ->request();
              $res    = $result->toArray();
              if($res['Code'] == 'OK'){
                  $data['status'] = 1;
                  $data['info']   = $res['Message'];
              }else{
                  $data['status'] = 0;
                  $data['info']   = $res['Message'];
              }
              return $data;
          } catch (ClientException $e) {
              $data['status'] = 0;
              $data['info']   = $e->getErrorMessage();
              return $data;
          } catch (ServerException $e) {
              $data['status'] = 0;
              $data['info']   = $e->getErrorMessage();
              return $data;
          }
      }

      4.发送短信

      $model = '18888888888';
      $code = rand(1000,9999);//这里是随机生成4位数字,这个方法是我自己写的哦,要注意!
      $res    = smsVerify($model, $code, config('app.aliyunsms.SMS_ID'));
      if($res['status'] == 1){
          echo '验证码发送成功';
      }else{
          echo '验证码发送失败';
      }

      你需要登录,才能进行发帖操作
    • 单栏布局 帖子间隔 侧栏位置: