微信小程序根据code获取openid

public R queryOpenId(@RequestParam String code) {
    String codeUrl = String.format("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", APPID, APPSECRET, code);
    HttpGet request = new HttpGet(codeUrl);
    // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    // 响应模型
    CloseableHttpResponse response = null;
    String openId = null;
    OpenIdForm result = null;
    try {
        // 由客户端执行(发送)Get请求
        response = httpClient.execute(request);
        // 从响应模型中获取响应实体
        HttpEntity responseEntity = response.getEntity();
        String body = EntityUtils.toString(responseEntity);
        log.debug("响应状态为:" + response.getStatusLine());
        log.debug("响应内容为:" + body);
        OpenIdForm openIdForm = JSONObject.parseObject(body, OpenIdForm.class);
        if (StringUtils.isNotEmpty(openIdForm.getOpenid())) {
            openId = openIdForm.getOpenid();
            result = openIdForm;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        HttpContextUtils.close(response);
        HttpContextUtils.close(httpClient);
    }
    //openid为空
    if (StringUtils.isEmpty(openId)) {
        return R.error();
    }
    DesignerEntity user = designerService.getOne(new QueryWrapper<DesignerEntity>().eq("openId",openId));
    return R.ok().put("openId",openId).put("user",user).put("result",result);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值