61e4d3ff2092231f7493a1795875b34a8ab54e32.svn-base 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. package com.iamberry.app.service;
  2. import static com.iamberry.app.config.ImberryConfig.INTER_SMS_KEY;
  3. import static com.iamberry.app.config.ImberryConfig.INTER_SMS_TEXT;
  4. import static com.iamberry.app.config.ImberryConfig.INTER_SMS_URL;
  5. import static com.iamberry.app.config.ImberryConfig.SMS_PASSWORD;
  6. import static com.iamberry.app.config.ImberryConfig.SMS_TEXT;
  7. import static com.iamberry.app.config.ImberryConfig.SMS_URL;
  8. import static com.iamberry.app.config.ImberryConfig.SMS_USERNAME;
  9. import java.text.MessageFormat;
  10. import java.util.ArrayList;
  11. import java.util.Date;
  12. import java.util.HashMap;
  13. import java.util.List;
  14. import java.util.Map;
  15. import net.sf.json.JSONObject;
  16. import org.apache.commons.lang3.StringUtils;
  17. import org.apache.http.HttpEntity;
  18. import org.apache.http.NameValuePair;
  19. import org.apache.http.client.entity.UrlEncodedFormEntity;
  20. import org.apache.http.client.methods.CloseableHttpResponse;
  21. import org.apache.http.client.methods.HttpPost;
  22. import org.apache.http.impl.client.CloseableHttpClient;
  23. import org.apache.http.impl.client.HttpClients;
  24. import org.apache.http.message.BasicNameValuePair;
  25. import org.apache.http.util.EntityUtils;
  26. import org.springframework.beans.factory.annotation.Autowired;
  27. import org.springframework.stereotype.Service;
  28. import com.iamberry.app.config.Response;
  29. import com.iamberry.app.config.ResponseHeader;
  30. import com.iamberry.app.core.entity.CodeValid;
  31. import com.iamberry.app.face.CodeService;
  32. import com.iamberry.app.mapper.CodeMapper;
  33. import com.iamberry.app.tool.util.Result;
  34. import com.iamberry.app.ulitity.Utility;
  35. import com.iamberry.wechat.tools.ResponseJson;
  36. import com.thoughtworks.xstream.XStream;
  37. import com.thoughtworks.xstream.io.xml.StaxDriver;
  38. /**
  39. * @company 深圳爱贝源科技有限公司
  40. * @website www.iamberry.com
  41. * @author 献
  42. * @tel 18271840547
  43. * @date 2016年11月1日
  44. * @explain 验证码业务实现类
  45. */
  46. @Service
  47. public class CodeServiceImpl implements CodeService {
  48. @Autowired
  49. private CodeMapper codeMapper;
  50. private static String ENCODING = "UTF-8";
  51. @Override
  52. public ResponseJson sendCode(String phone, int codeScenario) {
  53. // TODO Auto-generated method stub
  54. // 第一步,判断使用通道,如果是+86开头,优先使用国内通道,否则默认使用国外通道
  55. ResponseJson json = new ResponseJson();
  56. if (StringUtils.isEmpty(phone)) {
  57. json.setReturnCode(404);
  58. json.addResponseKeyValue("Phone Empty!");
  59. return json;
  60. }
  61. // 第二步,如果是国内,判断是否存在
  62. CodeValid codeValid = codeMapper.getLast(phone);
  63. Date now = new Date();
  64. // 通道是否是中国的
  65. boolean IS_CHANNEL_ZH = false;
  66. if (StringUtils.indexOf(phone, "+") != -1) {
  67. if (StringUtils.startsWith(phone, "+86")) {
  68. IS_CHANNEL_ZH = true;
  69. }
  70. } else {
  71. IS_CHANNEL_ZH = true;
  72. }
  73. // 判断通道
  74. if (IS_CHANNEL_ZH && codeValid != null) {
  75. // ** 切换通道需求:每次请求验证码,如果上一次验证码在一分钟以后,三分钟以内没有使用,那么切换通道 **//
  76. if (now.getTime() <= (codeValid.getCodeValidDate().getTime()) &&
  77. (now.getTime() - 60000) >= codeValid.getCodeSendDate().getTime() && codeValid.getCodeUse() == 2 && codeValid.getCodeScenario() == codeScenario) {
  78. // 如果等待三分钟后,那么切换通道,暂时不切换
  79. // IS_CHANNEL_ZH = false;
  80. }
  81. }
  82. // 获取验证码
  83. String code = Utility.getRandomCode(4);
  84. json = sendCMS(phone, code, IS_CHANNEL_ZH ? 1 : 2);
  85. if (json.getReturnCode() != 200) {
  86. json = sendCMS(phone, code, IS_CHANNEL_ZH ? 1 : 2);
  87. }
  88. // 保存发送记录
  89. codeValid = new CodeValid();
  90. codeValid.setCodeChannel(IS_CHANNEL_ZH ? 1 : 2);
  91. codeValid.setCodeMsg(json.getReturnMsg().get("returnMsg").toString());
  92. codeValid.setCodePhone(phone);
  93. codeValid.setCodeScenario(codeScenario);
  94. codeValid.setCodeSendDate(now);
  95. codeValid.setCodeValidDate(new Date(now.getTime() + 180000));
  96. codeValid.setCodeStatus(json.getReturnCode() == 200 ? 3 : 4);
  97. codeValid.setCodeUse(2);
  98. codeValid.setCodeValue(Integer.parseInt(code));
  99. codeMapper.save(codeValid);
  100. return json;
  101. }
  102. /**
  103. * @param phone 手机号码
  104. * @param code 短信验证码
  105. * @param channel 通道 1:主通道;2:备用通道(国外的电话通通使用此)
  106. * @return
  107. */
  108. private ResponseJson sendCMS(String phone, String code, int channel) {
  109. // 国内号码
  110. ResponseJson json = new ResponseJson();
  111. json.setReturnCode(500);
  112. String result = null;
  113. try {
  114. if (channel == 1) {
  115. // 使用主通道
  116. // result = sendZHCMS(phone, code);
  117. result = sendOtherCMS(phone, code);
  118. } else {
  119. // 使用备用通道
  120. result = sendOtherCMS(phone, code);
  121. }
  122. } catch (Exception e) {
  123. result = e.getMessage();
  124. }
  125. if (StringUtils.equals(result, "SUCCESS")) {
  126. json.setReturnCode(200);
  127. }
  128. json.addResponseKeyValue(result);
  129. return json;
  130. }
  131. private String sendOtherCMS(String phone, String code) {
  132. String text = MessageFormat.format(INTER_SMS_TEXT, code);
  133. String results = sendSms(text, phone);
  134. JSONObject json = JSONObject.fromObject(results);
  135. String resultcod = json.get("code").toString();
  136. if(resultcod.equals("0")){
  137. System.out.println("使用备用通道,发送验证码成功!" + code);
  138. return "SUCCESS";
  139. }else{
  140. System.out.println("使用备用通道,发送失败...!" + code);
  141. return results;
  142. }
  143. }
  144. public static String sendSms(String text, String mobile) {
  145. Map<String, String> params = new HashMap<String, String>();
  146. params.put("apikey", INTER_SMS_KEY);
  147. params.put("text", text);
  148. params.put("mobile", mobile);
  149. return post(INTER_SMS_URL, params);
  150. }
  151. /** 基于HttpClient 4.3的通用POST方法
  152. * @param url 提交的URL
  153. * @param paramsMap 提交<参数,值>Map
  154. * @return 提交响应
  155. */
  156. public static String post(String url, Map<String, String> paramsMap) {
  157. CloseableHttpClient client = HttpClients.createDefault();
  158. String responseText = "";
  159. CloseableHttpResponse response = null;
  160. try {
  161. HttpPost method = new HttpPost(url);
  162. if (paramsMap != null) {
  163. List<NameValuePair> paramList = new ArrayList<NameValuePair>();
  164. for (Map.Entry<String, String> param : paramsMap.entrySet()) {
  165. NameValuePair pair = new BasicNameValuePair(param.getKey(), param.getValue());
  166. paramList.add(pair);
  167. }
  168. method.setEntity(new UrlEncodedFormEntity(paramList, ENCODING));
  169. }
  170. response = client.execute(method);
  171. HttpEntity entity = response.getEntity();
  172. if (entity != null) {
  173. responseText = EntityUtils.toString(entity);
  174. }
  175. } catch (Exception e) {
  176. e.printStackTrace();
  177. } finally {
  178. try {
  179. response.close();
  180. } catch (Exception e) {
  181. e.printStackTrace();
  182. }
  183. }
  184. return responseText;
  185. }
  186. private String sendZHCMS(String phone, String code) throws Exception {
  187. CloseableHttpClient client = HttpClients.createDefault();
  188. Map<String, String> params = new HashMap<String, String>();
  189. CloseableHttpResponse response = null;
  190. params.put("username", SMS_USERNAME);
  191. params.put("password", SMS_PASSWORD);
  192. params.put("mobile", phone);
  193. params.put("content", MessageFormat.format(SMS_TEXT, code));
  194. HttpPost method = new HttpPost(SMS_URL);
  195. if (params != null) {
  196. List<NameValuePair> paramList = new ArrayList<NameValuePair>();
  197. for (Map.Entry<String, String> param : params.entrySet()) {
  198. NameValuePair pair = new BasicNameValuePair(param.getKey(), param.getValue());
  199. paramList.add(pair);
  200. }
  201. method.setEntity(new UrlEncodedFormEntity(paramList, "UTF-8"));
  202. }
  203. response = client.execute(method);
  204. HttpEntity entity = response.getEntity();
  205. if (entity != null) {
  206. String result = EntityUtils.toString(entity);
  207. XStream xs = new XStream(new StaxDriver());
  208. xs.alias("result", Result.class);
  209. Result object = (Result)xs.fromXML(result);
  210. response.close();
  211. if (0 == object.getResultcode()) {
  212. return "SUCCESS";
  213. } else {
  214. return object.getResultcode() + ":" + object.getErrordescription();
  215. }
  216. }
  217. return null;
  218. }
  219. @Override
  220. public ResponseJson validCode(String phone, String code, int codeScenario) {
  221. ResponseJson json = new ResponseJson();
  222. // 校验
  223. CodeValid codeValid = codeMapper.getLast(phone);
  224. if (codeValid == null) {
  225. // 操作有误
  226. json.setReturnCode(404);
  227. json.addResponseKeyValue("Wrong operation, No send record");
  228. return json;
  229. }
  230. Date now = new Date();
  231. if (now.getTime() >= codeValid.getCodeValidDate().getTime()) {
  232. // 验证码无效
  233. json.setReturnCode(403);
  234. json.addResponseKeyValue("Verification code is invalid");
  235. return json;
  236. }
  237. // 验证码是否使用 1:已经使用;2:未使用
  238. if (codeValid.getCodeUse().intValue() == 1) {
  239. // 验证码无效
  240. json.setReturnCode(402);
  241. json.addResponseKeyValue("Verification code has been used");
  242. return json;
  243. }
  244. // 必须 验证码正确,并且场景正确
  245. if (!(codeValid.getCodeValue() == (Integer.parseInt(code))
  246. && codeScenario == codeValid.getCodeScenario())) {
  247. // 验证码错误
  248. json.setReturnCode(405);
  249. json.addResponseKeyValue("Verification code error");
  250. return json;
  251. }
  252. // 只要校验成功,表示本次验证码已使用
  253. codeMapper.update(codeValid.getCodeId());
  254. json.setReturnCode(200);
  255. json.addResponseKeyValue("SUCCESS");
  256. return json;
  257. }
  258. /**
  259. * 放轰炸原则:
  260. * 1、每个手机号码,每60秒只能发送1次!
  261. * 2、每个手机号码,每小时只能发送三次!
  262. * 3、每个手机号码,每天只能发送10次!
  263. * @param phone
  264. * @return
  265. * @author 献
  266. * @Time 2016年12月5日
  267. */
  268. public Response interval(String phone) {
  269. CodeValid codeValid = codeMapper.getLast(phone);
  270. Date now = new Date();
  271. // 每个手机号,限制每60秒,只能发送一次
  272. if (codeValid != null && (60000 > (now.getTime() - codeValid.getCodeSendDate().getTime()))) {
  273. return new Response(new ResponseHeader(404, "每个手机号码,每60秒只能发送1次!", 0));
  274. }
  275. // 生成时间规则
  276. Date startDate = new Date();
  277. startDate.setMinutes(0);
  278. startDate.setSeconds(0);
  279. Date endDate = new Date();
  280. endDate.setMinutes(59);
  281. endDate.setSeconds(60);
  282. // 每个手机号码,每个小时最多3条
  283. if (codeMapper.getInterval(startDate, endDate, phone) >= 3) {
  284. return new Response(new ResponseHeader(404, "每个手机号码,每小时只能发送3次!", 0));
  285. }
  286. // 每个手机号码,每天最多10条
  287. endDate.setHours(23);
  288. startDate.setHours(0);
  289. if (codeMapper.getInterval(startDate, endDate, phone) >= 10) {
  290. return new Response(new ResponseHeader(404, "每个手机号码,每天只能发送10次!", 0));
  291. }
  292. return new Response(new ResponseHeader(200, "SUCCESS", 0));
  293. }
  294. }