阿里云对接短信

可以先去bibi看教程:下面是bibi教学视频

【狂神说】通俗易懂的阿里云短信业务实战教程_哔哩哔哩_bilibili

1: 我们需要在pom 引入一个jar包

<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>aliyun-java-sdk-core</artifactId>
  <version>4.0.3</version>
</dependency>

 2:下面是工具类

package com.yunze.common.constant;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.yunze.common.sms.SemdSms;
import org.springframework.stereotype.Service;

import java.util.Map;
/**
 * 阿里云 短信发送配置
 * */

@Service
public class SendSmsImpl implements SemdSms {


    @Override
    public boolean send(String phoneNum, String templateCode, Map<String, Object> code) {

        /**
         * regionID @cn-hangzhou
         * 阿里云短信服务账号 @accessKeyId
         * 阿里云短信服务密码 @secret
         * */

        // 链接阿里云  这个不需要动 cn-hangzhou  accessKeyId : 账号  secret: 密码
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou","xxxxxx","xxxxx");
        IAcsClient client = new DefaultAcsClient(profile);

        // 构建请求
        CommonRequest request = new CommonRequest();

        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");//官方说不要动
        request.setVersion("2017-05-25");//官方说不要动
        request.setAction("SendSms");//事件名称

        // 自定义的参数 (手机号,验证码,签名,模板!)
        request.putQueryParameter("PhoneNumbers",phoneNum);//手机号
        request.putQueryParameter("SignName","山东山东");//签名
        request.putQueryParameter("TemplateCode",templateCode);//模板CODE

        // 构建一个短信的验证码
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(code));

        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            return response.getHttpResponse().isSuccess();//成功
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }
}



下面说说这个阿里云的账号和密码 我的已经标记xxxx了

 1:登录阿里云平台  我们点击 AccessKey 管理

 2:进去之后提示  如何你没有然后自己去创建  --在这里提醒大家先看教学视频

 3:我们点击继续使用  然后我们就能看到自己的账号了  也就是 AccessKey ID

        密码在右边---操作  有个 查看 Secret 就可以看到我们的密码了。

 3:我们写个接口  去动态的实现数据

package com.yunze.common.sms;

import java.util.Map;

public interface SemdSms {
    public boolean send(String phoneNum, String templateCode, Map<String,Object> code);
}

 4:下面是我们的 Controller 层

package com.yunze.web.controller.common;

import com.yunze.common.core.redis.RedisCache;
import com.yunze.common.sms.SemdSms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin // 跨域支持
@RequestMapping
public class SmsApiController {

    @Autowired
    private SemdSms sendSms;

    @Resource
    private RedisCache redisCache;



    @GetMapping("/send/{phone}")
    public String code(@PathVariable String phone){
        int H = 24;
        // 调用发送方法
        Object code = redisCache.getCacheObject("login_"+phone);
        if (code!=null && code.toString().length()>0) { //不等于 空
            return "已存在,还没有过期";
        }

        StringBuilder builder = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            builder.append(random.nextInt(10));//实现验证码 6 位数字
        }
        // 生成验证码并存储到redis 中
        code = builder.toString();

        HashMap<String,Object> param = new HashMap<>();
        param.put("code",code);

        boolean isSend = sendSms.send(phone,"SMS_242220249",param);

        if(isSend){

            //设置 5 分钟过期
            redisCache.setCacheObject("login_"+phone, code, 5, TimeUnit.MINUTES);//设置5分钟过期
            return "验证成功 请查看手机验证码";

        }else {
            return "发送失败";
        }
    }
}

操作完毕 --------------------------------------

 下面操作你们可以不看   因为我是用的若依框架写的---其中也是遇到了  很多问题

// 手机号 登录
export function GetPhone(phone) {
  return request({
    url: '/send/'+phone,
    method: 'get'
  })
}

在 SecurityConfig.java 配置拦截

 前端还有一个拦截的地方  大家注意  在这个地方 大家可以看看

 

 我在这里总结以下我的问题

1:若依登录  Java 代码有个 token 验证 这边挺复杂的

大家请看 这篇文章 若依系统(Security)增加手机验证码登录

因为若依没有验证码是不让登录的

若依系统(Security)增加手机验证码登录 - 简书

 但是我写的 token 验证 跟这篇文章的不太一样 大家都看看

    /**
     * 短信登录验证
     * @param telephone 用户名
     * @param password 密码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String Massagelogin(String telephone, String password, String uuid)
    {
        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new SmsCodeAuthenticationToken(telephone));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(telephone, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(telephone, Constants.LOGIN_FAIL, e.getMessage()));
                throw new CustomException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(telephone, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUser());
        // 生成token
        return tokenService.createToken(loginUser);
    }

前端需要把数据放入到 token

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
阿里云短信对接需要以下步骤: 1. 在阿里云短信控制台中创建签名和模板,获取对应的签名和模板CODE。 2. 在阿里云控制台中获取 AccessKey ID 和 AccessKey Secret。 3. 在代码中调用阿里云短信 API,传入必要的参数,例如短信模板、签名、接收手机号等。 这里提供一个简单的 PHP 代码示例: ```php <?php require_once './aliyun-php-sdk-core/Config.php'; use Aliyun\Core\DefaultAcsClient; use Aliyun\Core\Profile\DefaultProfile; use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest; // 替换成自己的AccessKey信息 $accessKeyId = "your_accessKeyId"; $accessKeySecret = "your_accessKeySecret"; // 设置阿里云短信服务所在的Region,如华东1 $region = "cn-hangzhou"; // 替换成自己的短信签名和模板CODE $signName = "your_signName"; $templateCode = "your_templateCode"; // 发送短信的手机号码,支持多个手机号码,用英文逗号分隔 $phoneNumbers = "your_phoneNumbers"; // 短信模板中的变量替换JSON串,如验证码为:{"code":"123456"} $templateParam = "{\"code\":\"123456\"}"; // 初始化DefaultAcsClient实例并设置参数 $profile = DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret); DefaultProfile::addEndpoint("cn-hangzhou", "cn-hangzhou", "Sms", "sms.aliyuncs.com"); $client = new DefaultAcsClient($profile); $request = new SendSmsRequest(); // 设置请求参数 $request->setPhoneNumbers($phoneNumbers); $request->setSignName($signName); $request->setTemplateCode($templateCode); $request->setTemplateParam($templateParam); // 发送短信 $response = $client->getAcsResponse($request); // 输出结果 print_r($response); ?> ``` 注意,以上代码中需要替换成自己的 AccessKey ID、AccessKey Secret、短信签名、模板 CODE、手机号码、短信模板变量等信息。另外,阿里云短信服务需要收取一定的费用,请确保账户余额充足。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值