APP调用微信授权登录之服务端开发

个人技术网站 欢迎关注

一直在做微信支付 微信授权登录这块的APP接口 现在提供一个写好的微信授权service类给大家参考

 

 

import com.pojo.wechat.UserInfoData;
import com.utils.ConfigUtil;
import com.utils.https.HttpClientUtil;
import org.apache.commons.lang.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * APP调用微信授权获取用户信息
 * Created by LaoWang on 2017/11/11.
 */
@Service("WeiXinAuthService")
public class WeiXinAuthService {
    private static final Logger logger = LoggerFactory.getLogger(WeiXinAuthService.class);

    public static final String WX_AUTH_LOGIN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token";
    public static final String WX_USERINFO_URL = "https://api.weixin.qq.com/sns/userinfo";
    public static final String WX_ACCESS_INVALID = "https://api.weixin.qq.com/sns/auth";
    public static final String WX_REFREESH_ACCESS = "https://api.weixin.qq.com/sns/oauth2/refresh_token";
    //appid和appSecret 是在公众平台上申请的
    //AppId
    public static final String WX_APP_ID = ConfigUtil.getProperty("wx.appid");
    //AppSecret
    public static final String WX_APP_KEY = ConfigUtil.getProperty("wx.appkey");


    /**
     * 获取用户信息
     * @param code
     * @return
     * @throws JSONException
     */
    public UserInfoData checkLogin(String code) throws JSONException {
        //第一步:获取授权 access_token
        String access_token_url = WX_AUTH_LOGIN_URL+"?appid="+WX_APP_ID+"&secret="+WX_APP_KEY+"&code="+code+"&grant_type=authorization_code";
        //使用Https请求微信API接口
        String loginRet = HttpClientUtil.doGet(access_token_url,"utf-8");
        JSONObject grantObj = new JSONObject(loginRet);
        String errcode = grantObj.optString("errcode");
        if (!StringUtils.isEmpty(errcode)){
            logger.error("login weixin error {}",loginRet);
            return null;
        }
        String openId = grantObj.optString("openid");
        if (StringUtils.isEmpty(openId)){
            logger.error("login weixin getOpenId error {}",loginRet);
            return null;
        }
        String accessToken = grantObj.optString("access_token");
        String expiresIn = grantObj.optString("expires_in");
        String refreshToken = grantObj.optString("refresh_token");
        String scope = grantObj.optString("scope");
        //第二步:获取用户信息
        String getuserinfo_url = WX_USERINFO_URL+"?access_token="+accessToken+"&openid="+openId;
        //使用Https请求微信API接口
        String userRet = HttpClientUtil.doGet(getuserinfo_url,"utf-8");
        JSONObject userObj = new JSONObject(userRet);
        UserInfoData userInfo = new UserInfoData();
        userInfo.setOpenId(openId);
        userInfo.setAccessToken(accessToken);
        userInfo.setRefreshToken(refreshToken);
        userInfo.setScope(scope);
        userInfo.setExpiresIn(Integer.valueOf(expiresIn));
        String nickname = userObj.optString("nickname");
        String sex = userObj.optString("sex");
        String userImg = userObj.optString("headimgurl");
        String unionid = userObj.optString("unionid");
        userInfo.setNickname(nickname);
        userInfo.setUserImg(userImg);
        userInfo.setSex(sex);
        userInfo.setUnionid(unionid);
        return userInfo;
    }

    /**
     * 验证accessToken是否过期
     * @param accessToken
     * @param openID
     * @return
     * @throws JSONException
     */
    public boolean isAccessTokenIsInvalid(String accessToken,String openID) throws JSONException {
        String url = WX_ACCESS_INVALID+"?access_token=" + accessToken + "&openid=" + openID;
        String invalidRet = HttpClientUtil.doGet(url,"utf-8");
        try {
            JSONObject grantObj = new JSONObject(invalidRet);
            String errcode = grantObj.optString("errcode");
            if (!StringUtils.isEmpty(errcode)){
                logger.error("AccessToken Invalid error {}",grantObj);
                return false;
            }
            int errorCode = grantObj.getInt("errcode");
            if (errorCode == 0) {
                return true;
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 刷新refresh_token
     * @param refreshToken
     */
    public UserInfoData refreshAccessToken(String refreshToken) {
        String uri = WX_REFREESH_ACCESS+"?appid=" + WX_APP_ID + "&grant_type=refresh_token&refresh_token="+refreshToken;
        String invalidRet = HttpClientUtil.doGet(uri,"utf-8");
        UserInfoData userInfo = new UserInfoData();
        try {
            JSONObject object = new JSONObject(invalidRet);
            String errcode = object.optString("errcode");
            if (!StringUtils.isEmpty(errcode)){
                logger.error("Refresh AccessToken error {}",object);
                return null;
            }
            userInfo.setOpenId(object.getString("openid"));
            userInfo.setAccessToken(object.getString("access_token"));
            userInfo.setRefreshToken(object.getString("refresh_token"));
            userInfo.setExpiresIn(Integer.valueOf(object.getString("expires_in")));
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return userInfo;
    }
}

 

 

 

具体使用方法请根据项目需求进行更改
 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值