概述
记录下。
package com.fh.controller.app.other;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.fh.controller.base.BaseController;
import com.fh.service.aist.member.impl.AistMemberInfoServiceImpl;
import com.fh.util.PageData;
import com.fh.util.Ret;
import com.fh.util.Sms;
import com.fh.util.Tools;
import com.fh.util.jwt.JWTUtils;
@Controller
@RequestMapping(value = "/app")
public class LoginController extends BaseController {
private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);
@Resource(name = "aistMemberInfoServiceImpl")
private AistMemberInfoServiceImpl aistMemberInfoServiceImpl;
/**
* 小程序登录接口
*
*/
@ResponseBody
@RequestMapping(value = "/login")
public Object login(HttpServletRequest request, @RequestParam(value = "phone") String phone,
@RequestParam(value = "code") String code) {
if (!Tools.isPhoneRight(phone)) {
return Ret.fail("手机号格式错误").build();
}
if (!Sms.isCorrectCode(code, phone, request)) {
return Ret.fail("手机验证码错误").build();
}
try {
PageData pd = new PageData();
pd.put("phone", phone);
PageData memberInfo = aistMemberInfoServiceImpl.findByParam(pd);
if (memberInfo != null) {
LOGGER.info("登录成功,id:", pd.get("id"));
return Ret.ok("登录成功")
.put(JWTUtils.getXAccessToken(), JWTUtils.createToken(String.valueOf(pd.get("id")))).build();
}
/*PageData newMemberInfo = new PageData();
newMemberInfo.put("id", value);
newMemberInfo.put("status", value);
newMemberInfo.put("type", value);
newMemberInfo.put("id", value);
aistMemberInfoServiceImpl.save(newMemberInfo);
LOGGER.info("注册并登录成功,id:", newMemberInfo.get("id"));
return Ret.ok("登录成功").put(JWTUtils.getXAccessToken(), JWTUtils.createToken(String.valueOf(pd.get("id"))))
.build();*/
LOGGER.info("登录失败,库中未存在该手机号账户");
return Ret.fail("登录失败,库中未存在该手机号账户").build();
} catch (Exception e) {
e.printStackTrace();
LOGGER.error("登录失败", e);
return Ret.fail("登录失败").build();
}
}
/**
* 小程序登录接口
*
*/
@ResponseBody
@RequestMapping(value = "/getSmsCode")
public Ret getSmsCode(String phone) {
if (!Tools.isPhoneRight(phone)) {
return (Ret.fail("手机号格式错误").build());
}
String token = Sms.sendSms(phone);
if (token != null) {
return Ret.ok("成功发送验证码").put(JWTUtils.getX3RedsessionToken(), token).build();
} else {
return Ret.fail("同一手机号验证码短信发送超出5条").build();
}
}
}
发送和判断验证码 接口
package com.fh.util;
import io.jsonwebtoken.Claims;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fh.util.jwt.JWTUtils;
/**
* -短信验证码
*
* @author Xie Licheng
* @date 2019年8月14日
*/
public class Sms {
private static final Logger LOGGER = LoggerFactory.getLogger(Sms.class);
private static final String POST_URL = "***************";
private static final String ACCOUNT = "***********";
private static final String PASSWORD = "****************";
public static String sendSms(String phone) {
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(POST_URL);
client.getParams().setContentCharset("GBK");
method.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=GBK");
String mobile_code = String.valueOf(Tools.getRandomNum());
String content = "您的验证码是:" + mobile_code + "。请不要把验证码泄露给其他人。";
NameValuePair[] data =
{new NameValuePair("account", ACCOUNT), new NameValuePair("password", PASSWORD),
new NameValuePair("mobile", phone), new NameValuePair("content", content),};
method.setRequestBody(data);
try {
client.executeMethod(method);
String SubmitResult = method.getResponseBodyAsString();
Document doc = DocumentHelper.parseText(SubmitResult);
Element root = doc.getRootElement();
String code = root.elementText("code");
if ("2".equals(code)) {
return JWTUtils.createToken(phone + "," + mobile_code);
}
return null;
} catch (Exception e) {
LOGGER.error("验证码发送出错", e);
return null;
}
}
public static boolean isCorrectCode(String code, String phone, HttpServletRequest request) {
Claims resultClaims = JWTUtils.parse3rdSessionJwtClaims(request);
String codeToken = resultClaims.getId();
if (Tools.isEmpty(codeToken)) {
return false;
}
String[] codeTokenArray = codeToken.split(",");
if (codeTokenArray.length != 2) {
return false;
}
if (!phone.equals(codeTokenArray[0]) || !code.equals(codeTokenArray[1])) {
return false;
}
return true;
}
}
其他功能方法
public static boolean isPhoneRight(String phone) {
try {
return !(phone == null || "".equals(phone) || phone.length() != 11 || !Pattern.matches("^((1)\d{10})$",
phone));
} catch (Exception e) {
return false;
}
}
public static String createToken(String userId) {
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
long nowMillis = System.currentTimeMillis();
Date nowDate = new Date(nowMillis);
long expiredMillis = nowMillis + EXPIRED_TTLMILLIS;
Date expDate = new Date(expiredMillis);
byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(SECRET_KEY);
Key singingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
JwtBuilder builder =
Jwts.builder().setId(userId).setIssuedAt(nowDate).setSubject(SUBJECT).setIssuer(ISSUER)
.setExpiration(expDate).signWith(signatureAlgorithm, singingKey);
return builder.compact();
}
最后
以上就是成就缘分为你收集整理的微信小程序 手机号-验证码登录接口的全部内容,希望文章能够帮你解决微信小程序 手机号-验证码登录接口所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复