com.base.service.WeixinService.java Source code

Java tutorial

Introduction

Here is the source code for com.base.service.WeixinService.java

Source

/**
 * $Id: WeixinService.java Jun 3, 2015 5:27:18 PM hdp
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.base.service;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Formatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.base.dao.WeixinDao;
import com.base.dao.WxUserDao;
import com.base.entity.WeixinApptoken;
import com.base.entity.WxUser;
import com.base.util.EmojiFilter;
import com.base.util.HTTPSRequest;
import com.base.util.HttpSend;
import com.base.util.HttpUtil;
import com.core.dao.impl.AbstractBaseDaoImpl;

/**
 * 
 * 
 * 
 * @since 2016-1-11
 * @author jarous
 * 
 */
@Service
public class WeixinService extends AbstractBaseService<WeixinApptoken> {

    private static final String authUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
    private static final String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";

    @Resource
    private WeixinDao weixinDao;

    @Resource
    private WxUserDao wxUserDao;

    private final static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
    private final static String get_jsapi_ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    @Transactional
    public String getAccessToken() {
        return this.getToken().getAccessToken();
    }

    @Transactional
    public Map<String, String> getSignMap(String url) {
        WeixinApptoken apptoken = this.getToken();
        String jsapi_ticket = apptoken.getJsapiTicket();
        long timestamp = new Date().getTime();
        if (StringUtils.isBlank(jsapi_ticket) || (timestamp - apptoken.getJsapiTime().getTime()) > 7200 * 1000L) {
            String accessToken = apptoken.getAccessToken();
            String requesturl = get_jsapi_ticket_url.replaceAll("ACCESS_TOKEN", accessToken);
            String result = null;
            try {
                //            result = HTTPSRequest.httpsRequest(requesturl, "GET", null);
                result = HttpUtil.sendGet(requesturl, null);
            } catch (Exception e) {
            }
            JSONObject json = JSONObject.parseObject(result);
            if (json.containsKey("ticket")) {
                jsapi_ticket = json.getString("ticket");
                apptoken.setJsapiTicket(jsapi_ticket);
                apptoken.setJsapiTime(new Date());

                // TODO ?weixinApptokenService.saveOrUpdate()</p>?dao
                this.weixinDao.merge(apptoken);
            }
        }

        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
        String string1;
        String signature = "";

        // ??????
        string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str + "&timestamp=" + timestamp + "&url="
                + url;

        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp + "");
        ret.put("signature", signature);
        ret.put("appId", apptoken.getAppId());
        return ret;
        // return sign(this.getJsapi(), url);
    }

    @Transactional
    public WeixinApptoken getToken() {
        //      WeixinApptoken apptoken = this.get("1");
        WeixinApptoken apptoken = null;
        List<WeixinApptoken> weixinApptokenList = this.all();
        for (WeixinApptoken weixinApptoken : weixinApptokenList) {
            apptoken = weixinApptoken;
            break;
        }
        String accessToken = apptoken.getAccessToken();
        if (StringUtils.isNotEmpty(accessToken) && apptoken.getTime() != null) {
            String time = apptoken.getTime().getTime() + "";
            System.out.println("time:" + time);
            Date data = new Date();
            System.out.println("??:" + (data.getTime() - Long.parseLong(time)));
            if ((data.getTime() - Long.parseLong(time)) <= 1000 * 60 * 60 * 1) {
                return apptoken;
            }
        }
        String url = access_token_url.replaceAll("APPID", apptoken.getAppId()).replaceAll("APPSECRET",
                apptoken.getAppSecret());
        String result = null;
        try {
            //         result = HTTPSRequest.httpsRequest(url, "GET", null);
            result = HttpUtil.sendGet(url, null);
        } catch (Exception e) {

        }
        System.out.println("?token:" + result);
        JSONObject json = JSONObject.parseObject(result);
        if (json.containsKey("access_token")) {
            accessToken = json.getString("access_token");
            apptoken.setAccessToken(accessToken);
            apptoken.setTime(new Date());
            // TODO ?weixinApptokenService.saveOrUpdate()</p>?dao
            //         this.weixinApptokenDao.u
            this.update(apptoken);
        }
        return apptoken;
    }

    @Transactional
    public WxUser getUserByOpenIdAndCode(String code, HttpSession session) {
        WeixinApptoken apptoken = this.getToken();
        //?access_token
        String requestUrl = authUrl.replaceAll("APPID", apptoken.getAppId())
                .replaceAll("SECRET", apptoken.getAppSecret()).replaceAll("CODE", code);
        String result = HttpSend.httpRequestStr(requestUrl, "GET", null);
        if (StringUtils.isBlank(result)) {
            return null;
        }
        JSONObject json = JSONObject.parseObject(result.trim());
        if (!json.containsKey("openid")) {
            return null;
        }
        String openid = json.getString("openid");
        if (openid != null) {
            List<WxUser> wxUsers = this.wxUserDao.list("o.openid = ? ", openid);
            if (wxUsers != null && wxUsers.size() > 0) {
                return wxUsers.get(0);
            }
        }
        return null;
    }

    @Transactional
    public WxUser getOpenidByCode(String code, HttpSession session) {
        WeixinApptoken apptoken = this.getToken();
        this.LOG.info("api AuthController start");

        //?access_token
        String requestUrl = authUrl.replaceAll("APPID", apptoken.getAppId())
                .replaceAll("SECRET", apptoken.getAppSecret()).replaceAll("CODE", code);

        this.LOG.info(requestUrl);

        String result = HttpSend.httpRequestStr(requestUrl, "GET", null);
        this.LOG.info("?openid  result----" + result);
        if (StringUtils.isBlank(result))
            return null;
        JSONObject json = JSONObject.parseObject(result.trim());
        if (!json.containsKey("openid"))
            return null;
        String openid = json.getString("openid");
        String infoRequestUrl = infoUrl.replaceAll("ACCESS_TOKEN", json.getString("access_token"))
                .replaceAll("OPENID", openid);
        String infoResult = HttpSend.httpRequestStr(infoRequestUrl, "POST", null);
        this.LOG.info("? ? infoResult----" + infoResult);
        if (null != infoResult) {

            JSONObject info = JSONObject.parseObject(infoResult);
            List<WxUser> wxUsers = this.wxUserDao.list("o.openId = ? ", openid);
            String nickname = info.getString("nickname");
            nickname = EmojiFilter.filterEmoji(nickname);
            nickname = nickname.replaceAll("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]", "");
            WxUser user = null;
            if (wxUsers != null && wxUsers.size() == 0) {
                // (usernull)
                user = new WxUser();
                user.setHeadImageUrl(info.getString("headimgurl"));
                user.setNickName(nickname);
                //            user.setIsSuspended(false);
                user.setOpenId(openid);
                //            user.setSource("wx");
                user.setPhone("");
                user.setChangce(1);
                user.setShareLock(0);
                System.out.println("userid==================" + user.getId());
                //            user.setUserInfo(userInfo);
                //            user.setLastLogin(new Date());
                this.wxUserDao.persist(user);
            } else {
                user = wxUsers.get(0);
                //            user.setLastLogin(new Date());
                user.setNickName(nickname);
                user.setHeadImageUrl(info.getString("headimgurl"));
                this.wxUserDao.merge(user);
            }
            return user;
        }
        return null;
    }

    //   public Map<String, Object> sendBookHotelTemplet(BookHotel bookHotel,String openId) {
    //      // TODO Auto-generated method stub
    //      Map<String,Object> resultMap = new HashMap<String,Object>();
    //      Date date = new Date();
    //      SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
    //      String time = df.format(date);
    //      String templateid = "4LpCOqfk5bNEwJgQyotfQx8ZiipShSktgpWaA7XLhBI";
    //      String shuttleWeixinTemplateDetailUrl = "http://sino-corrugated.360vt.cn/lizhan/myHotel.do";
    //      String url = shuttleWeixinTemplateDetailUrl;
    //      StringBuilder msgContentSbr = new StringBuilder();
    //      Map<String,Object> firstMap = new HashMap<String,Object>();
    //      firstMap.put("color","#173177");
    //      firstMap.put("value", "?");
    //      Map<String,Object> keyword1 = new HashMap<String,Object>();
    //      keyword1.put("color","#173177");
    //      keyword1.put("value",bookHotel.getHotelType().getHotel().getName());
    //      Map<String,Object> keyword2 = new HashMap<String,Object>();
    //      keyword2.put("color","#173177");
    //      keyword2.put("value",bookHotel.getHotelType().getType());
    //      Map<String,Object> keyword3 = new HashMap<String,Object>();
    //      keyword3.put("color","#173177");
    //      keyword3.put("value",bookHotel.getRoomNum());
    //      Map<String,Object> keyword4 = new HashMap<String,Object>();
    //      keyword4.put("color","#173177");
    //      keyword4.put("value",df.format(bookHotel.getStartTime())+"-"+df.format(bookHotel.getEndTime()));
    //      Map<String,Object> keyword5 = new HashMap<String,Object>();
    //      keyword5.put("color","#173177");
    //      keyword5.put("value",bookHotel.getName()+"("+bookHotel.getPhone()+")");
    //      Map<String,Object> remarkMap = new HashMap<String,Object>();
    //      remarkMap.put("color","#173177");
    //      remarkMap.put("value","");
    //      Map<String,Object> dataMap = new HashMap<String,Object>();
    //      WeixinApptoken apptoken = this.getToken();
    //      String accessToken = apptoken.getAccessToken();
    //      dataMap.put("first", firstMap);
    //      dataMap.put("keyword1", keyword1);
    //      dataMap.put("keyword2", keyword2);
    //      dataMap.put("keyword3", keyword3);
    //      dataMap.put("keyword4", keyword4);
    //      dataMap.put("keyword5", keyword5);
    //      dataMap.put("remark", remarkMap);
    //      resultMap.put("result", "SUCCESS");
    //      for(int i = 0;i<3;i++){         
    //         int error = this.sendWeixinTemplateMsg(accessToken,openId, templateid, url, dataMap);
    //         if(error==0){
    //            break;
    //         }
    //      }
    //      resultMap.put("result", "OK");
    //      return resultMap;
    //   }
    //   
    //   public Map<String, Object> sendBookHotelFailTemplet(BookHotel bookHotel,String openId) {
    //      // TODO Auto-generated method stub
    //      Map<String,Object> resultMap = new HashMap<String,Object>();
    //      Date date = new Date();
    //      SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
    //      String time = df.format(date);
    //      String templateid = "uplTqGRtDNrKH_OfwxfhIAtw_RLeFToAyfslT28tlHs";
    //      String shuttleWeixinTemplateDetailUrl = "http://sino-corrugated.360vt.cn/lizhan/myHotel.do";
    //      String url = shuttleWeixinTemplateDetailUrl;
    //      StringBuilder msgContentSbr = new StringBuilder();
    //      Map<String,Object> firstMap = new HashMap<String,Object>();
    //      firstMap.put("color","#173177");
    //      firstMap.put("value", "?");
    //      Map<String,Object> keyword1 = new HashMap<String,Object>();
    //      keyword1.put("color","#173177");
    //      keyword1.put("value",bookHotel.getHotelType().getHotel().getName()+"(:"+bookHotel.getHotelType().getType()+")("+bookHotel.getRoomNum()+")");
    //      Map<String,Object> keyword2 = new HashMap<String,Object>();
    //      keyword2.put("color","#173177");
    //      keyword2.put("value",df.format(bookHotel.getStartTime())+"-"+df.format(bookHotel.getEndTime()));
    //      Map<String,Object> remarkMap = new HashMap<String,Object>();
    //      remarkMap.put("color","#173177");
    //      remarkMap.put("value",":"+bookHotel.getName()+"("+bookHotel.getPhone()+")\n:"+bookHotel.getReason()+"\n??");
    //      Map<String,Object> dataMap = new HashMap<String,Object>();
    //      WeixinApptoken apptoken = this.getToken();
    //      String accessToken = apptoken.getAccessToken();
    //      dataMap.put("first", firstMap);
    //      dataMap.put("keyword1", keyword1);
    //      dataMap.put("keyword2", keyword2);
    //      dataMap.put("remark", remarkMap);
    //      resultMap.put("result", "SUCCESS");
    //      for(int i = 0;i<3;i++){         
    //         int error = this.sendWeixinTemplateMsg(accessToken,openId, templateid, url, dataMap);
    //         if(error==0){
    //            break;
    //         }
    //      }
    //      resultMap.put("result", "OK");
    //      return resultMap;
    //   }
    //   
    //   public Map<String, Object> sendActivityNoticeTemplet(Activity activity,String content,String openId) {
    //      // TODO Auto-generated method stub
    //      Map<String,Object> resultMap = new HashMap<String,Object>();
    //      Date date = new Date();
    //      SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd HH:mm");
    //      String time = df.format(date);
    //      String templateid = "UHOfvEQPkGH0YkE-0F7yvMLTJ59X1y4jZcN4njSU3Pc";
    //      String shuttleWeixinTemplateDetailUrl = "http://sino-corrugated.360vt.cn/lizhan/activity.do";
    //      String url = shuttleWeixinTemplateDetailUrl;
    //      StringBuilder msgContentSbr = new StringBuilder();
    //      String activityTime = activity.getStartTime();
    //      try{         
    //         activityTime = df.format(df.parse(activity.getStartTime()));
    //      }catch (Exception e) {
    //         // TODO: handle exception
    //      }
    //      Map<String,Object> firstMap = new HashMap<String,Object>();
    //      firstMap.put("color","#173177");
    //      firstMap.put("value", content);
    //      Map<String,Object> keyword1 = new HashMap<String,Object>();
    //      keyword1.put("color","#173177");
    //      keyword1.put("value",activity.getName());
    //      Map<String,Object> keyword2 = new HashMap<String,Object>();
    //      keyword2.put("color","#173177");
    //      keyword2.put("value","???");
    //      Map<String,Object> keyword3 = new HashMap<String,Object>();
    //      keyword3.put("color","#173177");
    //      keyword3.put("value",activityTime);
    //      Map<String,Object> keyword4 = new HashMap<String,Object>();
    //      keyword4.put("color","#173177");
    //      keyword4.put("value",activity.getAddress());
    //      Map<String,Object> remarkMap = new HashMap<String,Object>();
    //      remarkMap.put("color","#173177");
    //      remarkMap.put("value","?????");
    //      Map<String,Object> dataMap = new HashMap<String,Object>();
    //      WeixinApptoken apptoken = this.getToken();
    //      String accessToken = apptoken.getAccessToken();
    //      dataMap.put("first", firstMap);
    //      dataMap.put("keyword1", keyword1);
    //      dataMap.put("keyword2", keyword2);
    //      dataMap.put("keyword3", keyword3);
    //      dataMap.put("keyword4", keyword4);
    //      dataMap.put("remark", remarkMap);
    //      resultMap.put("result", "SUCCESS");
    //      for(int i = 0;i<3;i++){         
    //         int error = this.sendWeixinTemplateMsg(accessToken,openId, templateid, url, dataMap);
    //         if(error==0){
    //            break;
    //         }
    //      }
    //      resultMap.put("result", "OK");
    //      return resultMap;
    //   }

    public Integer sendWeixinTemplateMsg(String accessToken, String openid, String templateid, String url,
            Map<String, Object> msgDatas) {
        // TODO Auto-generated method stub
        if (StringUtils.isBlank(accessToken)) {
            return 998;
        }
        String weixinUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
        String send_template_msg_url = weixinUrl.replace("ACCESS_TOKEN", accessToken);
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        jsonMap.put("touser", openid);
        System.out.println("??templateid*****************************" + templateid);
        jsonMap.put("template_id", templateid);
        jsonMap.put("topcolor", "#FF0000");
        jsonMap.put("url", url);
        jsonMap.put("data", msgDatas);
        String json = JSON.toJSONString(jsonMap);
        System.out.println("json--" + json);
        String responseResult = HttpSend.httpRequestStr(send_template_msg_url, "POST", json);
        System.out.println("responseResult--" + responseResult);
        if (StringUtils.isEmpty(responseResult)) {
            return 997;
        }
        JSONObject jsonObject = JSONObject.parseObject(responseResult);
        if (null == jsonObject) {
            return 996;
        }
        System.out.println("jsonObject--" + jsonObject.toString());
        try {
            int errcode = jsonObject.getIntValue("error");
            System.out.println("errcode--" + errcode);
            if (errcode == 0) {
                return 0;
            }
            return errcode;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("Exception--" + e.getMessage());
            return 999;
        }
    }

    /**
     * @param id
     * @return
     * ??
     */
    public boolean judge(String id) {
        WxUser user = this.wxUserDao.find(id);
        WeixinApptoken apptoken = this.getToken();
        String token = apptoken.getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + token + "&openid="
                + user.getOpenId() + "&lang=zh_CN";
        try {
            String infoResult = HTTPSRequest.httpsRequest(url, "GET", null);
            System.out.println(":" + infoResult);
            JSONObject info = JSONObject.parseObject(infoResult);
            if (info.get("subscribe") != null) {
                if (info.get("subscribe").toString().equals("1")) {//
                    return true;
                } else {
                    return false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public AbstractBaseDaoImpl<WeixinApptoken> getBaseDao() {
        // TODO Auto-generated method stub
        return weixinDao;
    }
}