Commit 7182279a authored by lee_mingzhu's avatar lee_mingzhu

添加微信登录相关代码

parent 03046483
...@@ -51,4 +51,10 @@ public interface Constants { ...@@ -51,4 +51,10 @@ public interface Constants {
Long ONE_DAY = 24 * 60 * 60L; Long ONE_DAY = 24 * 60 * 60L;
} }
interface WeChat {
String APP_ID = "wxcdf6077af8127559";
String REDIRECT_URL = "http://wechattest.xyqb.com/webchat/receiveCode";
String SCOPE = "snsapi_userinfo";
}
} }
package cn.quantgroup.xyqb.controller.external.user;
import cn.quantgroup.xyqb.entity.WebChatUserInfo;
import cn.quantgroup.xyqb.model.JsonResult;
import cn.quantgroup.xyqb.model.webchat.AccessTokenResponse;
import cn.quantgroup.xyqb.service.http.IHttpService;
import cn.quantgroup.xyqb.service.user.IUserService;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
/**
* Created by 11 on 2017/1/17.
*/
@RestController
@RequestMapping("/webchat")
public class WebChatController {
public static final String TOKEN = "5YihkluEo5QuWAWpFwzvA";
private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(WebChatController.class);
@Autowired
private IHttpService httpService;
@Autowired
private IUserService userService;
public String access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxcdf6077af8127559&secret=16eaec16084d0d9c52d4114f359cc72c&code=%s&grant_type=authorization_code";
public String access_userinfo_url = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN";
/**
* 开发者资质认证,有必要吗?
* @param request
* @return
*/
@RequestMapping("/checkValid")
public String valid(HttpServletRequest request) {
String echoStr = request.getParameter("echostr");
if(checkSignature(request)){
return echoStr;
}
return "";
}
/**
* 微信登录
* @param name 姓名
* @param idNo 身份证号
* @param phoneNo 手机号
* @param registerFrom ${registerFrom}
* @param channelId ${channelId}
* @param appChannel ${appChanel}
* @param key "xyqb"
* @return
*/
public JsonResult webChatLogin(String name, String idNo, String phoneNo, String registerFrom,
String channelId, String appChannel, String key){
if(StringUtils.isBlank(name) || StringUtils.isBlank(idNo) || StringUtils.isBlank(phoneNo)){
return JsonResult.buildErrorStateResult("请填写完整的用户信息.", null);
}
if(StringUtils.isBlank(key)){
return JsonResult.buildErrorStateResult("无效的商户信息.", null);
}
return null;
}
public static void main(String[] args) {
String test = " ";
System.out.println(StringUtils.isEmpty(test));
System.out.println(StringUtils.isBlank(test));
}
/**
* 验签:步骤
* 1.获取signature, timestamp, nonce三个参数
* 2.用timestamp, nonce, token三个参数做字符升序排列
* 3.将排列好的字符串进行sha1加密,和signature参数做比较
* 4.相等返回true,否则返回false
* @param request
* @return
*/
public boolean checkSignature(HttpServletRequest request) {
String signature = request.getParameter("signature");
String timestamp = request.getParameter("timestamp");
String nonce = request.getParameter("nonce");
String token = TOKEN;
String[] arrs = new String[]{token, timestamp, nonce};
Arrays.sort(arrs);
String joinStr = splitArray(arrs);
joinStr = sha1(joinStr);
return joinStr.equals(signature);
}
/**
* sha1加密算法,
* @param decript
* @return 返回40位16进制字符串
*/
public String sha1(String decript) {
try {
MessageDigest digest = java.security.MessageDigest
.getInstance("SHA-1");
digest.update(decript.getBytes());
byte messageDigest[] = digest.digest();
StringBuffer hexString = new StringBuffer();
// 字节数组转换为十六进制数
for (int i = 0; i < messageDigest.length; i++) {
String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
if (shaHex.length() < 2) {
hexString.append(0);
}
hexString.append(shaHex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
LOGGER.error("未找到sha1算法." + e.getMessage());
}
return "";
}
/**
* 数组分割为字符串
* @param arr
* @return
*/
private String splitArray(String[] arr) {
StringBuilder builder = new StringBuilder();
for(String str : arr){
builder.append(str);
}
return builder.toString();
}
/**
* 通过redirect_url获取code
* @param request
* @return
*/
@RequestMapping("/receiveCode")
public String receiveCode(HttpServletRequest request) {
String code = request.getParameter("code");
receiveAccessToken(code);
return null;
}
/**
* 拿到access_token,openId,获取用户信息,入库
* @param code
* @return
*/
private JsonResult receiveAccessToken(String code) {
String finalAccessTokenUrl = String.format(access_token_url, code);
String response = httpService.get(finalAccessTokenUrl);
AccessTokenResponse accessTokenResponse = null;
try {
accessTokenResponse = JSON.parseObject(response, AccessTokenResponse.class);
} catch (Exception e){
LOGGER.error("获取access_token出错{}:", e);
return JsonResult.buildErrorStateResult("获取access_token出错", null);
}
//从AccessTokenResponse中获取access_token, openid
String access_token = accessTokenResponse.getAccessToken();
String openId = accessTokenResponse.getOpenId();
String finalUserInfoUrl = String.format(access_userinfo_url, access_token, openId);
//拉取用户信息
String userInfo = httpService.get(finalUserInfoUrl);
saveWebChatUserInfo(userInfo);
return JsonResult.buildSuccessResult("success", null);
}
/**
* 保存微信用户信息
* @param userInfo
*/
private void saveWebChatUserInfo(String userInfo) {
WebChatUserInfo webChatUserInfo = JSON.parseObject(userInfo, WebChatUserInfo.class);
userService.saveWebChatUserInfo(webChatUserInfo);
}
}
package cn.quantgroup.xyqb.entity;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
import java.io.Serializable;
/**
* Created by 11 on 2017/1/17.
* 微信关联的用户信息
*/
@Entity
@Table(name = "webchat_userinfo")
@Data
public class WebChatUserInfo implements Serializable{
private static final long serialVersionUID = -1L;
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "user_id")
private Long userId;
@Column(name = "open_id")
private String openId;
@Column(name = "nick_name")
private String nickName;
@Column(name = "sex")
private short sex;
@Column(name = "language")
private String language;
@Column(name = "city")
private String city;
@Column(name = "province")
private String province;
@Column(name = "country")
private String country;
@Column(name = "head_img_url")
private String headImgUrl;
@Column(name = "privilege")
private String[] privilege;
}
...@@ -32,7 +32,7 @@ public class RequestFilter implements Filter { ...@@ -32,7 +32,7 @@ public class RequestFilter implements Filter {
private static final String [] ALLOWED_PATTERNS = { private static final String [] ALLOWED_PATTERNS = {
"/innerapi/**", "/user/exist","/user/register","/user/login","/user/register/fast", "/innerapi/**", "/user/exist","/user/register","/user/login","/user/register/fast",
"/user/login/fast", "/user/reset_password","/user/exist_check", "/user/login/fast", "/user/reset_password","/user/exist_check",
"/jr58/**","/app/login","/app/login_super","/config/**","/api/**","/user/exists_token", "platform/api/page/return_url" "/jr58/**","/app/login","/app/login_super", "/webchat/**", "/config/**","/api/**","/user/exists_token", "platform/api/page/return_url"
}; };
private static final String UNAUTH_RESULT = JSONObject.toJSONString(JsonResult.buildErrorStateResult("登录失败", null)); private static final String UNAUTH_RESULT = JSONObject.toJSONString(JsonResult.buildErrorStateResult("登录失败", null));
......
package cn.quantgroup.xyqb.model.webchat;
import lombok.Data;
import java.io.Serializable;
/**
* Created by 11 on 2017/1/17.
* 微信获取access_token接口的返回值
*/
@Data
public class AccessTokenResponse implements Serializable{
private static final long serialVersionUID = -1L;
private String accessToken;
private Long expiresIn;
private String refreshToken;
private String openId;
private String scope;
}
package cn.quantgroup.xyqb.repository;
import cn.quantgroup.xyqb.entity.WebChatUserInfo;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* Created by 11 on 2017/1/18.
*/
public interface IWebChatUserRepository extends JpaRepository<WebChatUserInfo, Long> {
}
package cn.quantgroup.xyqb.service.user; package cn.quantgroup.xyqb.service.user;
import cn.quantgroup.xyqb.entity.User; import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.entity.WebChatUserInfo;
/** /**
* Created by Miraculous on 15/7/5. * Created by Miraculous on 15/7/5.
...@@ -26,4 +27,6 @@ public interface IUserService { ...@@ -26,4 +27,6 @@ public interface IUserService {
User saveUser(User user); User saveUser(User user);
User findById(Long userId); User findById(Long userId);
WebChatUserInfo saveWebChatUserInfo(WebChatUserInfo webChatUserInfo);
} }
...@@ -2,7 +2,9 @@ package cn.quantgroup.xyqb.service.user.impl; ...@@ -2,7 +2,9 @@ package cn.quantgroup.xyqb.service.user.impl;
import cn.quantgroup.xyqb.Constants; import cn.quantgroup.xyqb.Constants;
import cn.quantgroup.xyqb.entity.User; import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.entity.WebChatUserInfo;
import cn.quantgroup.xyqb.repository.IUserRepository; import cn.quantgroup.xyqb.repository.IUserRepository;
import cn.quantgroup.xyqb.repository.IWebChatUserRepository;
import cn.quantgroup.xyqb.service.sms.ISmsService; import cn.quantgroup.xyqb.service.sms.ISmsService;
import cn.quantgroup.xyqb.service.user.ILkbUserService; import cn.quantgroup.xyqb.service.user.ILkbUserService;
import cn.quantgroup.xyqb.service.user.IUserService; import cn.quantgroup.xyqb.service.user.IUserService;
...@@ -36,6 +38,9 @@ public class UserServiceImpl implements IUserService { ...@@ -36,6 +38,9 @@ public class UserServiceImpl implements IUserService {
@Autowired @Autowired
private ISmsService smsService; private ISmsService smsService;
@Autowired
private IWebChatUserRepository webChatUserRepository;
@Override @Override
public User findByPhoneInDb(String phone) { public User findByPhoneInDb(String phone) {
return userRepository.findByPhoneNo(phone); return userRepository.findByPhoneNo(phone);
...@@ -56,6 +61,11 @@ public class UserServiceImpl implements IUserService { ...@@ -56,6 +61,11 @@ public class UserServiceImpl implements IUserService {
return userRepository.findById(userId); return userRepository.findById(userId);
} }
@Override
public WebChatUserInfo saveWebChatUserInfo(WebChatUserInfo webChatUserInfo) {
return webChatUserRepository.save(webChatUserInfo);
}
@Override @Override
public User registerAndReturn(String phoneNo, String password, Long registerFrom) { public User registerAndReturn(String phoneNo, String password, Long registerFrom) {
String uuid = lkbUserService.registerApp(phoneNo, password); String uuid = lkbUserService.registerApp(phoneNo, password);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment