Android开发:发送验证码验证手机号——榛子云短信服务

榛子云短信官网

在这里插入图片描述
在这里插入图片描述
点击注册后进行登录 页面如下图所示很是简洁,也省去了很多复杂的流程

在这里插入图片描述
需要进行充值
在这里插入图片描述
价格相对公道,个人开发测试完全够用

我的应用中有后续开发要用到的AppIdAppSecret
在这里插入图片描述

短信模板中可以根据个人需要进行编辑但是要进行审核
后续开发中需要用到模版的ID
在这里插入图片描述

在官网的开发文档中有SDK开发文档在这里插入图片描述


一、在Spring boot工程中创建一个发送验证码的API

1.创建一个新的Maven 模块

在这里插入图片描述

2.引入相关依赖

在这里插入图片描述

3.编写配置文件

server:
  port: 8223
spring:
  profiles:
    active: dev
  application:
    name: service-sms
#    redis数据库配置
  redis:
    host: 127.0.0.1
    port: 6379
    timeout: 3000ms
    lettuce:
      pool:
        max-idle: 5
        min-idle: 0
#        nacos配置
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 # nacos服务地址
#        远程服务调用
feign:
  client:
    config:
      default:
        connectTimeout: 10000  #连接超时配置
        readTimeout: 600000   #执行超时配置
   #    如果想要使用配置文件进行 榛子云配置 可以像下方这样
zhenziyun:
  sms:
     file:
        apiUrl: 你的apiUrl
        appId: 你的appId
        appSecret: 你的appSecret
        templateId: 你的短信模版

4.创建启动类以及添加随机数生成工具类

@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
@EnableFeignClients
@ComponentScan("com.ts")
public class SmsApplication {
    public static void main(String[] args) {
        SpringApplication.run(SmsApplication.class,args);
    }

}
public class RandomUtils {

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

5.Controller层

@RestController
@RequestMapping("/lxb/sms")
@Api(tags = "短信管理")
@CrossOrigin
public class ApiSmsController {
    @Resource
    private SmsService smsService;

    

    @Resource
    RedisTemplate redisTemplate;


    @ApiOperation("获取验证码")
    @GetMapping("/send/{mobile}")
    public Map<String,Object> SmsSend(
            @ApiParam(value = "手机号",required = true)
            @PathVariable String mobile
    ){
        //判断手机号是否已经被注册
        //Map<String, Object> byMobile = smsClient.getByMobile(mobile);
        //boolean b= (boolean) byMobile.get("data");
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();


       // if(!b){
//            1.生成随机数
            String fourBitRandom = RandomUtils.getFourBitRandom();
            smsService.sendMessage(mobile,fourBitRandom);
            redisTemplate.opsForValue().set("lxb:sms:code:"+mobile,fourBitRandom,5, TimeUnit.MINUTES);
            stringObjectHashMap.put("code",0);
            stringObjectHashMap.put("message","短信发送成功");


       // }
       // else
       // {
        //    stringObjectHashMap.put("code",404);
       //     stringObjectHashMap.put("message","短信发送失败");
            //该手机号已经被认证过
       // }


        return stringObjectHashMap;

    }


}

6.Service层

public interface SmsService {
    void sendMessage(String mobile, String fourBitRandom);
}

7.Impl实现类以及从配置文件中获取Secret、Id、模版Id的工具类

@Service
public class SmsServiceImpl implements SmsService {
    @Override
    public void sendMessage(String mobile, String fourBitRandom) {
        ZhenziSmsClient client=new ZhenziSmsClient(SmsUtils.API_URL,SmsUtils.APP_ID,SmsUtils.APP_SECRET);
        HashMap<String, Object> map = new HashMap<>();
        map.put("templateId","12812");
        map.put("number",mobile);

        String[] templateParams=new String[2];
        templateParams[0]=fourBitRandom;
        templateParams[1]="3";
        map.put("templateParams",templateParams);
        try {
            String result = client.send(map);
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
package com.ts.oss.util;

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

@Component
public class SmsUtils implements InitializingBean {

    @Value("${zhenziyun.sms.file.apiUrl}")
    private String apiUrl;
    @Value("${zhenziyun.sms.file.appId}")
    private String appId;
    @Value("${zhenziyun.sms.file.appSecret}")
    private String appSecret;
    @Value("${zhenziyun.sms.file.templateId}")
    private String templateId;


    //定义公开静态常量 供其他方法使用
    public static String API_URL;
    public static String APP_ID;
    public static String APP_SECRET;
    public static String TEMPLATED_ID;
    @Override
    public void afterPropertiesSet() throws Exception {
        API_URL=apiUrl;
        APP_ID=appId;
        APP_SECRET=appSecret;
        TEMPLATED_ID=templateId;
    }
}


提示:以下是本篇文章正文内容

二、Android 通过网络请求调用API实现验证码的发送?

1.权限的配置

<uses-permission android:name="android.permission.INTERNET" />

2.依赖的导入

implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.squareup.okhttp3:okhttp:4.4.1'

3.Xml文件的编写(UI界面的绘制)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <EditText
android:hint="请输入手机号"
        android:id="@+id/mobile"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <Button
        android:layout_gravity="center"
        android:id="@+id/sendMessage"

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="发送验证码"
        tools:ignore="MissingConstraints" />

</LinearLayout>

4.Activity方法的代码

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button button;
    private EditText editText;
    
    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText=findViewById(R.id.mobile);
        button=findViewById(R.id.sendMessage);

        button.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.sendMessage:
                String phonenumber=editText.getText().toString();
                //发送验证码
                OkHttpClient client= new OkHttpClient();//创建HTTP客户端
                String Url="http://你的IPv4地址:服务的端口号/lxb/sms/send"+"/"+phonenumber;
                Request request=new Request.Builder()
                        .url(Url)
                        .build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        e.printStackTrace();

                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getBaseContext(),"验证码发送成功",Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                });
        }
    }

三、实现效果图

在这里插入图片描述
在这里插入图片描述

  • 25
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot可以很容易地集成短信验证码功能。首先,你需要创建一个Spring Boot项目,并配置好基本环境。然后,你可以根据需要选择一个短信服务提供商。一些常见的选择包括阿里、腾讯片等。你可以根据自己的需求和预算选择适合的服务商。 在项目中,你需要配置短信服务的相关参数,比如API地址、应用ID和应用密钥等。这些参数可以在你选择的短信服务提供商的官方文档中找到。你可以将这些参数配置在项目的配置文件中,比如application.yaml文件中。 接下来,你需要编写代码来实现发送短信验证码的功能。你可以创建一个短信服务的工具类,其中包含发送短信验证码的方法。在这个方法中,你可以使用短信服务提供商提供的API来发送短信验证码。你可以根据需要自定义验证码的长度和过期时间等。 最后,你可以在需要发送短信验证码的地方调用这个工具类的方法,比如在用户注册、登录或进行交易确认等操作中。通过发送短信验证码,你可以再次确认用户的身份和意愿,增加交易的安全性和可靠性。同时,你也可以根据业务需求对验证码进行验证和处理。 总结起来,Spring Boot集成短信验证码功能的步骤包括创建项目、选择短信服务提供商、配置参数、编写发送短信验证码的代码和调用发送方法。通过这些步骤,你可以实现一个简单而优雅的短信验证码功能。\[1\]\[2\]\[3\] #### 引用[.reference_title] - *1* [Spring Boot优雅集成发送短信验证码登录(超详细,附源码)](https://blog.csdn.net/weixin_43691942/article/details/103393091)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [SpringBoot集成手机验证码业务(榛子短信服务)](https://blog.csdn.net/m0_66884848/article/details/123473438)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值