java通过微信授权获取用户信息

本文介绍了如何在Java应用中通过微信授权来获取用户信息。首先,设置好常量类或配置文件,接着请求获取授权code,由于直接在代码中跳转未成功,建议通过返回页面来实现用户的授权跳转。
摘要由CSDN通过智能技术生成

首先准备好常量类,当然也可以写到配置文件里

/**
 * 
 * 功能描述: 公用封装方法 <br/>
 * date: 2017-7-24 下午5:18:58 <br/>
 * lk
 */
public interface Constant {
    // 凭证获取(GET)
    public final static String TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";

    // 用户同意授权,获取code
    public final static String WX_OAUTH_URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";
    
    // 用户同意授权,回调url
    public final static String WX_REDIRECT_URL = "回调url";
    
    // 拉去用户信息url
    public final static String WX_SNSAPI_URL = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
    
    //微信openId
    public final static String WX_OPEN_ID = "公众好id";
    
    //微信appSecret
    public final static String WX_APP_SECRET = "appSecret";
}
然后需要几个工具类

/**
 * 
 * 功能描述: 公用封装方法 <br/>
 * date: 2017-7-24 下午5:18:58 <br/>
 * lk
 */
public class CommonMethod {
    /**
     * 获取接口访问凭证
     * 
     * @param appid 凭证
     * @param appsecret 密钥
     * @return
     */
    public static Token getToken(String appid, String appsecret, String code) {
        Token token = null;
        String requestUrl = Constant.TOKEN_URL.replace("APPID", appid).replace("SECRET", appsecret).replace("CODE", code);
        // 发起GET请求获取凭证
        net.sf.json.JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);


        if (null != jsonObject) {
            try {
                token = new Token();
                token.setAccessToken(jsonObject.getString("access_token"));
                token.setExpiresIn(jsonObject.getInt("expires_in"));
                token.setOpenId(jsonObject.getString("openid"));
            } catch (JSONException e) {
                token = null;
                // 获取token失败
                System.out.println("获取token失败");
                e.printStackTrace();
  
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值