阿里云短信服务(无需营业执照)快速上手

阿里云好像短信服务要营业执照

短信服务地址:

https://www.aliyun.com/product/sms?spm=5176.19720258.J_2686872250.9.775276f4077PYC&scm=20140722.M_5933522.P_197.MO_401-ID_5933522-MID_5933522-CID_20739-ST_3903-V_1

在这里插入图片描述

快速学习
在这里插入图片描述

1.绑定测试手机号码
(只能测试在这里面添加过的号码)

2.使用专用的测试模板(下面就有默认测试用例的内容)

3.点击 调用API发送短信

在这里插入图片描述

然后进入api测试页面

点击沙箱运行,开始用云服务器测试代码

在这里插入图片描述

等他编译,打包好之后按下回车

就会发送短信:

在这里插入图片描述

之后就收到短信

在这里插入图片描述

在这里复制依赖,然后代码复制到xml里

在这里插入图片描述
我这里的依赖是:

 <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>dysmsapi20170525</artifactId>
            <version>2.0.23</version>
        </dependency>

按照自己的风格来加到service里或者直接用我的

MsmService

package com.lkw.msmservice.service;

import java.util.Map;

public interface MsmService {
    
    

    boolean send(Map<String, Object> param, String phone) ;
}

MsmServiceImpl

package com.lkw.msmservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.lkw.msmservice.Utils.ConstantMsmUtil;
import com.lkw.msmservice.service.MsmService;
import com.lkw.servicebase.exceptionhandler.GuliException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

@Transactional
@Service
public class MsmServiceImpl implements MsmService {
    
    

    @Override
    public boolean send(Map<String, Object> param, String phone){
    
    
        try {
    
    
            //创建客户端
            Client client = new Client(new Config()
                    .setEndpoint("dysmsapi.aliyuncs.com")
                    .setAccessKeyId(ConstantMsmUtil.ACCESS_KEY_ID)
                    .setAccessKeySecret(ConstantMsmUtil.ACCESS_KEY_SECRET));

            //创建请求
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setSignName("阿里云短信测试")
                    .setTemplateCode("SMS_154950909")
                    .setPhoneNumbers(phone)
                    .setTemplateParam(JSONObject.toJSONString(param));

            //查看客户端
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            //输出打印信息
            //System.out.println(sendSmsResponse.getBody().getMessage());
        } catch (Exception e) {
    
    
            throw new GuliException();
        }
        return true;
    }
}

获取yml里的阿里云配置用的
ConstantMsmUtil

package com.lkw.msmservice.Utils;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class ConstantMsmUtil implements InitializingBean {
    
    


    @Value("${aliyun.sms.keyid}")
    private String keyid;

    @Value("${aliyun.sms.keysecret}")
    private String keysecret;

    public static String ACCESS_KEY_SECRET;
    public static String ACCESS_KEY_ID;


    @Override
    public void afterPropertiesSet() throws Exception {
    
    
        ACCESS_KEY_ID = keyid;
        ACCESS_KEY_SECRET = keysecret;

    }
}

//控制层
MsmController

package com.lkw.msmservice.controller;

import com.lkw.cmsservice.commonutils.R;
import com.lkw.cmsservice.commonutils.RandomUtil;
import com.lkw.msmservice.service.MsmService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;


@CrossOrigin
@RestController
@RequestMapping("/edumsm/msm")
public class MsmController {
    
    

    @Autowired
    private MsmService msmService;

    @GetMapping("send/{phone}")
    public R sendMsm(@PathVariable String phone){
    
    
        String code ;
        //2、如果redis获取不到,进行阿里云发送

        //生成随机数,传递阿里云进行发送
        code = RandomUtil.getFourBitRandom();
        Map<String, Object> param = new HashMap<>();
        param.put("code",code);
        //调用service的方法,发送
        boolean isSend = msmService.send(param,phone);
        if (isSend) {
    
    
            //阿里云发送成功,把发送成功的验证码放入redis缓存中
            //设置有效时间
            //redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok();
        }else
            return R.error().message("短信发送失败");
    }
}

yml
只展示本文有用配置的在



aliyun:
  sms:
    keyid: LTAI5tS6amFwgFinXXU9KMst
    keysecret: 9lJ2OsiEvYBeIXLQErVMNQMhDQQKgA

获取随机验证码的工具类

RandomUtil

package com.lkw.cmsservice.commonutils;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

/**
 * 获取随机数
 * 
 * @author qianyi
 *
 */
public class RandomUtil {
    
    

   private static final Random random = new Random();

   private static final DecimalFormat fourdf = new DecimalFormat("0000");

   private static final DecimalFormat sixdf = new DecimalFormat("000000");

   public static String getFourBitRandom() {
    
    
      return fourdf.format(random.nextInt(10000));
   }

   public static String getSixBitRandom() {
    
    
      return sixdf.format(random.nextInt(1000000));
   }

   /**
    * 给定数组,抽取n个数据
    * @param list
    * @param n
    * @return
    */
   public static ArrayList getRandom(List list, int n) {
    
    

      Random random = new Random();

      HashMap<Object, Object> hashMap = new HashMap<Object, Object>();

      // 生成随机数字并存入HashMap
      for (int i = 0; i < list.size(); i++) {
    
    

         int number = random.nextInt(100) + 1;

         hashMap.put(number, i);
      }

      // 从HashMap导入数组
      Object[] robjs = hashMap.values().toArray();

      ArrayList r = new ArrayList();

      // 遍历数组并打印数据
      for (int i = 0; i < n; i++) {
    
    
         r.add(list.get((int) robjs[i]));
         System.out.print(list.get((int) robjs[i]) + "\t");
      }
      System.out.print("\n");
      return r;
   }
}

猜你喜欢

转载自blog.csdn.net/m0_52070517/article/details/128190254