微信小程序获取获取openid

之前看很多获取openid都是直接在小程序里面获取的
但是现在不能在小程序里面讲获取openid 的地址加为白名单了
所以只能通过前段传来code 后段获取openid了
微信小程序代码

 /**
   * 生命周期函数--监听页面加载
   * 微信获取openid
   */
  onLoad: function (options) {
    wx.login({
      success: function (res) {
        var code = res.code;//登录凭证
        //console.log(code);
        wx.request({
          url: 'http://域名',  // 获取openid
          data: {
                code: code//传递的code数据
          }
        })
      },
      fail: function () {
        callback(false)
      }
    }); 
  }

后段java获取openid的代码

/**
 * Created by hubo on 2017/11/10
 * openid数据库的操作指令
 */
public class AccessOpenId extends HttpServlet{
    /**
     * 获取用户登陆openid方法
     */
    private static final String APPID = "";   //小程序的APPID
    private static final String APPSECRET = ""; //小程序的appsecret
    private static final String OPENID_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret" +
                                            "=SECRET&js_code=JSCODE&grant_type=authorization_code";//获取openid的地址

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        String Code = req.getParameter("code"); //获取前台传入的参数

        String url = OPENID_URL.replace("APPID",APPID).replace("SECRET",APPSECRET).replace("JSCODE",Code);

        JSONObject jsonObject = WeixinUtil.doGetStr(url);   //调取Get提交方法

        String OpenId = jsonObject.getString("openid"); //获取openid        
    }

}

doget方法代码

/**
     * get请求
     * @param url
     * @return
     */
    public static JSONObject doGetStr(String url){

        DefaultHttpClient httpClient = new DefaultHttpClient();

        HttpGet httpGet = new HttpGet(url);

        JSONObject jsonObject = null;

        try {
            HttpResponse response = httpClient.execute(httpGet);

            HttpEntity entity = response.getEntity();   //接受结果
            if(entity != null){
                String result = EntityUtils.toString(entity,"UTF-8");
                jsonObject = JSONObject.fromObject(result);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

获取的opneid就是openid然后返回前段就好了

你可能感兴趣的:(微信小程序)