java后台获取openid(小程序开发 前端+后台)

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_35821988/article/details/82932055

前台需要request后台Servlet响应

data:{ } 传值,需要有appid , appsecret ,js_code(临时登录凭证)

需要把openid设置为全局变量,不重复获取

获取openid之前,确保appid正确,且与配置文件中的appid一致。

前端app.js代码如下,全局数据需要根据自己的填写。

//app.js
App({
  globalData: {
    requestURL: 'http://localhost:8080',//请求地址
    appid: '',
    appsecret: '',//
    userInfo: null,
    openid: ''
  },
  onLaunch: function () {
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    var that = this;
    wx.login({
      success: function (res) {
        console.log(res.code);
        wx.request({
          url: 'http://localhost:8080/CloudExplorer/GetOpenIdServlet',
          data: {
            appid: that.globalData.appid,
            secret: that.globalData.appsecret,
            js_code: res.code,
            grant_type: 'authorization_code'
          },
          method: 'POST',
          header: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          success: function (res) {
            console.log(res)
            var OPEN_ID = res.data.openId;//获取到的openid
            that.globalData.openid = res.data.openId;
            console.log(that.globalData.openid)
          }
        })
      }
    })
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: res => {
              this.globalData.userInfo = res.userInfo
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })
  }

})

后台Servlet需要调用WeChatService类中获取openid的函数

Servlet写法如下:

package cloud.Servlet;

import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.google.gson.Gson;

import cloud.Service.*;

@WebServlet(urlPatterns={"/GetOpenIdServlet"})
public class GetOpenIdServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置请求编码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        /* 设置响应头允许ajax跨域访问 */
        response.setHeader("Access-Control-Allow-Origin", "*");
        /* 星号表示所有的异域请求都可以接受, */
        response.setHeader("Access-Control-Allow-Methods", "GET,POST");

       
        //转成json数据
        String appid=request.getParameter("appid");
        String secret=request.getParameter("secret");
        String js_code=request.getParameter("js_code");
        
        WeChatService getOpenId=new WeChatService();
        String openId=getOpenId.GetOpenID(appid,secret,js_code);
        Map<String, String> result = new HashMap<String, String>();;
        result.put("openId",openId);
        result.put("msg", "后台已收到");
        String json = new Gson().toJson(result);
        //返回值给微信小程序
        Writer out = response.getWriter();
        out.write(json);
        out.flush();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

WeChatService类的写法如下:

package cloud.Service;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
/**
 * @author chd
 * @QQ:1025584691
 */
public class WeChatService {
    /**
     * 调用对方接口方法
     * @param path 对方或第三方提供的路径
     * @param data 向对方或第三方发送的数据,大多数情况下给对方发送JSON数据让对方解析
     */
    public static String interfaceUtil(String path,String data) {
    	String openId="";
        try {
            URL url = new URL(path);
            //打开和url之间的连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            PrintWriter out = null;
            //请求方式
//          conn.setRequestMethod("POST");
//           //设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); 
            //设置是否向httpUrlConnection输出,设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个
            //最常用的Http请求无非是get和post,get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet,
            //post与get的 不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            //发送请求参数即数据
            out.print(data);
            //缓冲数据
            out.flush();
            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            //构造一个字符流缓存
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String str = "";
            while ((str = br.readLine()) != null) {
            	openId=str;
                System.out.println(str);
            }
            //关闭流
            is.close();
            //断开连接,最好写上,disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
            //固定多线程的话,如果不disconnect,链接会增多,直到收发不出信息。写上disconnect后正常一些。
            conn.disconnect();
            System.out.println("完整结束");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return openId;
    }
    public static String GetOpenID(String appid,String appsecret,String Code) {
    	//临时登录凭证
    	String URL = "https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+appsecret+"&js_code="+Code+"&grant_type=authorization_code";
    	String openId=interfaceUtil(URL, "");
    	return openId;
    }
}

 

展开阅读全文

没有更多推荐了,返回首页