小程序第三方登录代码的简单例子

小程序第三方登录代码的简单例子

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();
		}
	}

完整的代码可以在这里下载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值