天天看點

SpringBoot 簡單便捷- 實作App第三方微信登入第一步擷取微信openID

我不寫代碼,我隻是代碼的搬運工。

導入pom檔案

<dependency>
		<groupId>org.apache.httpcomponents</groupId>
		<artifactId>httpclient</artifactId>
		<version>4.5.3</version><!--$NO-MVN-MAN-VER$ -->
	</dependency>
	<!-- 微信支付 -->
	<dependency>
		<groupId>com.github.wxpay</groupId>
		<artifactId>wxpay-sdk</artifactId>
		<version>0.0.3</version>
	</dependency>
           

第一步擷取微信openID

* 擷取openID
 * 
 * @param code
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/getWxOpenid", method = RequestMethod.GET, produces = "application/json")
@ApiOperation("擷取微信Openid")
public R getOpenidNews(String code) throws Exception {
	/**
	 * 第一步 通過code擷取openId
	 */
	LOGGER.info("微信code-->" + code);
	// 頁面擷取openId接口
	String getopenid_url = "https://api.weixin.qq.com/sns/oauth2/access_token";
	String param = "appid=" + PrivateParam.APP_ID + "&secret=" + PrivateParam.APP_SECRET + "&code=" + code
			+ "&grant_type=authorization_code";
	String openIdStr = HttpRequestUtil.sendGet(getopenid_url, param);
	// 轉成Json格式
	JSONObject json = JSONObject.parseObject(openIdStr);
	LOGGER.info("json-->" + json);
	if ("40029".equals(json.getString("errcode"))) {
		return R.error().put("data", "Code無效錯誤!").put("json", json);
	}
	// 擷取openId
	String openId = json.getString("openid");
	if (openId == null) {
		return R.error().put("data", "openId為空值!");
	}
	WxOpenidEntity wx = new WxOpenidEntity();
	// 網頁授權接口的憑證
	wx.setAccessToken(json.getString("access_token"));
	// access_token接口調用憑證逾時時間機關
	wx.setExpiresIn(json.getString("expires_in"));
	// 使用者重新整理access_token
	wx.setRefreshToken(json.getString("refresh_token"));
	// 使用者的唯一辨別
	wx.setOpenid(json.getString("openid"));
	// 使用者授權的作用域
	wx.setScope(json.getString("scope"));
	return R.ok().put("data", wx);
}
           

HttpRequestUtil 工具類

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

/**
 *
 * @author Mr.wang
 * @version 2019年12月12日 下午4:09:30 微信支付類型
 */

public class HttpRequestUtil {

	/**
	 * 向指定URL發送GET方法的請求
	 * 
	 * @param url   發送請求的URL
	 * @param param 請求參數,請求參數應該是 name1=value1&name2=value2 的形式。
	 * @return URL 所代表遠端資源的響應結果
	 */
	public static String sendGet(String url, String param) {
		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = url + "?" + param;
			System.out.println(urlNameString);
			URL realUrl = new URL(urlNameString);
			// 打開和URL之間的連接配接
			URLConnection connection = realUrl.openConnection();
			// 設定通用的請求屬性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 建立實際的連接配接
			connection.connect();
			// 擷取所有響應頭字段
			Map<String, List<String>> map = connection.getHeaderFields();
			// 周遊所有的響應頭字段
			for (String key : map.keySet()) {
				System.out.println(key + "--->" + map.get(key));
			}
			// 定義 BufferedReader輸入流來讀取URL的響應
			in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("發送GET請求出現異常!" + e);
			e.printStackTrace();
		}
		// 使用finally塊來關閉輸入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 向指定 URL 發送POST方法的請求
	 * 
	 * @param url   發送請求的 URL
	 * @param param 請求參數,請求參數應該是 name1=value1&name2=value2 的形式。
	 * @return 所代表遠端資源的響應結果
	 */
	public static String sendPost(String url, String param) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打開和URL之間的連接配接
			URLConnection conn = realUrl.openConnection();
			// 設定通用的請求屬性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 發送POST請求必須設定如下兩行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 擷取URLConnection對象對應的輸出流
			out = new PrintWriter(conn.getOutputStream());
			// 發送請求參數
			out.print(param);
			// flush輸出流的緩沖
			out.flush();
			// 定義BufferedReader輸入流來讀取URL的響應
			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}

		} catch (Exception e) {
			System.out.println("發送 POST 請求出現異常!" + e);
			e.printStackTrace();
		}
		// 使用finally塊來關閉輸出流、輸入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

}
           

WxOpenidEntity 實體類

import lombok.Data;

@Data
public class WxOpenidEntity {
	
	/**
	 * 網頁授權接口調用憑證,注意:此access_token與基礎支援的access_token不同
	 */
	private String accessToken;`在這裡插入代碼片`
	/**
	 * access_token接口調用憑證逾時時間,機關(秒)
	 */
	private String expiresIn;
	/**
	 * 使用者重新整理access_token
	 */
	private String refreshToken;
	/**
	 * 	使用者唯一辨別
	 */
	private String openid;
	/**
	 * 使用者授權的作用域,使用逗号(,)分隔
	 */
	private String scope;
}
           

第二步-擷取微信使用者資訊

/**
	 * 擷取微信使用者資訊
	 * 
	 * @param accessToken
	 * @param openid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getWxUserMsg", method = RequestMethod.GET, produces = "application/json")
	@ApiOperation("擷取微信使用者資訊")
	public R getWxUnionid(String accessToken, String openid) throws Exception {
		/**
		 * 第一步 通過code擷取openId
		 */
		System.out.println("accessToken-->" + accessToken);
		System.out.println("openid-->" + openid);
		// 頁面擷取openId接口
		String getopenid_url = "https://api.weixin.qq.com/sns/userinfo";
		String param = "access_token=" + accessToken + "&openid=" + openid + "&;
		String openIdStr = HttpRequestUtil.sendGet(getopenid_url, param);
		// 轉成Json格式
		JSONObject json = JSONObject.parseObject(openIdStr);
		if ("40003".equals(json.getString("errcode"))) {
			return R.error().put("msg", "openid無效!").put("json", json);
		}
		WxUnionidEntity unionid = new WxUnionidEntity();
		// 使用者微信openID
		unionid.setOpenid(json.getString("openid"));
		// 使用者昵稱
		unionid.setNickname(json.getString("nickname"));
		// 使用者性别
		unionid.setSex(json.getString("sex"));
		// 使用者個人資料填寫的省份
		unionid.setProvince(json.getString("province"));
		// 使用者個人資料填寫的城市
		unionid.setCity(json.getString("city"));
		// 使用者個人資料填寫的國家
		unionid.setCountry(json.getString("country"));
		// 使用者頭像
		unionid.setHeadimgurl(json.getString("headimgurl"));
		// 使用者特權資訊
		unionid.setPrivilege(json.getString("privilege"));
		// 使用者unionid
		unionid.setUnionid(json.getString("unionid"));
		return R.ok().put("data", unionid);
	}
           

WxUnionidEntity 實體類

import lombok.Data;

@Data
public class WxUnionidEntity {

	/**
	 * 使用者的唯一辨別
	 */
	private String openid;
	/**
	 * 使用者昵稱
	 */
	private String nickname;
	/**
	 * 使用者的性别,值為1時是男性,值為2時是女性,值為0時是未知
	 */
	private String sex;
	/**
	 * 使用者個人資料填寫的省份
	 */
	private String province;
	/**
	 * 普通使用者個人資料填寫的城市
	 */
	private String city;
	/**
	 * 	國家,如中國為CN
	 */
	private String country;
	/**
	 * 使用者頭像,最後一個數值代表正方形頭像大小(有0、46、64、96、132數值可選,0代表640*640正方形頭像),使用者沒有頭像時該項為空。若使用者更換頭像,原有頭像URL将失效。
	 */
	private String headimgurl;
	/**
	 * 使用者特權資訊,json 數組,如微信沃卡使用者為(chinaunicom)
	 */
	private String privilege;
	/**
	 * 隻有在使用者将公衆号綁定到微信開放平台帳号後,才會出現該字段。
	 */
	private String unionid;
}
           

繼續閱讀