1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- package com.yingying.tourist.web;
-
- import java.io.UnsupportedEncodingException;
- import java.util.Map;
-
- import org.apache.commons.lang3.StringUtils;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.ResponseBody;
-
- import com.alibaba.fastjson.JSON;
- import com.alibaba.fastjson.JSONObject;
- import com.baomidou.mybatisplus.mapper.EntityWrapper;
- import com.yingying.tourist.common.WechatUtil;
- import com.yingying.tourist.domain.User;
- import com.yingying.tourist.exception.ErrorCode;
- import com.yingying.tourist.result.MessageResult;
- import com.yingying.tourist.service.UserService;
- import com.yingying.tourist.service.WechatService;
-
- import lombok.extern.slf4j.Slf4j;
-
- @Controller
- @Slf4j
- public class WechatController {
-
- @Autowired
- private WechatService wechatService;
-
- @Autowired
- private UserService userService;
-
- @RequestMapping(value="token")
- @ResponseBody
- public String checkToken(String signature, String echostr, String timestamp, String nonce) {
-
- return echostr;
- }
-
-
- @RequestMapping(value="checkJsAuth")
- @ResponseBody
- public MessageResult<String> checkJsAuth(String url) {
-
- String jsapi_ticket = wechatService.getTicket();
-
- Map<String, String> map = WechatUtil.sign(jsapi_ticket, url);
-
- String sign = JSON.toJSONString(map);
-
- if(StringUtils.isBlank(sign)) {
- return new MessageResult<String>().failure(ErrorCode.JS_SIGN_NULL);
- }
-
- return new MessageResult<String>().ok(sign);
-
- }
- @RequestMapping(value="code",produces="application/json;charset=utf-8")
- @ResponseBody
- public MessageResult<String> code(String code) {
- String result = wechatService.getAuthToken(code);
- JSONObject jsonObject = JSONObject.parseObject(result);
- String openId = jsonObject.getString("openid");
- String token = jsonObject.getString("access_token");
-
- if(StringUtils.isBlank(openId)) {
- return new MessageResult<String>().failure(ErrorCode.OPENID_NULL);
- }
-
- // 首先查询openid 是否在数据库中,如果存在直接返回openid
- EntityWrapper<User> userWrapper = new EntityWrapper<>();
- userWrapper.eq("openid", openId);
- User user = userService.selectOne(userWrapper);
- if (user != null) {
- return new MessageResult<String>().ok(openId);
- }
-
- try {
- // 如果不存在,通过token和openid去获取用户信息,并插入到数据库中
- User wechatUser = wechatService.getWechatUser(token, openId);
- if(wechatUser != null) {
- userService.insert(wechatUser);
- }
- } catch (UnsupportedEncodingException e) {
- log.info("编码集转换失败");
- }
-
- return new MessageResult<String>().ok(openId);
- }
- }
|