欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

第三方登录-微信登录

程序员文章站 2022-03-25 13:22:13
...

第三方微信登录

官方地址文档

微信开放平台地址

第三方登录-微信登录

第三方登录-微信登录
微信登录官方文档

微信工具类

WXUtils-工具类


package cn.com.hwqh.user.config;

import cn.com.hwqh.user.entity.model.OAuthInfo;
import cn.com.hwqh.user.entity.model.WxUser;
import cn.com.hwqh.user.util.JacksonUtils;
import cn.com.hwqh.user.util.utility.HttpRequestUtil;
import cn.com.hwqh.util.FastJsonHelper;
import cn.com.hwqh.util.MyConfiguration;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;


/**
 * @ClassName: WXUtils
 * @version: 1.0
 * @description:
 * @author: zhaonian
 * @create: 2020-01-07 14:17
 **/
public class WXUtils {
    /**
     * wx.appid
     */
    public static final String WX_APPID = MyConfiguration.create().getString("wx.appid");

    /**
     * wx.secret
     */
    public static final String WX_SECRET = MyConfiguration.create().getString("wx.secret");

    /**
     * wx.REDIRECT_URI
     */
    public static final String REDIRECT_URI = MyConfiguration.create().getString("wx.redirect_uri");
    static Long expires_in;
    static String refreshToken;
    static String scope;

    /**
     * 获取access_token
     */
    public static OAuthInfo getAccessToken(String code) {
        String authUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code ";
        authUrl = authUrl.replace("APPID", WXUtils.WX_APPID);
        authUrl = authUrl.replace("SECRET", WXUtils.WX_SECRET);
        authUrl = authUrl.replace("CODE", code);
        String jsonString = HttpRequestUtil.sendPost(authUrl, "");
        System.out.println("jsonString: " + jsonString);
        OAuthInfo auth = null;
        try {
            auth = (OAuthInfo) JacksonUtils.readValue(jsonString, OAuthInfo.class);
            expires_in = auth.getExpires_in();
            refreshToken = auth.getRefresh_token();
            scope = auth.getScope();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return auth;
    }


    /**
     * WX_APPID: 微信开发者测试账号
     * REDIRECT_URI: 同意授权后跳转的 URL
     * 第一步:用户同意授权,获取code(引导关注者打开如下页面:)
     * 获取 code、state
     */
    public static String getStartURLToGetCode() {
        String takenUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";
        takenUrl = takenUrl.replace("APPID", WXUtils.WX_APPID);
//        takenUrl= takenUrl.replace("REDIRECT_URI", URL.encode(WXUtils.REDIRECT_URI,"UTF-8"));
        //FIXME : snsapi_userinfo
        takenUrl = takenUrl.replace("SCOPE", "snsapi_userinfo");
        System.out.println(takenUrl);
        return takenUrl;
    }

    /**
     * 获取用户信息
     */
    public static WxUser getUserInfo(String accessToken,String openID,Long expires_in) {
        if (isAccessTokenIsInvalid(accessToken,openID) ) {
            String uri = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openID;
            HttpClient client = new DefaultHttpClient();
            HttpGet get = new HttpGet(URI.create(uri));
            try {
                HttpResponse response = client.execute(get);
                if (response.getStatusLine().getStatusCode() == 200) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
                    StringBuilder builder = new StringBuilder();
                    for (String temp = reader.readLine(); temp != null; temp = reader.readLine()) {
                        builder.append(temp);
                    }
                    WxUser wxUser = FastJsonHelper.jsonDecode(builder.toString(), WxUser.class);
                    return wxUser ;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return  new WxUser();
    }

    /**
     * 检验授权凭证(access_token)是否有效
     *
     * @return
     */
    private static boolean isAccessTokenIsInvalid(String accessToken, String openID) {
        String url = "https://api.weixin.qq.com/sns/auth?access_token=" + accessToken + "&openid=" + openID;
        URI uri = URI.create(url);
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(uri);
        HttpResponse response;
        try {
            response = client.execute(get);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();

                BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
                StringBuilder sb = new StringBuilder();

                for (String temp = reader.readLine(); temp != null; temp = reader.readLine()) {
                    sb.append(temp);
                }
                JSONObject object = new JSONObject(sb.toString().trim());
                int errorCode = object.getInt("errcode");
                if (errorCode == 0) {
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}

相关标签: 微信开放平台