微信小程序获取获取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然后返回前段就好了

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值