com.mingsoft.weixin.util.BaseUtils.java Source code

Java tutorial

Introduction

Here is the source code for com.mingsoft.weixin.util.BaseUtils.java

Source

/**
The MIT License (MIT) * Copyright (c) 2016 (mingsoft.net)
    
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
    
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
    
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

package com.mingsoft.weixin.util;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.mingsoft.util.JsonUtil;
import com.mingsoft.util.StringUtil;
import com.mingsoft.weixin.http.HttpClientConnectionManager;

/**
 * ???????</br>
 * ?http://mp.weixin.qq.com/wiki/index.php?title=%E9%A6%96%E9%A1%B5</br>
 * ?httpClient???</br>
 * @author wangtp
 * @version 
 * ?100-000-000<br/>
 * 2015921 ?10:13:58<br/>
 * ?<br/>
 */
public abstract class BaseUtils {

    public Logger logger = Logger.getLogger(this.getClass());

    /**
     * ?appid,???(?ID)
     */
    protected String appid;

    /**
     * ?secret,???
     */
    protected String secret;

    /**
     * httpclient?com.mingsoft.util.proxy???https??
     */
    protected DefaultHttpClient HTTPCLIENT = new DefaultHttpClient();;

    /**
     * ??
     */
    private String accessToken = null;

    /**
     * ?
     */
    protected final static String WEIXIN_JSON_ERR_STR = "errmsg";

    /**
     * ?tokenjson
     */
    protected final static String ACCESS_TOEN_OK_STR = "access_token";

    /**
     * ?tokenjson
     */
    protected final static String ACCESS_TOEN_ERR_STR = "invalid appid";

    /**
     * ??token?
     */
    private final static String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&";

    /**
     * ???
     */
    protected final static String SERVICE_MSG = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=";

    /**
     * ?ticket ,ticketURL???
     */
    protected final static String CREATE_TICKET = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=";

    /**
     * ticket???
     */
    protected final static String GET_QRCODE = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=";

    /**
     * ?openid
     */
    protected final static String GET_USER_OPENID_LIST = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=";

    /**
     * openid ?
     */
    protected final static String GET_USERDATA_BYOPENID = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=";

    /**
     * code???access_token;??
     *      appid:?, ?
     *      secret:?,?appsecret
     *      code:?,?code?
     *      grant_type:?,authorization_code
     *:https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxdf90b2c4ece8de81&secret=5888a47b886535146ffa8ab6f1bed24b&code="?code"&grant_type=authorization_code
     */
    protected final static String AUTHORIZATION_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token";

    /**
     * access_token,access_token??refresh_token
     * refresh_token7?30?60?90refresh_token????
     * ??:
     *      appid:?, ?
     *      grant_type:?, refresh_token
     *      refresh_token:?,access_token?refresh_token?
     *:https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN
     */
    protected final static String AUTHORIZATION_REFRESH_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/refresh_token";

    /**
     * ??
     * ?snsapi_userinfo??access_tokenopenid??
     * ??:
     *      access_token:?,???,?access_token?access_token??
     *      openid:?,
     *      lang:?,zh_CN zh_TW ?en 
     *:https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
     */
    protected final static String AUTHORIZATION_SCOPE_URL = "https://api.weixin.qq.com/sns/userinfo";

    /**
     * ????
     */
    protected final static String GROUP_URL = "https://api.weixin.qq.com/cgi-bin/groups/";

    /**
     * ??????
     * @param appid ??????
     * @param secret ??????
     */
    public BaseUtils(String appid, String secret) {
        this.appid = appid;
        this.secret = secret;
    }

    public String getAccessToken() {
        if (accessToken == null) {
            try {
                HTTPCLIENT = (DefaultHttpClient) HttpClientConnectionManager.getSSLInstance(HTTPCLIENT);
                HttpGet get = HttpClientConnectionManager
                        .getGetMethod(ACCESS_TOKEN_URL + "appid=" + appid + "&secret=" + secret);
                HttpResponse response = HTTPCLIENT.execute(get);
                String jsonStr = EntityUtils.toString(response.getEntity(), HttpClientConnectionManager.UTF8);

                Map object = JsonUtil.getMap4Json(jsonStr);
                logger.debug("?token:" + jsonStr);
                //?appidsecret??,null
                if (object.get(this.WEIXIN_JSON_ERR_STR) != null
                        && object.get(this.WEIXIN_JSON_ERR_STR).equals(this.ACCESS_TOEN_ERR_STR)) {
                    return null;
                }
                if (StringUtil.isBlank(object.get(ACCESS_TOEN_OK_STR).toString())) {
                    return null;
                }
                accessToken = object.get(ACCESS_TOEN_OK_STR).toString();
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return accessToken;
    }

    /**
     * ???JSON
     * @param pathUrl ?
     * @return ??JSON,???:
     *                jsonsStr.getString("?JSON???")
     */
    public Map<String, Object> jsonStrAuthor(String pathUrl) {
        HttpGet get = HttpClientConnectionManager.getGetMethod(pathUrl);
        DefaultHttpClient HTTPCLIENT = new DefaultHttpClient();
        try {
            HttpResponse responses = (HttpResponse) HTTPCLIENT.execute(get);
            String jsonStr = EntityUtils.toString(responses.getEntity(), "utf-8");
            logger.debug("JSON:" + jsonStr);
            return JsonUtil.getMap4Json(jsonStr);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * ???
     * @param request 
     * @param filePath ?
     * @return
     */
    public String getRealPath(HttpServletRequest request, String filePath) {
        return request.getServletContext().getRealPath(File.separator) + filePath;
    }

}