package com.jsh.erp.service.sms.impl; import com.jsh.erp.service.redis.RedisUtil; import com.jsh.erp.service.sms.SmsService; import lombok.extern.slf4j.Slf4j; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.util.Random; @Service @Slf4j public class SmsServiceImpl implements SmsService { private final RedisUtil redisUtil; private final String accessKey; private final String secretKey; private final String region; private final String signName; private final String templateId; public SmsServiceImpl(RedisUtil redisUtil, @Value("${volc.sms.access-key}") String accessKey, @Value("${volc.sms.secret-key}") String secretKey, @Value("${volc.sms.region}") String region, @Value("${volc.sms.sign-name}") String signName, @Value("${volc.sms.template-id}") String templateId) { this.redisUtil = redisUtil; this.accessKey = accessKey; this.secretKey = secretKey; this.region = region; this.signName = signName; this.templateId = templateId; } @Override public boolean sendCode(String phone) { //测试生成固定的凑得 String code = "888888"; redisUtil.setCode(phone, code); return true; // // 生成6位随机验证码 // String code = String.format("%06d", new Random().nextInt(999999)); // // // 存储到Redis // redisUtil.setCode(phone, code); // // // 构造火山云请求 // try { // // 使用火山云短信API(示例为简化版,需根据官方文档调整) // String url = "https://sms.volcengineapi.com/v2/send"; // String jsonBody = String.format("{\"phone\":\"%s\",\"sign_name\":\"%s\",\"template_id\":\"%s\",\"template_param\":\"{\\\"code\\\":\\\"%s\\\"}\"}", phone, signName, templateId, code); // // // 生成签名(需按火山云签名算法实现) // String signature = generateVolcSignature(accessKey, secretKey); // // // 发送HTTP请求 // CloseableHttpClient client = HttpClients.createDefault(); // HttpPost httpPost = new HttpPost(url); // httpPost.setHeader("Content-Type", "application/json"); // httpPost.setHeader("Authorization", "HMAC-SHA256 Credential=" + accessKey + ",Signature=" + signature); // httpPost.setEntity(new StringEntity(jsonBody)); // // CloseableHttpResponse response = client.execute(httpPost); // return response.getStatusLine().getStatusCode() == 200; // } catch (Exception e) { // log.error("短信发送失败: {}", e.getMessage()); // return false; // } } @Override public boolean verifyCode(String phone, String code) { String storedCode = redisUtil.getCode(phone); return code != null && code.equals(storedCode); } // 火山云签名生成方法(需根据官方文档实现) private String generateVolcSignature(String accessKey, String secretKey) { // 实际需按火山云签名算法生成(示例简化) return "generated_signature"; } }