通過(guò)微信公眾號(hào)獲取用戶信息

1.控制類

設(shè)置公眾號(hào)回調(diào)域名.png

獲取測(cè)試公眾號(hào):https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index

package com.taxsearch.controller.tf;

import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.taxsearch.util.WXAuthUtil;



/**
 * FileName: WXLoginController.java
 * @Description: 通過(guò)公眾號(hào)獲取微信用戶信息
 * All rights Reserved, Designed By JS-YFB
 * Copyright:   Copyright(C) 2017-2027
 * Company      JS-YFB LTD.
 * @author:     yc
 * @version     V1.0 
 * Createdate:  2018年8月30日 下午11:18:02
 *
 */


@Controller
public class WXLoginController {
    private static final Logger logger = Logger.getLogger(WXLoginController.class);
/**
 * 公眾號(hào)微信登錄授權(quán)
 * @param request
 * @param response
 * @return
 * @throws ParseException
 * @author  lbh 
 * @date 創(chuàng)建時(shí)間:2018年1月18日 下午7:33:59  
 * @parameter
 */
    @RequestMapping(value = "/wxLogin", method = RequestMethod.GET)
    public String wxLogin(HttpServletRequest request,
            HttpServletResponse response)
            throws ParseException {
        //這個(gè)url的域名必須要進(jìn)行再公眾號(hào)中進(jìn)行注冊(cè)驗(yàn)證tfds.scjinsui.com:9001,這個(gè)地址是成功后的回調(diào)地址
        String backUrl="http://tfds.scjinsui.com:9001/TFds/callBack.do";
        // 第一步:用戶同意授權(quán),獲取code
        String url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+WXAuthUtil.APPID
                + "&redirect_uri="+URLEncoder.encode(backUrl)
                + "&response_type=code"
                + "&scope=snsapi_userinfo"
                + "&state=STATE#wechat_redirect";

        logger.info("forward重定向地址{" + url + "}");
        //response.sendRedirect(url);
        return "redirect:"+url;//必須重定向,否則不能成功
    }
/**
 * 公眾號(hào)微信登錄授權(quán)回調(diào)函數(shù)
 * @param modelMap
 * @param req
 * @param resp
 * @return
 * @throws ServletException
 * @throws IOException
 * @author  lbh 
 * @date 創(chuàng)建時(shí)間:2018年1月18日 下午7:33:53  
 * @parameter
 */
    @RequestMapping(value = "/callBack", method = RequestMethod.GET)
    @ResponseBody
    public String callBack(ModelMap modelMap,HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //獲取code
        String code =req.getParameter("code");
        //獲取openid
        Map<String, String> map1 = getOpenId(code);
        String openid = map1.get("openid");
        //獲取基礎(chǔ)token
        Map<String, String> map2 = getToken();
        String token = map2.get("access_token");
        //獲取用戶信息
        Map<String, String> map3 = getUserInfo(token,openid);
//        net.sf.json.JSONObject jsonObject=WeiXin.getWeiXin(code);
//        return jsonObject.toString();
        return map3.toString();
    }
    
    /**
     * @Title: getToken
     * @Description: 獲取基礎(chǔ)token
     * @param: @return
     * @param: @throws ClientProtocolException
     * @param: @throws IOException  
     * @return: Map<String,String>   
     * @throws
     */
    public Map<String, String> getToken() throws ClientProtocolException, IOException{
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+WXAuthUtil.APPID
              + "&secret="+WXAuthUtil.APPSECRET;
        Map<String, String> map = WXAuthUtil.doGetJson(url);
        return map;
    }
    
    
    /**
     * @Title: getOpenId
     * @Description: 通過(guò)code獲取OpenId
     * @param: @param code
     * @param: @return
     * @param: @throws ClientProtocolException
     * @param: @throws IOException  
     * @return: Map<String,String>   
     * @throws
     */
     public Map<String, String> getOpenId(String code) throws ClientProtocolException, IOException{
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+WXAuthUtil.APPID
              + "&secret="+WXAuthUtil.APPSECRET
              + "&code="+code
              + "&grant_type=authorization_code";
        Map<String, String> map = WXAuthUtil.doGetJson(url);
        return map;
    }
   
  
   /**
    * @Title: getUserInfo
    * @Description: 獲取useriNFO
    * @param: @param accessToken
    * @param: @param openId
    * @param: @return
    * @param: @throws ClientProtocolException
    * @param: @throws IOException  
    * @return: Map<String,String>   
    * @throws
    */
    public Map<String, String> getUserInfo(String accessToken, String openId) throws ClientProtocolException, IOException {
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+accessToken+"&openid="+openId;
        Map<String, String> map = WXAuthUtil.doGetJson(requestUrl);
        return map;
        
    }
}

2.發(fā)送請(qǐng)求并接受返回的JSON字符串并轉(zhuǎn)換為MAP

參數(shù).png
package com.taxsearch.util;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Map;

import org.apache.http.HttpEntity;
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.springframework.util.DigestUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

public class WXAuthUtil {
    public static final String APPID="wx87bff1545b051cad";
    public static final String APPSECRET ="bbc6053f8766b1abc2e309a70187da04";
    
    public static Map<String, String> doGetJson(String url) throws ClientProtocolException, IOException {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet httpGet =new HttpGet(url);
        HttpResponse response =  client.execute(httpGet);
        HttpEntity entity =response.getEntity();
        String result= "";
        Map<String, String> map = null;
        if(entity!=null)
        {
            //把返回的結(jié)果轉(zhuǎn)換為JSON對(duì)象
            result =EntityUtils.toString(entity, "UTF-8");
//              jsonObject =JSON.parseObject(result);
            GsonBuilder gb = new GsonBuilder();
            Gson g = gb.create();
            map = g.fromJson(result, new TypeToken<Map<String, Object>>() {}.getType());
            
        }
        
        return map;
    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,711評(píng)論 19 139
  • Spring Web MVC Spring Web MVC 是包含在 Spring 框架中的 Web 框架,建立于...
    Hsinwong閱讀 22,978評(píng)論 1 92
  • 1,如果要求你盡可能全面的介紹自己,你打算用什么樣的架構(gòu)來(lái)描述? 從雙方能發(fā)生的連接點(diǎn): 職業(yè)、行業(yè)、學(xué)校、城市 ...
    李大俠ID閱讀 382評(píng)論 0 0
  • 本人是鄭州大學(xué)本科大三在校生,高考時(shí)可能因?yàn)樾膽B(tài)好超常發(fā)揮很多分,為了考上高中老師常說(shuō)的211大學(xué),抉擇了一會(huì)兒,...
    古木書(shū)屋閱讀 286評(píng)論 0 0
  • 國(guó)石通常是一個(gè)國(guó)家人們喜愛(ài)的或具有優(yōu)異特性和重要價(jià)值,或是在該國(guó)出產(chǎn)和加工方面具有物色的寶石或玉石,例如南非的鉆石...
    珠寶大課堂閱讀 3,700評(píng)論 0 0

友情鏈接更多精彩內(nèi)容