springboot+微信小程序用codeid换取openid

springboot+微信小程序用codeid换取openid

1.首先我们需要去微信公众平台
https://mp.weixin.qq.com/
准备的是AppID(小程序ID)和AppSecret(小程序密钥)
在这里插入图片描述
2.准备好后开始写代码
3.controller

@RestController
public class GetOpenIdController {
    /**
     * 功能描述:
     * 微信小程序用codeid换取openid
     * @param codeId
     * @return
     */
    @GetMapping("/onLogin")
    private HttpResponseEntity onLogin(String codeId){
        HttpResponseEntity httpResponseEntity = new HttpResponseEntity();
        try {
            String openid = RedisUtils.getOpenId(codeId);
            System.err.println(openid);
            httpResponseEntity.setCode(Constans.SUCCESS_CODE);
            httpResponseEntity.setMessage(Constans.RESULT_SUCCESS);
            httpResponseEntity.setData(openid);
        }catch (Exception e){
            e.printStackTrace();
            httpResponseEntity.setMessage(Constans.RESULT_EXIST);
            httpResponseEntity.setCode(Constans.ADD_EXIST_CODE);
        }
        return httpResponseEntity;
    }
}

4.RedisUtils

/**
     * 获取小程序codeid换取openid
     * @param codeId
     * @return
     */
    public static String getOpenId(String codeId) {
        String url = CODE_URL + APP_ID + "&secret=" + SECRET + "&js_code=" + codeId + "&grant_type=authorization_code";
        PrintWriter out = null;
        BufferedReader in = null;
        String line;
        StringBuffer stringBuffer = new StringBuffer();
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();

            // 设置通用的请求属性 设置请求格式
            //设置返回类型
            conn.setRequestProperty("contentType", "text/plain");
            //设置请求类型
            conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
            //设置超时时间
            conn.setConnectTimeout(1000);
            conn.setReadTimeout(1000);
            conn.setDoOutput(true);
            conn.connect();
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应    设置接收格式
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "UTF-8"));
            while ((line = in.readLine()) != null) {
                stringBuffer.append(line);
            }
            JSONObject jsonObject = JSONObject.parseObject(stringBuffer.toString());
            return jsonObject.get("openid").toString();

        } catch (Exception e) {
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return null;
    }
/**
     *  根据code换取openId
     *  本接口应在后端服务器调用
     */
    private final static String CODE_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=";

    private final static String APP_ID = "AppID(小程序ID)";

    private final static String SECRET = "AppSecret(小程序密钥)";

CODE_URL为请求地址
这样后台就完成了(封装的返回结果集这里就不展示了)

微信小程序端:

新建一个小程序
修改app.js就好

//app.js
App({
  onLaunch: function () {
    var that = this;
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 登录
    wx.login({
      success: function(res) {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
      if(res.code){
        wx.request({
          url: 'http://localhost:8080/onLogin',
          data:{
            codeId:res.code
          },
          success: res => {
            console.log(res);
            res.data.openid = res.data.data;
            that.globalData.openid = res.data.openid;
            console.log(that.globalData.openid);
          }
        })
      }else{
        console.log("获取用户登录失败!" + res.errMsg)
      }
    }
  })
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo
              console.log(res);
              // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })
  },
  globalData: {
    userInfo: null,
    openid:null
  }
})

这样就基本完成了
我们来运行下看看效果:
在这里插入图片描述
在这里插入图片描述

完整代码demo

博客地址

博客地址

码云代码地址

代码地址

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值