java微信开发-OAuth2.0授权

1、配置web环境

这里使用springMVC配置,参照”java微信开发-springMVC配置”

2、给用户发现以下地址

public static String getOAuthUrl() {
        StringBuffer weixin_auth_url = new StringBuffer();
        weixin_auth_url.append("https://open.weixin.qq.com/connect/oauth2/authorize?" 
                + "appid=" + 公众号appID
                + "&redirect_uri=" + 回调地址
                + "&response_type=code&scope=snsapi_base&state=123#wechat_redirect");
        // "response_type=code&scope=snsapi_userinfo&state=authorize#wechat_redirect");
    return weixin_auth_url.toString();

注:

参数必须说明
appid公众号的唯一标识
redirect_uri授权后重定向的回调链接地址,请使用urlencode对链接进行处理
response_type返回类型,请填写code
scope应用授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且,即使在未关注的情况下,只要用户授权,也能获取其信息)
state重定向后会带上state参数,开发者可以填写a-zA-Z0-9的参数值,最多128字节
#wechat_redirect无论直接打开还是做页面302重定向时候,必须带此参数

3、处理回调请求

/**
     * 根据用户code,获取openID
     * @param request
     * @return
     */
    @RequestMapping("/hello/redirect")
    public String redirectFun(HttpServletRequest request){
        //根据微信code获取用户openID
        String openID = OAuth.getOpenIdByCode(request);
        if("".equals(openID)){
            System.out.println("获取微信用户openID失败");
        }else{
            request.setAttribute("openId", openID);
        }
        System.out.println(openID);
        return "hello";
    }

OAuth类

package OAuth2;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.SpringMVC.web.controller.MessageUtil;

/**
 * 微信网页授权
 * 
 * @author 32950745
 *
 */
public class OAuth {
    /**
     * 得到openID
     * 
     */

    public static String getOpenIdByCode(HttpServletRequest request){
        String openID = "";
        HttpClientCommon http = new HttpClientCommon();
        String code = request.getParameter("code");
        if(code == null || "".equals(code)){
            return openID;
        }else{
            //利用code获取openID
            StringBuffer access_token_url = new StringBuffer();
            access_token_url.append("https://api.weixin.qq.com/sns/oauth2/access_token?");
            //非静默授权时
            //access_token_url.append("https://api.weixin.qq.com/sns/userinfo?")
            access_token_url.append(
                    "appid="+微信公众号appID+
                    "&secret="+微信公众号appsecret+
                    "&code="+code+
                    "&grant_type=authorization_code"
                    );
            try{
                @SuppressWarnings({ "rawtypes" })
                Map tokenMap = http.HttpGet(access_token_url.toString());
                System.out.println("tokenMap:"+tokenMap);
                if(tokenMap != null && tokenMap.containsKey("openid")){
                    openID = (String)tokenMap.get("openid");
                }
            }catch(Exception e){
            }
        }
        return openID;
    }
}

HttpClientCommon 类

package OAuth2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;

public class HttpClientCommon {

    public Map HttpGet(String url) throws Exception {
        String result = "";
        try{
            result = sendRequest(url,null,"GET");
        }catch(Exception e){
            throw e;
        }
        Map map = JsonUtils.getMap(result);
        if(map == null || map.get("errcode") != null){
            System.out.println("HttpClientCommon类的HttpGet方法出错");
        }else{
            return map;
        }
        return null;
    }

    private String sendRequest(String url, String content, String method) throws IOException {
        URL sendUrl = new URL(url);
        System.out.println("url:"+url);
        StringBuilder sbf = new StringBuilder();
        HttpURLConnection http = (HttpURLConnection)sendUrl.openConnection();
        //设置请求方式
        http.setRequestMethod(method);
        //url连接可以用于输入输出
        http.setDoInput(true);
        http.setDoOutput(true);
        http.setRequestProperty("Content-Type", "application/json");
        http.setRequestProperty("Content-Type", "application/json");
        http.setRequestProperty("Content-Type", "application/json");
        //设置头
        //http.addRequestProperty(method, "/ HTTP/1.1");
        if("POST".equals(method)){
            //设置包体
            http.getOutputStream().write(content.getBytes("utf-8"));
            http.getOutputStream().flush();
            http.getOutputStream().close();
        }
        //取得返回值
        InputStream in = http.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"));
        String line = null;
        while((line = reader.readLine()) != null){
            sbf.append(line);
        }
        return sbf.toString();
    }
}

JsonUtils类

package OAuth2;
import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONObject;

/**
 * 该类负责JSON字符串与对象的互相转化
 * @author 32950745
 *
 */
public class JsonUtils {
    /**
     * 防止实例化
     */
    private JsonUtils(){
    }

    /**
     * 字符串转换为map
     * @param result
     * @return
     */
    public static Map getMap(String jsonString) {
        return (Map)JSONObject.toBean(JSONObject.fromObject(jsonString), HashMap.class);
    }   
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值