Java 微信公众登录

一、准备工作

1、准备需要的配置参数(APPID、APPSecret)

 2、网页授权域名(位置:公众号设置->功能设置)

 二、代码实现

#微信公众号
wechat:
  appid: 123455667878
  appSecret: aabcdsrdsfdgdfrgtr466446
  #snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid)
  # snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地
  scope: snsapi_base
  authUrl: https://open.weixin.qq.com/connect/oauth2/authorize
 public Result<?> weChatCallback(String code) {
        if (StringUtils.isBlank(code)) {
            return Result.error("");
        }
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid +
                "&secret=" + appSecret +
                "&code=" + code +
                "&grant_type=authorization_code";
        //进行网络请求,访问微信服务器接口
        CmLwcsePaymentUser user = null;
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(NetUtil.get(url));
        try {
            if (null != jsonObject) {
                System.out.println("==========================jsonObject" + jsonObject);
                //从返回的JSON数据中取出access_token和openid,拉取用户信息时用
                //网页授权接口调用凭证
                String accessToken = jsonObject.getString("access_token");
                //用户刷新access_token
                String refresh_token = jsonObject.getString("refresh_token");
                //access_token接口调用凭证超时时间
                String expires_in = jsonObject.getString("expires_in");
                //用户授权的作用域
                String scope = jsonObject.getString("scope");
                //用户唯一标识
                String openid = jsonObject.getString("openid");
                if (StringUtils.isBlank(openid)) {
                    return Result.error("信息有误");
                }
                //业务逻辑
            }
        } catch (Exception e) {
            int errorCode = jsonObject.getInteger("errcode");
            String errorMsg = jsonObject.getString("errmsg");
            log.error("获取网页授权凭证失败 errcode:{} errmsg:{}", errorCode, errorMsg);
            e.printStackTrace();
        }
        return Result.OK(user);
    }


  //获取用户信息
 public static CmLwcsePaymentUser getUserInfo(String accessToken, String openId, CmLwcsePaymentUser snsUserInfo) {
        // 拼接请求地址
        String requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
        requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
        // 通过网页授权获取用户信息
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(NetUtil.get(requestUrl));

        if (null != jsonObject) {
            try {
                snsUserInfo = new CmLwcsePaymentUser();
                // 用户的标识
                snsUserInfo.setOpenId(jsonObject.getString("openid"));
                // 昵称
                snsUserInfo.setNickName(jsonObject.getString("nickname"));
                // 性别(1是男性,2是女性,0是未知)
                snsUserInfo.setSex(jsonObject.getInteger("sex"));
                // 用户所在国家
                snsUserInfo.setCountry(jsonObject.getString("country"));
                // 用户所在省份
                snsUserInfo.setProvince(jsonObject.getString("province"));
                // 用户所在城市
                snsUserInfo.setCity(jsonObject.getString("city"));
                // 用户头像
                snsUserInfo.setHeadImgUrl(jsonObject.getString("headimgurl"));

                //与开放平台共用的唯一标识,只有在用户将公众号绑定到微信开放平台帐号后,才会出现该字段。
                snsUserInfo.setUnionId(jsonObject.getString("unionid"));
            } catch (Exception e) {
                snsUserInfo = null;
                int errorCode = jsonObject.getInteger("errcode");
                String errorMsg = jsonObject.getString("errmsg");
                log.error("获取用户信息失败 errcode:{} errmsg:{}", errorCode, errorMsg);
            }
        }
        return snsUserInfo;
    }

工具类:

public final class NetUtil {
    public static CloseableHttpClient httpClient = HttpClientBuilder.create().build();

    /**
     * get请求获取String类型数据
     * @param url 请求链接
     * @return
     */
    public static String get(String url){
        StringBuffer sb = new StringBuffer();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response = httpClient.execute(httpGet);           //1

            HttpEntity entity = response.getEntity();
            InputStreamReader reader = new InputStreamReader(entity.getContent(),"utf-8");
            char [] charbufer;
            while (0<reader.read(charbufer=new char[10])){
                sb.append(charbufer);
            }
        }catch (IOException e){//1
            e.printStackTrace();
        }finally {
            httpGet.releaseConnection();
        }
        return sb.toString();
    }

参考微信公众号开发文档:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html

注意事项:

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值