微信小程序登录流程总结 目录 1.1. 前端调用wx.login 。。给后端传递一个code 1 1.2. 开发者需要在开发者服务器后台调用 auth.code2Session,使用 code 换取
微信小程序登录流程总结
目录
1.1. 前端调用wx.login 。。给后端传递一个code 1
1.2. 开发者需要在开发者服务器后台调用 auth.code2Session,使用 code 换取 openid 和 session_key 等信息 1
wx.login({
success(res) {
if (res.code) {
// 发起网络请求
wx.request({
url: 'https://test.com/onLogin',
data: {
code: res.code
}
})
} else {
console.log('登录失败!' + res.errMsg)
}
}
})
-
- 开发者需要在开发者服务器后台调用 auth.code2Session,使用 code 换取 openid 和 session_key 等信息
登录凭证校验。通过 wx.login() 接口获得临时登录凭证 code 后传到开发者服务器调用此接口完成登录流程。更多使用方法详见 小程序登录。
GET https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
属性 | 类型 | 默认值 | 必填 | 说明 |
appid | string |
| 是 | 小程序 appId |
secret | string |
| 是 | 小程序 appSecret |
js_code | string |
| 是 | 登录时获取的 code |
grant_type | string |
| 是 | 授权类型,此处只需填写 authorization_code |
|
|
|
|
|
返回参数 参数 说明 openid 用户唯一标识 session_key 会话密钥 expires_in 过期时长(默认7200)
- Code
/springboothelloword
package springboothelloword;
import java.io.IOException;
import java.util.Map;
import javax.servlet.ServletRequest;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
@RestController
@EnableAutoConfiguration
public class Example {
// http://localhost:8080/jscode2session?code=xxxx
@RequestMapping("/jscode2session") // 登录
public String jscode2session(HttpServletRequest req) throws ClientProtocolException, IOException {
String code = req.getParameter("code");
String url = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
url=url.replaceAll("JSCODE", code);
// 执行get请求.
CloseableHttpResponse response = HttpClients.createDefault().execute(new HttpGet(url));
// 获取响应实体
String html = EntityUtils.toString(response.getEntity());
return html;
}
- 登录流程图