初步实现微信授权登录可以按自己的需求进行修增

package com.ltdd.hall.biz.api.controller;


import com.alibaba.fastjson.JSON;
import com.ltdd.core.domain.RestResponse;
import com.ltdd.core.exception.BizException;
import com.ltdd.hall.common.util.RestUtile;
import com.ltdd.hall.dal.biz.dataobject.HotCityDO;
import com.ltdd.hall.dal.biz.dataobject.WxOauth2TokenDO;
import com.ltdd.hall.dal.biz.dataobject.WxUserInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

@Api(value = "WX", description = "微信相关文档")
@RestController
@RequestMapping("/wx")
@Slf4j
@Validated
public class WxController {

//    @ApiOperation(value = "test微信", httpMethod = "GET")
//    @RequestMapping(value = "/hotCity", method = RequestMethod.GET)
//    public RestResponse<HotCityDO> hotCity(@RequestParam("id")String id) {
//        HotCityDO hotCityDO = stationService.getInfo(id);
//        return RestResponse.succ("历史城市详情查询成功",hotCityDO);
//    }
        @ApiOperation(value = "test微信", httpMethod = "GET")
        @RequestMapping("/authorize")
        public ModelAndView alipayforward(HttpServletRequest req, HttpServletResponse resp) throws Exception {
              String uri = urlEncodeUTF8("http://xxxxxxx.com/wx/notifyLogin");
              String appid ="wxfcd7cd841cxxxxxx";
              String urlNameString = "redirect:https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri="+uri+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
              return new ModelAndView(urlNameString);

        }
    /**
          * URL编码(utf-8)
           *
           * @param source
           * @return
     */
    public static String urlEncodeUTF8(String source) {
       String result = source;
        try {
               result = java.net.URLEncoder.encode(source, "utf-8");
            } catch (UnsupportedEncodingException e) {
                 e.printStackTrace();
        }
        return result;
    }
//    @ApiOperation(value = "微信回调", httpMethod = "GET")
    @RequestMapping(value = "/notifyLogin", method = RequestMethod.GET)
    public RestResponse<WxUserInfo> notifyLogin(HttpServletRequest request,HttpServletResponse response) throws Exception {
        Map<String, String[]> params = request.getParameterMap();//针对get获取get参数
        String[] codes = params.get("code");//拿到code的值
       // String[] codes = {"021PeKh62lFEbR0GoCe62d9Dh62PeKhG"};
        String code = codes[0];
        WxOauth2TokenDO oauth2Token = this.getOauth2AccessToken("wxfcd7cd84xxxxxx", "f627e014e7d7xxxxxxfa77a2axxxxx", code);
        // 网页授权接口访问凭证
        String accessToken = oauth2Token.getAccessToken();
        // 用户标识
        String openId = oauth2Token.getOpenId();
        WxUserInfo snsUserInfo = this.getSNSUserInfo(accessToken,openId);
        return RestResponse.succ("历史城市详情查询成功",snsUserInfo);
    }

    public static WxOauth2TokenDO   getOauth2AccessToken(String appId, String appSecret, String code) throws Exception {
        WxOauth2TokenDO wat = null;
        // 拼接请求地址
        String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token";
        // 获取网页授权凭证
        String query = "appid="+appId+"&secret="+appSecret+"&code="+code+"&grant_type=authorization_code";
        RestUtile restUtil = new RestUtile();
        String resultString = restUtil.load(requestUrl,query);
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(resultString);
        if (null != jsonObject) {
            try {
                wat = new WxOauth2TokenDO();
                wat.setAccessToken(jsonObject.getString("access_token"));
                wat.setExpiresIn(jsonObject.getInteger("expires_in"));
                wat.setRefreshToken(jsonObject.getString("refresh_token"));
                wat.setOpenId(jsonObject.getString("openid"));
                wat.setScope(jsonObject.getString("scope"));
            } catch (Exception e) {
                wat = null;
                int errorCode = jsonObject.getInteger("errcode");
                String errorMsg = jsonObject.getString("errmsg");

            }
            return wat;
        }
        return wat;
//        if (null != jsonObject) {
//            try {
//                wat = new WxOauth2TokenDO();
//                wat.setAccessToken(jsonObject.getString("access_token"));
//                wat.setExpiresIn(jsonObject.getInteger("expires_in"));
//                wat.setRefreshToken(jsonObject.getString("refresh_token"));
//                wat.setOpenId(jsonObject.getString("openid"));
//                wat.setScope(jsonObject.getString("scope"));
//            } catch (Exception e) {
//                wat = null;
//                int errorCode = jsonObject.getInteger("errcode");
//                String errorMsg = jsonObject.getString("errmsg");
//
//            }
//        }
//        return wat;
    }


    public WxUserInfo getSNSUserInfo(String accessToken, String openId) throws Exception {
        WxUserInfo snsUserInfo = null;
        // 拼接请求地址
      //  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));


        String requestUrl = "https://api.weixin.qq.com/sns/userinfo";
        // 获取网页授权凭证
        String query = "access_token="+accessToken+"&openid="+openId;
        RestUtile restUtil = new RestUtile();
        String resultString = restUtil.load(requestUrl,query);
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(resultString);

        if (null != jsonObject) {
            try {
                snsUserInfo = new WxUserInfo();
                // 用户的标识
                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"));
                // 用户特权信息
                List<String> list = JSON.parseArray(jsonObject.getString("privilege"),String.class);
                snsUserInfo.setPrivilegeList(list);
                //与开放平台共用的唯一标识,只有在用户将公众号绑定到微信开放平台帐号后,才会出现该字段。
                snsUserInfo.setUnionid(jsonObject.getString("unionid"));
            } catch (Exception e) {
                snsUserInfo = null;
                int errorCode = jsonObject.getInteger("errcode");
                String errorMsg = jsonObject.getString("errmsg");

            }
        }
        return snsUserInfo;
    }


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值