主要步骤:
- 前端获取到code(wx.login),传入服务器
- 服务器通过参数AppID和AppSecret访问官方接口,获取到OpenId
- 服务器将OpenId进行相应的业务处理并返回给前端
在服务器访问微信官方接口: https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
主要逻辑流程如下:
![image](https://img7.php1.cn/3cdc5/cb94/cd5/e47f729e1161b1b3.png)
后台Java实现如下:
public static String getWXProfile(String code) throws JSONException {String params &#61; "appid&#61;" &#43; StaticData.appId &#43; "&secret&#61;" &#43; StaticData.appSecret &#43; "&js_code&#61;" &#43; code &#43; "&grant_type&#61;authorization_code";String sr &#61; sendGet("https://api.weixin.qq.com/sns/jscode2session", params);JSONObject json &#61; new JSONObject(sr);String session_key &#61; json.get("session_key").toString();String openId &#61; (String) json.get("openid");return openId;}public static String sendGet(String url, String param){String result &#61; "";BufferedReader in &#61; null;try {String urlNameString &#61; url &#43; "?" &#43; param;URL realUrl &#61; new URL(urlNameString);URLConnection connection &#61; 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 &#61; connection.getHeaderFields();// 遍历所有的响应头字段in &#61; new BufferedReader(new InputStreamReader(connection.getInputStream()));String line;while ((line &#61; in.readLine()) !&#61; null) {result &#43;&#61; line;}} catch (Exception e) {System.out.println("发送GET请求出现异常&#xff01;" &#43; e);e.printStackTrace();}finally {try {if (in !&#61; null) {in.close();}} catch (Exception e2) {e2.printStackTrace();}}return result;}
#亲测有效