欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

[微信]微信小程序后台授权操作

程序员文章站 2022-04-03 09:19:27
...


@Controller
@RequestMapping("/user")
public class UserController {
	public final static Logger logger = LoggerFactory.getLogger(UserController.class);

	/**
	 * appid 小程序id 微信公众平台 设置中的开发设置中可以查到
	 */
	public static final String APPID = "XXXXX===小程序AppId===XXXX";
	/**
	 * AppSecret 小程序** 微信公众平台 设置中的开发设置中可以查询
	 */
	public static final String SECRET = "XXXXXXXX小程序**XXXXXXXXXX";
	/**
	 * 用于获取用户openid的接口网址 其中%s将会用String.format函数替换为实际的值 建议单独储存
	 */
	public static final String Web_access_tokenhttps = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";

	/**
	 * 通过APPID,SECET,code组合出用于获取用户openid的实际网址 建议单独储存
	 */
	public static String getWebAccess(String code) {
		return String.format(Web_access_tokenhttps, APPID, SECRET, code);
	}

	@Autowired
	private IUserService userService;

	/**
	 * 微信授权
	 * 
	 * @return json格式数据 如果成功返回值为{ userid:XX}
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("unused")
	@RequestMapping("/authorise.do")
	@ResponseBody
	public Map<String, Object> wx_authorise(HttpServletRequest request) {
		logger.info("======authorise.do========", request);
		Map<String, Object> map = new HashMap<String, Object>();
		String code = "";
		String userInfo = "";
		code = request.getParameter("code");// 获取code,换取openId
		userInfo = request.getParameter("userInfo");// 获取用户数据
		JSONObject user = JSON.parseObject(userInfo);

		// 登录凭证不能为空

		if (code == null || code.length() == 0) {
			map.put("msg", "code Can't be empty.");
			return map;

		}

		logger.info(">>>微信小程序登录,请求数据为[ code:" + code + "]");
		logger.info("用户名字:" + user.getString("nickName"));// 用户名字
		logger.info("用户性别:" + user.getString("gender"));// 性别

		// 获取用户openid的实际网址
		String token = getWebAccess(code);
		// 通过HttpGet方法将token发送至微信服务器并获得其回执(使用code换取access_token)
		String rec = httpGet(token);
		System.err.println("微信回执为:/n" + rec);
		JSONObject json = JSON.parseObject(rec);
		// 获取用户IP地址
		String ip = new UserController().getIpAddr(request);
		System.out.println("用户IP:" + ip);
		// 获取回执的openid
		if (json != null) {
			String openid = json.getString("openid");// 获取openid
			
			user_register flag = userService.findOpenId(openid);

			
			if (null != flag) {// 登录
				// 判断openid是否存在 如果存在则保存登录信息
				user_login login = new user_login();
				login.setUser_id(flag.getUser_id());
				login.setLogin_ip(ip);
				login.setLogin_name(flag.getLogin_name());
				login.setLogin_time(new Date());

				logger.info("====input====userService.AddUserLoginInfo===STARTED==");
				userService.AddUserLoginInfo(login);
				logger.info("====output====userService.AddUserLoginInfo====END==");

				map.put("msg", "0");
				map.put("user_id", flag.getUser_id());

			} else if(null == flag){
				// 注册
				user_register register = new user_register();
			    register.setOpenid(openid);
				register.setLogin_name(openid);
         register.setNick_name(user.getString("nickName"));
				register.setPassword("");
				register.setRegist_date(new Date());
				register.setTypename("房客");

				logger.info("====input====userService.AddUser===STARTED==:{}", register);
				int result = userService.AddUser(register);// 添加注册表信息
				logger.info("====output====userService.AddUser====END==:{}", result);

				String getUser_id = userService.findOpenIdByPhone(openid);

				logger.info("====getUser_id======:{}", getUser_id);

				// 添加用户账户信息
				user_account account = new user_account();
				account.setUser_id(Integer.valueOf(getUser_id));// 用户编号
				account.setStates(user_account.states_yes);

				logger.info("====input====userService.AddUsertAccount===STARTED==:{}", account);
				int accountId = userService.AddUsertAccount(account);
				logger.info("====output====userService.AddUsertAccount====END==:{}", accountId);

				// 添加用户信息
				user_info userinfo = new user_info();
				userinfo.setAvatarUrl(user.getString("avatarUrl"));
				userinfo.setCity(user.getString("city"));
				userinfo.setCountry(user.getString("country"));
				userinfo.setNick_name(user.getString("nickName"));
				userinfo.setUser_id(Integer.valueOf(getUser_id));
				String gender = "女";
				if (user.getInteger("gender") == 1) {
					gender = "男";
				}
				userinfo.setGender(gender);
				logger.info("====input====userService.AddUserInfo===STARTED==");
				userService.AddUserInfo(userinfo);
				logger.info("====output====userService.AddUserInfo====END==");

				// 添加用户登录信息
				user_login login = new user_login();
				login.setUser_id(Integer.valueOf(getUser_id));
				login.setLogin_ip(ip);
				login.setLogin_name(openid);
				login.setLogin_time(new Date());

				logger.info("====input====userService.AddUserLoginInfo===STARTED==");
				userService.AddUserLoginInfo(login);
				logger.info("====output====userService.AddUserLoginInfo====END==");
				if (result > 0 && accountId > 0) {
					
					map.put("msg", "0");
					map.put("user_id", login.getUser_id());
					

				}
				// 如果无openid则new一个user_register储存至数据库并返回id

				// 注册表信息添加
				// map.put("user_id", result);

			}else {
				map.put("msg", "Abnormal!!");
			}
		}
		return map;
	}

	/**
	 * @Description: 获取客户端IP地址
	 */
	@SuppressWarnings("unused")
	private String getIpAddr(HttpServletRequest request) {
		logger.info("====unused====END==:{}", request);
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
			if (ip.equals("127.0.0.1")) {
				// 根据网卡取本机配置的IP
				InetAddress inet = null;
				try {
					inet = InetAddress.getLocalHost();
				} catch (Exception e) {
					e.printStackTrace();
				}
				ip = inet.getHostAddress();
			}
		}
		// 多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
		if (ip != null && ip.length() > 15) {
			if (ip.indexOf(",") > 0) {
				ip = ip.substring(0, ip.indexOf(","));
			}
		}
		return ip;
	}

	/**
	 * 通过HttpGet类发送GET请求并获取返回信息
	 * 
	 * @param path
	 *            发送至的网址
	 * @return
	 */
	public String httpGet(String path) {
		if (path == null) {
			return null;
		}
		String rec = null;
		HttpGet get = new HttpGet(path);
		try {
			HttpResponse response = HttpClients.createDefault().execute(get);
			HttpEntity entity = response.getEntity();
			rec = EntityUtils.toString(entity);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return rec;
	}

}