JAVA微信开发(一), 微信授权登录

JAVA微信开发(一), 微信授权登录

      • 感谢开源社区大佬们的无私奉献,谢谢!!

证实过可以用的微信授权登陆2020.04.18

1.__开发前先从公众号查出APPID和APPSECRE
2.注册url的域名: 公众号-设置-公众号设置-功能设置
3.注册的url是你的项目根路径,不是回调路径
4.一般将MP_*****.txt放在web或webapp中,微信会从注册的url中找到这个文件
JAVA微信开发(一), 微信授权登录_第1张图片


第一步:用户同意授权,请求微信获取code


import java.net.URLEncoder;


private static final String APP_ID = "wx***********";    //填写自己公众号的APPID
private static final String APP_SECRET = "c22************";   //填写自己公众号的APPSECRE

 /**
     * 公众号微信登录授权
     *
     * @return
     * @throws Exception
     * @parameter
     */
    @RequestMapping("/wxLogin")
    public void wxLogin(HttpServletResponse response) throws Exception {

        

        // 这个url的域名必须要进行再公众号中进行注册验证,这个地址是成功后的回调地址
        String backUrl = "https://项目访问路径/controller层/callBack";

        // 第一步:用户同意授权,请求微信获取code
        String getCodeUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + APP_ID
                + "&redirect_uri=" + URLEncoder.encode(backUrl)
                + "&response_type=code" + "&scope=snsapi_userinfo"
                + "&state=STATE#wechat_redirect";

        //重定向到微信服务器
        response.sendRedirect(getCodeUrl);


    }

第二步:通过code换取网页授权access_token
第三步:刷新access_toke-暂时用不上
第四步:拉取用户信息


import com.alibaba.fastjson.JSONObject;

/**
     * 公众号微信登录授权回调函数
     *
     * @return
     * @throws Exception
     * @parameter
     */
    @RequestMapping("/callBack")
    @ResponseBody
    public void callBack(HttpServletRequest request, HttpServletResponse response) throws Exception {	
	//接收微信服务器返回的code
        String code = request.getParameter("code");

        // 第二步:通过code换取网页授权access_token
        String getTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APP_ID + "&secret="
                + APP_SECRET + "&code=" + code + "&grant_type=authorization_code";

        JSONObject getTokenJson = AuthUtil.doGetJson(getTokenUrl);
         String openid = getTokenJson.getString("openid");
        String access_token = getTokenJson.getString("access_token");
        String refresh_token = getTokenJson.getString("refresh_token");

        // 第五步验证access_token是否失效;展示都不需要
        String vlidTokenUrl = "https://api.weixin.qq.com/sns/auth?access_token=" + access_token + "&openid=" + openid;
        JSONObject validTokenJson = AuthUtil.doGetJson(vlidTokenUrl);
        

        if (!"0".equals(validTokenJson.getString("errcode"))) {
            // 第三步:刷新access_token(如果需要)-----暂时没有使用,参考文档https://mp.weixin.qq.com/wiki,
            String refreshTokenUrl = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid="
                    + openid + "&grant_type=refresh_token&refresh_token=" + refresh_token;
            JSONObject refreshTokenJson = AuthUtil.doGetJson(refreshTokenUrl);
                     access_token = refreshTokenJson.getString("access_token");
        }

        // 第四步:拉取用户信息(需scope为 snsapi_userinfo)
        String getUserInfoUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="
                + Getaccess_token.postToken(APP_ID, APP_SECRET)
                + "&openid=" + openid + "&lang=zh_CN";
        JSONObject wxUserInfoJson = AuthUtil.doGetJson(getUserInfoUrl);
  System.out.println("获取用户信息,wxUserInfoJson=" + wxUserInfoJson.toString());
        /*
         * end 获取微信用户基本信息
         */

        // 、判断是否关注
        if ("0".equals(wxUserInfoJson.getString("subscribe"))) {
            // 没有关注重定向到关注页面
            response.sendRedirect(
                    "https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzU5Mjk2MDkzOA==&scene=124#wechat_redirect");
        }

		//关注了转发到指定页面,例如index
        request.getRequestDispatcher("/index").forward(request, response);


        // 接来的业务逻辑请自由发挥
        /**
         *
         */
         
    }

用到的工具类


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

/**
 * 
 * 工具类
 * 用来根据接口地址进行网络请求
 * @author 
 *
 */
public class AuthUtil {
    public static JSONObject doGetJson(String url) throws Exception {
    	JSONObject jsonObject = null;
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            // 把返回的结果转换为JSON对象
            String result = EntityUtils.toString(entity, "UTF-8");
            jsonObject = JSON.parseObject(result);
        }
        return jsonObject;

    }

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class Getaccess_token {
	/**
	 * 用于获取access_token
	 * 
	 * @param appid
	 * @param secret
	 * @return
	 * @throws IOException
	 */
	public static String postToken(String appid, String secret) throws IOException {
		String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid
				+ "&secret=" + secret;
		// 打开和URL之间的连接
		URL url = new URL(requestUrl);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setRequestMethod("POST");
		// 设置通用的请求属性
		connection.setRequestProperty("Content-Type", "application/json");
		connection.setRequestProperty("Connection", "Keep-Alive");
		connection.setUseCaches(false);
		connection.setDoOutput(true);
		connection.setDoInput(true);

		// 得到请求的输出流对象
		DataOutputStream out = new DataOutputStream(connection.getOutputStream());
		out.writeBytes("");
		out.flush();
		out.close();

		// 建立实际的连接
		connection.connect();
		// 定义 BufferedReader输入流来读取URL的响应
		BufferedReader in = null;
		if (requestUrl.contains("nlp"))
			in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "GBK"));
		else
			in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
		String result = "";
		String getLine;
		while ((getLine = in.readLine()) != null) {
			result += getLine;
		}
		in.close();
		JSONObject jsonObject = JSON.parseObject(result);
		String accesstoken = jsonObject.getString("access_token");
		return accesstoken;
	}
}

感谢开源社区大佬们的无私奉献,谢谢!!

你可能感兴趣的:(java微信开发)