一、controller調用?
/*** 登錄** @author jiaketao* @since 2024-04-10*/
@RestController
@RequestMapping("/login")
public class LoginController {/*** 【小程序】登錄獲取session_key和openid** @param code 前端傳code* @return*/@GetMapping("/getWXSessionKey")public 自己的業務返回體 getWXSessionKey(String code) {//根據前端傳來的code,調用微信的接口獲取到當前用戶的openidJSONObject jsonObject = WeChatLoginUtils.getWXSessionKey(code);String openId = jsonObject.getString("openid");//自己的業務邏輯... }/*** 【小程序】獲取手機號** @param code 第二次的code* @return*/@GetMapping("/getWXPhoneInfo")public String getWXPhoneInfo(String code) throws IOException {return WeChatLoginUtils.getWXPhoneInfo(code).getJSONObject("phone_info").getString("phoneNumber");}}
二、封裝的工具類
?1、微信登錄核心工具類:WeChatLoginUtils
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;import java.io.IOException;/*** 微信小程序登錄工具類** @author jiaketao* @since 2024-04-10*/
public class WeChatLoginUtils {/*** 1.獲取session_key** @param code 微信小程序的第一個code* @return*/public static JSONObject getWXSessionKey(String code) {String urlResult = HttpRequestUrlUtil.httpGet("https://api.weixin.qq.com/sns/jscode2session?appid=" + WxConstUtils.WX_OPEN_APPLET_APPID + "&secret=" + WxConstUtils.WX_OPEN_APPLET_SECRET + "&js_code=" + code + "&grant_type=authorization_code");// 轉為jsonJSONObject jsonObject = JSON.parseObject(urlResult);return jsonObject;}/*** 2.獲取access_token** @return*/public static JSONObject getWXAccessToken() {String urlResult = HttpRequestUrlUtil.httpGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + WxConstUtils.WX_OPEN_APPLET_APPID + "&secret=" + WxConstUtils.WX_OPEN_APPLET_SECRET);// 轉為jsonJSONObject jsonObject = JSON.parseObject(urlResult);return jsonObject;}/*** 獲取手機號** @param code 微信小程序的第2個code* @return*/public static JSONObject getWXPhoneInfo(String code) throws IOException {// 調用 2.獲取access_tokenString access_token = getWXAccessToken().getString("access_token");String getPhoneNumberUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + access_token;JSONObject json = new JSONObject();json.put("code", code);// post請求json = HttpRequestUrlUtil.postResponse(getPhoneNumberUrl, json);return json;}}
2、配置文件:WxConstUtils
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;/*** 微信登錄支付相關字段工具類** @author zhaoyan* @since 2024-04-10*/
@Component
public class WxConstUtils implements InitializingBean {// 小程序 appidpublic static String WX_OPEN_APPLET_APPID;// 小程序 secret密鑰public static String WX_OPEN_APPLET_SECRET;// 商戶號public static String WX_OPEN_MCHID;// 密鑰keypublic static String WX_OPEN_KEY;//從配置文件獲取以上內容的配置值// 小程序appid@Value("${wx.open.applet.app_id}")private String appletAppId;//小程序 secret密鑰@Value("${wx.open.applet.secret}")private String appletSecret;// 商戶號@Value("${wx.open.mch_id}")private String mchId;// 密鑰key@Value("${wx.open_key}")private String key;@Overridepublic void afterPropertiesSet() throws Exception {WX_OPEN_APPLET_APPID = appletAppId;WX_OPEN_APPLET_SECRET = appletSecret;WX_OPEN_MCHID = mchId;WX_OPEN_KEY = key;}
}
3、http請求工具類:HttpRequestUrlUtil
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;/*** http請求** @author jiaketao* @since 2024-04-10*/
public class HttpRequestUrlUtil {/*** post請求** @param url* @param object* @return*/public static String httpPost(String url, JSONObject object) {String result = "";// 使用CloseableHttpClient和CloseableHttpResponse保證httpcient被關閉CloseableHttpClient httpClient;CloseableHttpResponse response;HttpPost httpPost;UrlEncodedFormEntity entity;try {httpClient = HttpClients.custom().build();List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();Set<String> keySets = object.keySet();Iterator<String> keys = keySets.iterator();while (keys.hasNext()) {String key = keys.next();nameValuePairs.add(new BasicNameValuePair(key, object.getString(key)));}entity = new UrlEncodedFormEntity(nameValuePairs, "utf-8");httpPost = new HttpPost(url);httpPost.setEntity(entity);//設置超時時間RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000).build();httpPost.setConfig(requestConfig);response = httpClient.execute(httpPost);if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {result = EntityUtils.toString(response.getEntity());}} catch (ClientProtocolException e) {} catch (IOException e) {} catch (Exception e) {} finally {}return result;}/*** get請求** @param url* @return*/public static String httpGet(String url) {String result = "";// 使用CloseableHttpClient和CloseableHttpResponse保證httpcient被關閉CloseableHttpClient httpClient = null;CloseableHttpResponse response = null;try {httpClient = HttpClients.custom().build();response = httpClient.execute(new HttpGet(url));if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {result = EntityUtils.toString(response.getEntity());}} catch (ClientProtocolException e) {} catch (IOException e) {} catch (Exception e) {} finally {}return result;}/*** post請求封裝 參數為?a=1&b=2&c=3** @param path 接口地址* @param Info 參數* @return* @throws IOException*/public static JSONObject postResponse(String path, String Info) throws IOException {//1, 得到URL對象URL url = new URL(path);//2, 打開連接HttpURLConnection conn = (HttpURLConnection) url.openConnection();//3, 設置提交類型conn.setRequestMethod("POST");//4, 設置允許寫出數據,默認是不允許 falseconn.setDoOutput(true);conn.setDoInput(true);//當前的連接可以從服務器讀取內容, 默認是true//5, 獲取向服務器寫出數據的流OutputStream os = conn.getOutputStream();//參數是鍵值隊 , 不以"?"開始os.write(Info.getBytes());//os.write("googleTokenKey=&username=admin&password=5df5c29ae86331e1b5b526ad90d767e4".getBytes());os.flush();//6, 獲取響應的數據//得到服務器寫回的響應數據BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));String str = br.readLine();JSONObject json = JSONObject.parseObject(str);System.out.println("響應內容為: " + json);return json;}/*** post請求封裝 參數為{"a":1,"b":2,"c":3}** @param path 接口地址* @param Info 參數* @return* @throws IOException*/public static JSONObject postResponse(String path, JSONObject Info) throws IOException {HttpClient client = new DefaultHttpClient();HttpPost post = new HttpPost(path);post.setHeader("Content-Type", "application/json");post.addHeader("Authorization", "Basic YWRtaW46");String result = "";try {StringEntity s = new StringEntity(Info.toString(), "utf-8");s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));post.setEntity(s);// 發送請求HttpResponse httpResponse = client.execute(post);// 獲取響應輸入流InputStream inStream = httpResponse.getEntity().getContent();BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));StringBuilder strber = new StringBuilder();String line = null;while ((line = reader.readLine()) != null)strber.append(line + "\n");inStream.close();result = strber.toString();System.out.println(result);if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {System.out.println("請求服務器成功,做相應處理");} else {System.out.println("請求服務端失敗");}} catch (Exception e) {System.out.println("請求異常");throw new RuntimeException(e);}return JSONObject.parseObject(result);}
}
三、maven依賴:pom.xml
<!-- 導入Json格式化依賴 -->
<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.83</version>
</dependency><!-- 導入Apache HttpClient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.14</version>
</dependency><!-- Spring Boot Starter (包含 Spring Core, Spring Beans, Spring Context 等) -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId><version>2.7.18</version> <!-- 或使用最新版本 -->
</dependency><!-- 如果需要 @Value 注解讀取配置文件 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-config</artifactId><version>2.7.18</version>
</dependency>
四、配置文件:application.properties
#wechat Config
wx.open.applet.app_id=自己的appid
wx.open.applet.secret=自己的secret密鑰
#wx.open.applet.sub_app_id=
wx.open.mch_id=
wx.open_key=
wx.open.sub_mch_id=