java實現微信公衆號授權登錄獲取用戶信息流程

參考地址微信公衆號開發文檔:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1445241432

前提:需要申請認證的微信公衆號;獲取對應的APPID和APPSECRET;並且還需要獲取到用戶信息權限(點擊“修改“添加服務器的域名地址),前期工作安裝測試賬號爲例給大家展示下:

1)、公衆測試賬號獲取

  訪問上面的連接,選擇“接口測試號申請”獲得直接打開http://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index通過微信客戶端掃碼登錄即可登錄。

  登錄完即可獲取到一個測試公衆賬號的信息。主要有appId和appsecret兩個參數,這將唯一標示一個公衆號,並且需要將他們作爲參數獲取用戶的信息。

2)、關注公衆號

   用戶只有關注了這個公衆號了,才能通過打開有公衆號信息的鏈接去授權第三方登錄,並獲取用戶信息的操作。故我們還需要用我們的微信關注微信號,操作如下:
  還是剛剛那個登錄成功後跳轉的頁面,我們可以看到,該頁面有一個二維碼,我們可以通過掃描該二維碼進行關注,關注成功在右邊的“用戶列表”會多一個用戶的信息。如下圖所示:

3)配置回調函數
  我們在微信客戶端訪問第三方網頁(即我們自己的網頁)的時候,我們可以通過微信網頁授權機制,我們不僅要有前面獲取到的appid和appsecret還需要有當用戶授權之後,回調的域名設置,即用戶授權後,頁面會跳轉到哪裏。具體的配置如下:

  還是在剛剛的頁面,有一個“網頁授權獲取用戶基本信息”,點擊後面的修改

 
   填寫回調的域名:
 
  如果你的網址沒有被列入過黑名單,就會在頂部出現
 
 然後,域名配置就成功了!可以進行開發了。

一。授權開發的流程(詳情的東西請以官網爲準,在此就不多說了):具體而言,網頁授權流程分爲四步:

1、引導用戶進入授權頁面同意授權,獲取code

2、通過code換取網頁授權access_token(與基礎支持中的access_token不同)

3、如果需要,開發者可以刷新網頁授權access_token,避免過期

4、通過網頁授權access_token和openid獲取用戶基本信息(支持UnionID機制)

二.按照如上流程我就不多說廢話直接粘代碼供大家參考,請大家多多指教(代碼裏的所有APPID,APPSECRET都是使用的官網提供測試賬號

1.設計一個公用網絡請求工具類:

package com.wxutil.auth;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
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;

public class WXAuthUtil {
    public static final String APPID="wx9b39273dce55dc2f";
    public static final String APPSECRET ="06f175852111045f81ebf62db28a44a0";
    private static final String TOKEN = "immco";
    public static JSONObject doGetJson(String url) throws ClientProtocolException, IOException {
        JSONObject jsonObject =null;
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet httpGet =new HttpGet(url);
        HttpResponse response =  client.execute(httpGet);
        HttpEntity entity =response.getEntity();
        if(entity!=null)
        {
            //把返回的結果轉換爲JSON對象
            String result =EntityUtils.toString(entity, "UTF-8");
            jsonObject =JSON.parseObject(result);
        }
        
        return jsonObject;
    }
   
}

2.微信登錄的實現類(裏面包含引導action和確認登錄後的回調函數):

package com.wxutil.controller;


import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.UUID;


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 com.alibaba.fastjson.JSONObject;
import com.wxutil.auth.SHA1;
import com.wxutil.auth.WXAuthUtil;



/** 
* @author  lbh 
* @date 創建時間:2018年1月18日 下午12:35:11 
* @version 1.0 
* @parameter  
* @since  
* @return  
*/


@Controller
@RequestMapping("/wx")
public class WXLoginController {
    private static final Logger logger = Logger.getLogger(WXLoginController.class);
/**
 * 公衆號微信登錄授權
 * @param request
 * @param response
 * @return
 * @throws ParseException
 * @author  lbh 
 * @date 創建時間:2018年1月18日 下午7:33:59  
 * @parameter
 */
    @RequestMapping(value = "/wxLogin", method = RequestMethod.GET)
    public String wxLogin(HttpServletRequest request,
            HttpServletResponse response)
            throws ParseException {
        //這個url的域名必須要進行再公衆號中進行註冊驗證,這個地址是成功後的回調地址
        String backUrl="http://d84e26b6.ngrok.io/WX_auth/wx/callBack";
        // 第一步:用戶同意授權,獲取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;//必須重定向,否則不能成功
    }
/**
 * 公衆號微信登錄授權回調函數
 * @param modelMap
 * @param req
 * @param resp
 * @return
 * @throws ServletException
 * @throws IOException
 * @author  lbh 
 * @date 創建時間:2018年1月18日 下午7:33:53  
 * @parameter
 */
    @RequestMapping(value = "/callBack", method = RequestMethod.GET)
    public String callBack(ModelMap modelMap,HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*
         * start 獲取微信用戶基本信息
         */
        String code =req.getParameter("code");
      //第二步:通過code換取網頁授權access_token
         String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+WXAuthUtil.APPID
                + "&secret="+WXAuthUtil.APPSECRET
                + "&code="+code
                + "&grant_type=authorization_code";

        System.out.println("url:"+url);
        JSONObject jsonObject = WXAuthUtil.doGetJson(url);
        /*
         { "access_token":"ACCESS_TOKEN",
            "expires_in":7200,
            "refresh_token":"REFRESH_TOKEN",
            "openid":"OPENID",
            "scope":"SCOPE" 
           }
         */
        String openid = jsonObject.getString("openid");
        String access_token = jsonObject.getString("access_token");
        String refresh_token = jsonObject.getString("refresh_token");
        //第五步驗證access_token是否失效;展示都不需要
        String chickUrl="https://api.weixin.qq.com/sns/auth?access_token="+access_token+"&openid="+openid;

        JSONObject chickuserInfo = WXAuthUtil.doGetJson(chickUrl);
        System.out.println(chickuserInfo.toString());
        if(!"0".equals(chickuserInfo.getString("errcode"))){
            // 第三步:刷新access_token(如果需要)-----暫時沒有使用,參考文檔https://mp.weixin.qq.com/wiki,
            String refreshTokenUrl="https://api.weixin.qq.com/sns/oauth2/refresh_token?appid="+openid+"&grant_type=refresh_token&refresh_token="+refresh_token;

            JSONObject refreshInfo = WXAuthUtil.doGetJson(chickUrl);
            /*
             * { "access_token":"ACCESS_TOKEN",
                "expires_in":7200,
                "refresh_token":"REFRESH_TOKEN",
                "openid":"OPENID",
                "scope":"SCOPE" }
             */
            System.out.println(refreshInfo.toString());
            access_token=refreshInfo.getString("access_token");
        }
       
       // 第四步:拉取用戶信息(需scope爲 snsapi_userinfo)
       String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token
                + "&openid="+openid
                + "&lang=zh_CN";
        System.out.println("infoUrl:"+infoUrl);
        JSONObject userInfo = WXAuthUtil.doGetJson(infoUrl);
        /*
         {    "openid":" OPENID",
            " nickname": NICKNAME,
            "sex":"1",
            "province":"PROVINCE"
            "city":"CITY",
            "country":"COUNTRY",
            "headimgurl":    "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
            "privilege":[ "PRIVILEGE1" "PRIVILEGE2"     ],
            "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
            }
         */
        System.out.println("JSON-----"+userInfo.toString());
        System.out.println("名字-----"+userInfo.getString("nickname"));
        System.out.println("頭像-----"+userInfo.getString("headimgurl"));
        /*
         * end 獲取微信用戶基本信息
         */
        //獲取到用戶信息後就可以進行重定向,走自己的業務邏輯了。。。。。。
        //接來的邏輯就是你係統邏輯了,請自由發揮
       
        return "login";
    }
    
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章