小程序第三方登录代码的简单例子
apai登录原理的图解
如下:
小程序代码
如下:
js:
loginClick: function () {
wx.login({
//758c4538366874aab3f63c6813206407 secertID
//wx7275afd7086da55a appId
success: function (res) {
if (res.code) {
wx.request({
url: '要登录的第三方Url',
data: {
code: res.code,
appid: '你的小程序appid',
secretId: '你的小程序secretId'
},
success: function (e) {
console.log(e);
wx.setStorage({
key: 'openid',
data: e.data.openid,
});
wx.setStorage({
key: 'session_key',
data: e.data.session_key,
});
},
method: "GET"
});
} else {
console.log('获取用户登录失败!' + res.errMsg);
}
}
})
}
然后我在java中写了一个servlet来作为小程序请求的对象
接收小程序发送过来的data数据 解析后拼成微信小程序 auth.code2Session的api Url
然后发送请求,获得数据,response到小程序中。
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
String code = request.getParameter("code");
String appid = request.getParameter("appid");
String secret = request.getParameter("secretId");
System.out.println(code+"\r\n"+appid+"\r\n"+secret);
String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+secret+"&js_code="+code+"&grant_type=authorization_code";
String reponse2 = doGet2(url,"utf-8");
JSONObject rs = JSONObject.fromObject(reponse2);
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
char[] buf = rs.toString().toCharArray();
if(buf.length>0){
out.write(buf);//发送
out.flush();
out.close();
System.out.println("*******************数据发送到前台*******************");
}
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}