微信小程序登录Java后台接口
微信小程序登录java后台接口
首先看一下微信小程序的开发文档:
微信小程序开发文档
步骤:
具体实现步骤
小程序端
随便弄一个按钮,绑定下面的方法
java服务器端
package com.kylin.wxtest.controller;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;import com.kylin.wxtest.bean.Login;import org.apache.http.HttpEntity;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;@RestControllerpublic class UserController { private static final long serialVersionUID=1L; private static final String APPID = "wxb88xxxxxxxx46140e"; private static final String SECRET = "19fa40c6xxxxxxxx6ae971267"; private String code; public String getCode() { return code; } public void setCode(String code) { this.code = code; } @RequestMapping(value = "/login") public String login(String code){ System.out.println(code); System.out.println("------------------------------------"); //微信那边的接口,grant_type=authorization_code是固定的 String url="https://api.weixin.qq.com/sns/jscode2session?appid="+APPID+ "&secret="+SECRET+"&js_code="+ code +"&grant_type=authorization_code"; //发送请求给微信后端 CloseableHttpClient httpClient= HttpClients.createDefault(); HttpGet httpGet=new HttpGet(url); InputStream inputStream=null; CloseableHttpResponse httpResponse=null; StringBuilder result=new StringBuilder(); try { httpResponse=httpClient.execute(httpGet); HttpEntity entity=httpResponse.getEntity(); inputStream=entity.getContent(); BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream)); String line=""; while ((line=bufferedReader.readLine())!=null){ System.out.println(line); //这里需要使用fastjson来提取一下内容 JSONObject jsonObject= JSON.parseObject(line); Login login=new Login(); login.setOpenid(jsonObject.getString("openid")); login.setSession_key(jsonObject.getString("session_key")); result.append(login.getOpenid()+"hello_world"+login.getSession_key()); System.out.println(result.toString()); } } catch (IOException e) { e.printStackTrace(); } return result.toString(); }}总结
这样小程序端就可以获取到openId以及session_key;相当于授权成功!
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。

