WeixinIndexController.java 9.42 KB
package com.server.web.controller;

import com.server.utils.SHA1;
import com.server.utils.weixin.WXMessageType;
import com.server.utils.weixin.WeixinBaseUtil;
import com.server.web.common.mapper.TKzyUserMapper;
import com.server.web.common.model.TKzyUser;
import com.server.web.common.model.TKzyUserExample;
import jodd.util.URLDecoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.jfinal.weixin.sdk.kit.PaymentKit.xmlToMap;

/**
 * Created by 豆腐干Sama on 2018/12/5.
 */
@RestController
@RequestMapping(value = BaseController.WX_NAMESPACE + "/wxIndex",produces = "application/json")
public class WeixinIndexController extends BaseController{
    @Value("${wx.app.secret}")
    private String appSecret;
    @Value("${wx.app.id}")
    private String appId;
    @Value("${wx.tocken}")
    private String wxTocken;
    @Autowired
    private TKzyUserMapper userMapper;
    @RequestMapping(value = "/authorizeCallback",method = {RequestMethod.GET,RequestMethod.POST})
    public void authorizeCallback(HttpServletRequest request, HttpServletResponse response) {
        try {

            String code = request.getParameter("code");// 授权码
            String redirectUri = request.getParameter("redirectUri");// redirectUri参数,验证成功跳转
            WeixinBaseUtil weixinBaseUtil = new WeixinBaseUtil();
            logger.error("授权回调参数:code " + code + " appId " + appId + " appSecret:" + appSecret);
            Map<String, Object> _AuthMap = weixinBaseUtil.authorization(appId, appSecret, code);

            if (_AuthMap == null) {
                response.sendRedirect(redirectUri);
                return;
            }

            String openId = (String)_AuthMap.get("openid");
            String nickname = (String) _AuthMap.get("nickname");
            String headimgurl = (String) _AuthMap.get("headimgurl");

            logger.error("nickname:" + nickname + "");
            TKzyUser user;
            TKzyUserExample example = new TKzyUserExample();
            example.createCriteria().andWxOpenidEqualTo(openId);
            List<TKzyUser> users = userMapper.selectByExample(example);
            if (CollectionUtils.isEmpty(users)) {
                user = new TKzyUser();
                user.setHeadPhoto(headimgurl);
                user.setFullName(nickname);
                user.setWxOpenid(openId);
            } else {
                user = users.get(0);
                user.setLastLoginDt(new Date());
                if (StringUtils.isEmpty(user.getFullName())) {
                    user.setFullName(nickname);
                }
                if (StringUtils.isEmpty(user.getHeadPhoto())) {
                    user.setHeadPhoto(headimgurl);
                }
                userMapper.updateByPrimaryKeySelective(user);
            }

            request.getSession().setAttribute(WX_USER_SESSION_KEY,user);
            logger.error("user.getNickName:" + user.getFullName());
            response.sendRedirect(redirectUri);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public Map<String,Object> getAccessToken() {
        String accessToken = getAccessToken(appId, appSecret);
        if (StringUtils.hasText(accessToken)) {
            return returnSuccess(accessToken);
        } else {
            return returnError("0","获取access_toke失败",null);
        }
    }
    public void textWrite(String text,HttpServletResponse response) {
        response.setContentType("text/html; charset=UTF-8");
        try {
            response.getWriter().write(text);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 处理接受参数
     * @param request
     * @return
     */
    public static String readRequestStr(HttpServletRequest request) {
        BufferedReader reader = null;
        StringBuilder sb = new StringBuilder();
        try {
            reader = new BufferedReader(new InputStreamReader(request.getInputStream(), "utf-8"));
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != reader) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    @RequestMapping(value = "/callback", method = {RequestMethod.POST, RequestMethod.GET})
    public void callback(HttpServletRequest request, HttpServletResponse response){
        try{
            String signature = request.getParameter("signature");
            String nonce = request.getParameter("nonce");
            String echostr = request.getParameter("echostr");
            String timestamp = request.getParameter("timestamp");
            boolean isPass =checkSignature(signature, timestamp, nonce);
            if (!isPass) {
                logger.error("isPass 验证错误!!");
                return;
            } else if (StringUtils.hasText(echostr)) {
                textWrite(echostr,response);
                return;
            }
            String xmlStr =readRequestStr(request);
            Map<String, String> map = xmlToMap(xmlStr);
            if (map == null) {
                logger.error("callback-map is null !!");
            }else{
                String msgType = map.get("MsgType");
                String content ="";
                if (WXMessageType.event.toString().equals(msgType)) {//点击事件
                    // FIXME: 2018/12/5
                }else if(WXMessageType.text.toString().equals(msgType)){//关键字回复
                    // FIXME: 2018/12/5
                }
                String openId = map.get("ToUserName");
                String wx_id = map.get("FromUserName");

                if(content!=null&&!"".equals(content.trim())){
                    textWrite(getWxStringMsg(openId,wx_id, content),response);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        System.out.println(URLDecoder.decode("http%3A%2F%2Fkzy-wx-1.jimijiayuan.cn%2Fhome"));

//        String urlTicket = "http://kzy-wx.jimijiayuan.cn/home?shareFlag=true";
//        urlTicket = urlTicket.substring(0,urlTicket.indexOf("?"));
//        System.out.println(urlTicket);
    }

    @ResponseBody
    @RequestMapping(value = "/jsApiSignature", method = {RequestMethod.POST, RequestMethod.GET}, produces = "application/json")
    public Map<String,Object> jsApiSignature(HttpServletRequest request) throws Exception{
        try{
            String urlTicket = request.getParameter("url");
            if(StringUtils.hasText(urlTicket)){
//                urlTicket = URLDecoder.decode(urlTicket);
                System.out.println("传参:\t"+urlTicket);
                Map<String, Object> signature = jsApiSignature(urlTicket);
                if(signature!=null) {
                    return returnSuccess(signature);
                }
            }else{
                return returnError("0","参数url缺失",null);
            }
        }catch (Exception e){
            e.printStackTrace();
            return returnError("0","服务器异常",null);
        }
        return returnError("0","获取签名失败","");
    }


    public boolean checkSignature(String signature,String timestamp,String nonce) {
        String[] str = new String[]{wxTocken, timestamp, nonce};
        //排序
        Arrays.sort(str);
        //拼接字符串
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < str.length; i++) {
            buffer.append(str[i]);
        }
        //进行sha1加密
        String temp = SHA1.encode(buffer.toString());
        //与微信提供的signature进行匹对
        return signature.equals(temp);
    }

    public String getWxStringMsg(String fromUserName, String toUserName, String content) {
        String msg = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[%s]]></MsgType><Content><![CDATA[%s]]></Content></xml>";
        return String.format(msg, new String[]{toUserName, fromUserName, Long.valueOf(System.currentTimeMillis() / 1000).toString(), "text", content});
    }

    public Map<String,Object> jsApiSignature(String url) throws Exception{
        if(StringUtils.hasText(appId)&&StringUtils.hasText(appId)&&StringUtils.hasText(url)){
            String jsapi_ticket =WeixinBaseUtil.getTicket(appId,getAccessToken(appId,appSecret),url,redisTemplate);
            Map<String, Object> sign = WeixinBaseUtil.sign(jsapi_ticket, url, appId);
            return sign;
        }else{
            return null;
        }
    }
}