zoukankan      html  css  js  c++  java
  • 微信小程序获取openId SpringBoot

    微信小程序获取openId

    官方文档

    wx.login:【穿梭门
    https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html
    auth.code2Session【穿梭门
    https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html

    案例

    小程序端

    首先登录获取code,携带code去我们自己的后台。

        wx.login({
          success(res) {
            if (res.code) {
              console.log(res.code)
              http.postData('我们自己的后台接口地址', {
                'code': res.code
              }, (rep) => {
                if (rep.success) {
                  console.log("返回数据:", rep);
                } else {
                  console.log("获取openId失败",);
                }
              })
            } else {
              console.log('登录失败")
            }
          }
        })
    

    我们自己后台

    我们自己的后台接口,用户接受微信小程序请求我们自己后台接口

    /**
    * @TODO 微信小程序通过code获取openid
    * @Auther wjw
    * @Date 2020/4/22 8:29
    */
    @ApiOperation("微信小程序通过code获取openid")
    @PostMapping("/getId")
    public Result<Object> getWeChatOpenId(@RequestBody JSONObject jsonObject) {
    	String code= jsonObject.getString("code");
    	JSONObject json = getSessionKeyOropenid(code);
    	return Result.ok(json);
    }
    

    后台接收到小程序的请求根据这个方式请求微信官方获取用户的openId

    /**
     * 获取微信小程序 session_key 和 openid
     *
     * @param code 调用微信登陆返回的Code
     * @return
     */
    public JSONObject getSessionKeyOropenid(String code) {
    	//微信端登录code值
    	String wxCode = code;
    	String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";  //请求地址 https://api.weixin.qq.com/sns/jscode2session
    	Map<String, String> requestUrlParam = new HashMap<String, String>();
    	requestUrlParam.put("appid", "你微信小程序的appID");  //开发者设置中的appId
    	requestUrlParam.put("secret", "你微信小程序的appSecret"); //开发者设置中的appSecret
    	requestUrlParam.put("js_code", wxCode); //小程序调用wx.login返回的code
    	requestUrlParam.put("grant_type", "authorization_code");    //默认参数 authorization_code
    	//发送post请求读取调用微信 https://api.weixin.qq.com/sns/jscode2session 接口获取openid用户唯一标识
    	JSONObject jsonObject = JSON.parseObject(sendPost(requestUrl, requestUrlParam));
    	return jsonObject;
    }
    

    在获取微信用户openId是调用的方法,就是发送一个post请求,请求微信官方。

    	/**
    	 * 向指定 URL 发送POST方法的请求
    	 *
    	 * @param url 发送请求的 URL
    	 * @return 所代表远程资源的响应结果
    	 */
    	public String sendPost(String url, Map<String, ?> paramMap) {
    		PrintWriter out = null;
    		BufferedReader in = null;
    		String result = "";
    
    		String param = "";
    		Iterator<String> it = paramMap.keySet().iterator();
    
    		while (it.hasNext()) {
    			String key = it.next();
    			param += key + "=" + paramMap.get(key) + "&";
    		}
    
    		try {
    			URL realUrl = new URL(url);
    			// 打开和URL之间的连接
    			URLConnection conn = realUrl.openConnection();
    			// 设置通用的请求属性
    			conn.setRequestProperty("accept", "*/*");
    			conn.setRequestProperty("connection", "Keep-Alive");
    			conn.setRequestProperty("Accept-Charset", "utf-8");
    			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
    			// 发送POST请求必须设置如下两行
    			conn.setDoOutput(true);
    			conn.setDoInput(true);
    			// 获取URLConnection对象对应的输出流
    			out = new PrintWriter(conn.getOutputStream());
    			// 发送请求参数
    			out.print(param);
    			// flush输出流的缓冲
    			out.flush();
    			// 定义BufferedReader输入流来读取URL的响应
    			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
    			String line;
    			while ((line = in.readLine()) != null) {
    				result += line;
    			}
    		} catch (Exception e) {
    			// logger.error(e.getMessage(), e);
    		}
    		//使用finally块来关闭输出流、输入流
    		finally {
    			try {
    				if (out != null) {
    					out.close();
    				}
    				if (in != null) {
    					in.close();
    				}
    			} catch (IOException ex) {
    				ex.printStackTrace();
    			}
    		}
    		return result;
    	}
    

    最后微信用户的openID就拿到了。

  • 相关阅读:
    【Swift】图文混排,ios开发中在textfield或textView中插入图片
    ios开发-指纹识别
    ios开发-程序压后台后,悄悄的抓取数据~~
    setNeedDisplay和setNeedsLayout
    rangeOfString用法
    NSThread的使用
    UIActivityIndicatorView的详细使用
    iOS高斯模糊处理
    HIbernate学习笔记(一) 了解hibernate并搭建环境建立第一个hello world程序
    Hibernate4搭建Log4J日志管理(附Log4j.properties配置详解)
  • 原文地址:https://www.cnblogs.com/wjw1014/p/12749694.html
Copyright © 2011-2022 走看看