微信小程序实现登录之java后台

微信小程序登录流程大致为:

第一步:前端调用wx.login()函数,获取返回的code值。(每次通过wx.login()得到的code值可能不一样)

第二步:传递获取到的code值到服务器端,在服务器端用小程序appid,appsecret等去请求微信服务器,获取openid和session_key。(注:每个微信账号,在每个小程序中获取到的openid是唯一的,它可以作为判断新用户和老用户的依据。)

第三步:将用户openid保存到数据库,并将用户id返回到前端,放到缓存中保持登录态。

 

个人比较喜欢在小程序启动时,将登陆代码写到onLanuch()中,每次小程序启动后,去登陆,如果第一次进入该小程序,就将新用户保存到数据库,如果不是新用户,将用户id返回到前端。下面给出app.js文件的实现代码:

//app.js
App({
  onLaunch: function() {
    let that = this;
    wx.login({
      success: function (res) {
        //console.log(res.code);
        if (res.code) {
          wx.request({
            url: that.globalData.host + '/xxx/xxx/xxxx/xxxx,//这里写自己java后台的请求地址
            method: 'POST',
            data: {
              code: res.code
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            success(res) {
              //console.log('用户登录成功!id=' + res.data.session_key);
              wx.setStorageSync("userid", res.data.userid);//将用户id保存到缓存中
              wx.setStorageSync("session_key", res.data.session_key);//将session_key保存到缓存中
            }
          })
        } else {
          console.log('获取用户登录态失败!' + res.errMsg)
        }
      }
    })
  },
  globalData: {
    host: 'http://localhost:80'
  }
})

java后台的接收代码如下:

 import net.sf.json.JSONObject;//解析json字符串所需的包

/**maven依赖如下

<!-- 解析JSON所需包-->
		<dependency>
			<groupId>net.sf.json-lib</groupId>
			<artifactId>json-lib-ext-spring</artifactId>
			<version>1.0.2</version>
		</dependency>

**/


/*******************************小程序********************************/
    @PostMapping("/xxxx/xxxx")
    @ResponseBody
    public AjaxResult mini_Login(HttpServletRequest request,@Param("code") String code)
    {
        //String c=request.getParameter("code");//也可以通过此语句获取code值
        //System.out.println(code);
        AjaxResult res=new AjaxResult();//这里是自定义类,用于封装返回的数据,你可以用map替代
        String result="";
        try{//请求微信服务器,用code换取openid。HttpUtil是工具类,后面会给出实现,Configure类是小程序配置信息,后面会给出代码
            result = HttpUtil.doGet(
                    "https://api.weixin.qq.com/sns/jscode2session?appid="
                            + Configure.mini_appID + "&secret="
                            + Configure.mini_secret + "&js_code="
                            + code
                            + "&grant_type=authorization_code", null);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        //System.out.println(result);
        JSONObject jsonObj = JSONObject.fromObject(result);//解析从微信服务器上获取到的json字符串
        System.out.println("用户的openid为:"+jsonObj.get("openid"));//此处也可以得到session_key的值
        res.put("session_key",jsonObj.get("session_key").toString());
//这里Miniuser类是自己的业务类,你可以根据自己需要自行定义
        Miniuser miniuser=miniuserService.isRegister(jsonObj.get("openid").toString());//去数据库判断用户是否存在该用户
        if(miniuser!=null)//如果存在该用户
        {
            res.put("userid",miniuser.getMini_id());//将用户id返回
            return res;
        }
        //如果是新用户,就添加用户到数据库中
        Miniuser userInfo=new Miniuser();//封装小程序对象
        userInfo.setMini_openid(jsonObj.get("openid").toString());
        //将用户信息保存到数据库中
        miniuserService.saveMiniUser(userInfo);
        res.put("userid",miniuserService.isRegister(jsonObj.get("openid").toString()).getMini_id());
        return res;
    }

HttpUtil工具类实现如下:

package xxx.xxxxxx.xxxxxxxx.xxxxxxxxxx;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.httpclient.HttpStatus;//此类需要添加maven依赖或jar包

/** 将此依赖添加到pom.xml中
<!-- HttpUtils所需包-->
		<dependency>
			<groupId>commons-httpclient</groupId>
			<artifactId>commons-httpclient</artifactId>
			<version>3.1</version>
		</dependency>

**/

public class HttpUtil {

    public static String doGet(String urlPath, HashMap<String, Object> params)
            throws Exception {
        StringBuilder sb = new StringBuilder(urlPath);
        if (params != null && !params.isEmpty()) { // 说明有参数
            sb.append("?");

            Set<Entry<String, Object>> set = params.entrySet();
            for (Entry<String, Object> entry : set) { // 遍历map里面的参数
                String key = entry.getKey();
                String value = "";
                if (null != entry.getValue()) {
                    value = entry.getValue().toString();
                    // 转码
                    value = URLEncoder.encode(value, "UTF-8");
                }
                sb.append(key).append("=").append(value).append("&");
            }

            sb.deleteCharAt(sb.length() - 1); // 删除最后一个&
        }
        // System.out.println(sb.toString());
        URL url = new URL(sb.toString());
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5000); // 5s超时
        conn.setRequestMethod("GET");

        if (conn.getResponseCode() == HttpStatus.SC_OK) {// HttpStatus.SC_OK ==
            // 200
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            StringBuilder sbs = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sbs.append(line);
            }
            // JSONObject jsonObject = new JSONObject(sbs.toString());
            return sbs.toString();
        }

        return null;
    }
}

Configure类的代码如下:

package xxxx.xxxxx.xxxxxxxx.xxxxxxx;

/**
 * 这里放置各种配置数据
 */
public class Configure {
    /************************************************************小程序设置********************************************************************/
    public static String mini_appID = "xxxxxxxxxxxxxxxxx";//appid,去自己的小程序后台找
    public static String mini_secret = "xxxxxxxxxxxxxxxxxxxxxxxxxx";//appsecret,去自己小程序后台找
    public static String grant_type = "authorization_code";
    /************************************************************小程序设置********************************************************************/

}

以上为所有的代码,有疑问的小伙伴可以留言,或者有错误之处还请多多指正。

转发请注明出处,谢谢!

  • 19
    点赞
  • 115
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值