微信网页授权和获取 `access_token` 和 `openid` 的过程通常涉及前端和后端的协作。以下是一个简化的流程和示例代码,展示如何在 Java 后端中获取 `access_token` 和 `openid`,以及如何推送微信模板消息。 1. 前端获取授权 首先,用户在前端点击一个按钮或其他元素,以触发微信授权。 ```html <!-- 引入微信 JS SDK --> <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script> <script> wx.config({ debug: true, appId: 'YOUR_APP_ID', timestamp: YOUR_TIMESTAMP, nonceStr: 'YOUR_NONCE_STR', signature: 'YOUR_SIGNATURE', jsApiList: ['chooseImage', 'uploadImage'] }); </script> ``` 2. 后端获取 access_token 和 openid 当用户在前端完成授权后,微信会将用户重定向回你指定的回调 URL,并携带一个 code 参数。你需要使用这个 code 参数向后端请求 `access_token` 和 `openid`。 请求 access_token 和 openid ```java import java.net.HttpURLConnection; import java.net.URL; import java.io.BufferedReader; import java.io.InputStreamReader; import org.json.JSONObject; public class WeChatService { private static final String APP_ID = "YOUR_APP_ID"; private static final String APP_SECRET = "YOUR_APP_SECRET"; private static final String TOKEN = "YOUR_TOKEN"; // 验证用的令牌,用于防止 CSRF 攻击 private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APP_ID + "&secret=" + APP_SECRET + "&code="; private static final String OPENID_URL = "https://api.weixin.qq.com/sns/userinfo?access_token="; public static JSONObject getAccessTokenAndOpenId(String code) throws Exception { String urlString = ACCESS_TOKEN_URL + code; URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); return new JSONObject(response.toString()); // 解析返回的 JSON 字符串为 JSONObject } } ``` 3. 使用 access_token 和 openid 推送模板消息 使用 `access_token` 和 `openid` 来推送微信模板消息。这通常在后端完成。 推送模板消息的请求: 注意:为了推送模板消息,你需要在微信公众平台上设置模板并获取模板ID。 * 请求地址:`https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN` * 请求方法:POST * 请求数据:JSON 格式,参考微信官方文档。以下是一个示例: ```java public static void sendTemplateMessage(String accessToken, String openId, String templateId, JSONObject data) throws Exception { String urlString = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken; URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); // 需要设置允许输出数据,否则请求无法发送。 connection.setRequestProperty("Content-Type", "application/json"); // 设置请求的内容类型为 JSON。 try (OutputStream os = connection.getOutputStream()) { // 注意:需要捕获异常,防止出现资源泄露。 os.write(JSONObject.toJSONString(data).getBytes("UTF-8")); // 将 JSON 数据转换为字节数组并写入输出流。注意:这里使用了 UTF-8 编码。 } catch (Exception e) [2024-02-28 10:21:50 | AI写代码神器 | 1023点数解答]