微信网页开发之授权登录(java实现)


建议先去查看微信开发官方文档:
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842

第一步:用户同意授权,获取code

  • 前台通过请求链接https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
    可以获取到code。

  • code说明 : code作为换取access_token的票据,每次用户授权带上的code将不一样,code只能使用一次,5分钟未被使用自动过期。

第二步:通过code换取网页授权access_token

  • 获取code后,请求以下链接获取access_token: https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
  • 正确时返回的JSON数据包如下:
    {
    “access_token”:“ACCESS_TOKEN”,
    “expires_in”:7200,
    “refresh_token”:“REFRESH_TOKEN”,
    “openid”:“OPENID”,
    “scope”:“SCOPE”
    }
  • controller层代码实现
/**
     * 微信浏览器获取用户信息
     * @param code
     * @param state
     * @return
     */
    @GetMapping(value = "/userInfo",produces = "text/html;charset=utf-8")
    public String getUserInformation(String code, String state, HttpServletRequest request) {
        TbUser tbUser = new TbUser();
        if (StringUtils.isEmpty(code)){
            return resultError("code为空");
        }
        JSONObject jsonData = WeixinSign.getAccessToken(code);
        String openid = jsonData.getString("openid");
        String access_token = jsonData.getString("access_token");
        String refresh_token = jsonData.getString("refresh_token");
        HttpSession session = request.getSession();

        //验证access_token是否失效
        JSONObject validateData = WeixinSign.getValidateData(access_token, openid);
        if (!"0".equals(validateData.getString("errcode"))){
            //刷新access_token
            JSONObject refreshData= WeixinSign.getRefreshToken(refresh_token);
            access_token = refreshData.getString("access_token");
        }
        JSONObject userData = null;
        try {
            //拉取用户信息
            userData = WeixinSign.getUserInfo(access_token, openid);
            Object unionid = userData.get("unionid");
            Object nickName = userData.get("nickname");
            Object headimgurl = userData.get("headimgurl");
            Object sex = userData.get("sex");
            if (!StringUtils.isEmpty(unionid)) {
                //用户是否注册过
                tbUser = tbUserService.selectByUnionid(unionid.toString());
                if (StringUtils.isEmpty(tbUser)) {
                    tbUser = new TbUser();
                    String userId = UUID.randomUUID().toString().replace("-", "");
                    tbUser.setId(userId);
                    if (!StringUtils.isEmpty(nickName)){
                        tbUser.setNickname(nickName.toString());
                    }
                    if (!StringUtils.isEmpty(headimgurl)){
                        tbUser.setHeadimgUrl(headimgurl.toString());
                    }
                    if (!StringUtils.isEmpty(sex)){
                        tbUser.setSex(new Byte(sex.toString()));
                    }
                    tbUser.setCreateTime(new Date());
                    tbUser.setUnionid(unionid.toString());
                    tbUserService.insertUser(tbUser);
                }

            }
        } catch (Exception e) {
            logger.error("获取用户信息异常:"+e.getMessage());
            return resultError("获取用户信息异常");
        }
        Map map=new HashMap();
        map.put("id",tbUser.getId());
        map.put("unionid",tbUser.getUnionid());
        map.put("headimgUrl",tbUser.getHeadimgUrl());
        map.put("nickname",tbUser.getNickname());
        map.put("sex",tbUser.getSex());
        map.put("province",userData.get("province").toString());
        map.put("city",userData.get("city").toString());
        map.put("openid",userData.get("openid").toString());
        map.put("sessionid",getSession().getId());
        return resultSuccess(map);
    }
  • 微信工具类WeixinSign
package com.sjyx.contest.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class WeixinSign {

	/**
	 * 网页
	 */
	public static String wy_appid = "wxdee18320bb16f695";
	public static String wy_secret = "85a6c0d7fdb86f59c386dc99b8a5f3ec";

    public static JSONObject getAccessToken(String code){
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?";
		String params = "appid="+wy_appid+"&secret="+wy_secret+"&code="+code+"&grant_type=authorization_code";
		String result = HttpRequestUtil.httpGet(url + params);
		JSONObject data = JSON.parseObject(result);

		return data;
	}

	public static JSONObject getValidateData(String access_token,String openid){
		String url = "https://api.weixin.qq.com/sns/auth?access_token=" + access_token + "&openid=" + openid;
		String result = HttpRequestUtil.httpGet(url);
		JSONObject data = JSON.parseObject(result);

		return data;
	}

	public static JSONObject getRefreshToken(String refresh_token){
		String url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + wy_appid + "&grant_type=refresh_token&refresh_token=" + refresh_token;
		String result = HttpRequestUtil.httpGet(url);
		JSONObject data = JSON.parseObject(result);

		return data;
	}

	public static JSONObject getUserInfo(String access_token,String openid){
		String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN";
		String result = HttpRequestUtil.httpGet(url);
		JSONObject data = JSON.parseObject(result);

		return data;
	}
}
  • Http请求工具类
package com.sjyx.contest.common.utils;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URLDecoder;

public class HttpRequestUtil {  
    private static Logger logger = LoggerFactory.getLogger(HttpRequestUtil.class);    //日志记录
   
   
    /** 
     * post请求 
     * @param url         url地址 
     * @return 
     */  
    public static String httpPost(String url){  
        //post请求返回结果  
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost method = new HttpPost(url);
        String str = "";  
        try {  
            HttpResponse result = httpClient.execute(method);
            url = URLDecoder.decode(url, "UTF-8");  
            /**请求发送成功,并得到响应**/  
            if (result.getStatusLine().getStatusCode() == 200) {  
                try {  
                    /**读取服务器返回过来的json字符串数据**/  
                    str = EntityUtils.toString(result.getEntity(),"UTF-8");
                } catch (Exception e) {  
                    logger.error("post请求提交失败:" + url, e);  
                }  
            }  
        } catch (IOException e) {  
            logger.error("post请求提交失败:" + url, e);  
        }  
        return str;  
    }  
   
   
    /** 
     * 发送get请求 
     * @param url    路径 
     * @return 
     */  
    public static String httpGet(String url){  
        //get请求返回结果  
         String strResult = null;  
        try {  
            DefaultHttpClient client = new DefaultHttpClient();
            //发送get请求  
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);
   
            /**请求发送成功,并得到响应**/  
            if (response.getStatusLine().getStatusCode() == org.apache.http.HttpStatus.SC_OK) {  
                /**读取服务器返回过来的json字符串数据**/  
                  strResult = EntityUtils.toString(response.getEntity(),"UTF-8");
            } else {  
                logger.error("get请求提交失败:" + url);  
            }  
        } catch (IOException e) {  
            logger.error("get请求提交失败:" + url, e);  
        }  
        return strResult;  
    }  
}

第三步:刷新access_token(如果需要)

  • 由于access_token拥有较短的有效期,当access_token超时后,可以使用refresh_token进行刷新,refresh_token有效期为30天,当refresh_token失效之后,需要用户重新授权。
  • 获取第二步的refresh_token后,请求以下链接获取access_token:
    https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN
  • 正确时返回的JSON数据包如下:
    {
    “access_token”:“ACCESS_TOKEN”,
    “expires_in”:7200,
    “refresh_token”:“REFRESH_TOKEN”,
    “openid”:“OPENID”,
    “scope”:“SCOPE”
    }

第四步:拉取用户信息(需scope为 snsapi_userinfo)

  • 如果网页授权作用域为snsapi_userinfo,则此时开发者可以通过access_token和openid拉取用户信息了。
  • 请求方法

http:GET(请使用https协议) https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN

  • 参数 描述
    access_token: 网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同
    openid:用户的唯一标识
    lang: 返回国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语
  • 正确时返回的JSON数据包如下:
    {
    “openid”:" OPENID",
    " nickname": NICKNAME,
    “sex”:“1”,
    “province”:“PROVINCE”
    “city”:“CITY”,
    “country”:“COUNTRY”,
    “headimgurl”: “http://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46”,
    “privilege”:[ “PRIVILEGE1” “PRIVILEGE2” ],
    “unionid”: “o6_bmasdasdsad6_2sgVt7hMZOPfL”
    }
  • 具体代码第二步已给出

附:检验授权凭证(access_token)是否有效

  • 请求方法

http:GET(请使用https协议) https://api.weixin.qq.com/sns/auth?access_token=ACCESS_TOKEN&openid=OPENID

  • 参数 描述
    access_token: 网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同
    openid: 用户的唯一标识
  • 正确的JSON返回结果:

{ “errcode”:0,“errmsg”:“ok”}

  • 1
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
您好!对于H5网页微信授权登录,您可以使用Java开发语言来实现。下面是一个简单的示例代码,帮助您理解如何在Java中进行微信授权登录: ```java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class WeChatLogin { public static void main(String[] args) throws IOException { // 获取授权登录的code String code = getAuthorizationCode(); // 通过code获取access_token和openid String appId = "your_app_id"; String appSecret = "your_app_secret"; String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appId + "&secret=" + appSecret + "&code=" + code + "&grant_type=authorization_code"; String accessTokenResponse = sendGetRequest(accessTokenUrl); // 解析access_token和openid String accessToken = parseJsonValue(accessTokenResponse, "access_token"); String openid = parseJsonValue(accessTokenResponse, "openid"); // 使用access_token和openid进行业务逻辑处理 // ... System.out.println("Access Token: " + accessToken); System.out.println("OpenID: " + openid); } private static String getAuthorizationCode() { // 在此处实现获取授权登录的code的逻辑 // ... return "authorization_code"; } private static String sendGetRequest(String url) throws IOException { URL getUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection(); connection.setRequestMethod("GET"); connection.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); return response.toString(); } private static String parseJsonValue(String json, String key) { // 在此处实现解析JSON中指定key的value的逻辑 // ... return "value"; } } ``` 请注意,这只是一个简单的示例代码,实际实现中您需要根据自己的需求进行修改和完善。另外,您需要替换代码中的`your_app_id`和`your_app_secret`为您在微信开放平台申请的真实App ID和App Secret。 希望这个示例对您有所帮助!如果您有其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

07feng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值