java 开发第三方微信接口

对于第三方的登陆,qq,微信,微博已经受到了广大用户的欢迎,今天实现了一下基于微信的第三方登陆 。

   对于第三方微信登陆 前期准备:

   1、首先需要注册一个微信公众号:mp.weixin.com

    2、完成用户认证等一系列操作(在此我就不再一一演示)

    3、获得自己的   AppID(应用ID)
                                 AppSecret(应用密钥)

4、废话不多说就是开始干

   工具类:

AuthUtil:

   public static final String APPID="你自己的哦";
    public static final String APPSECRET="你自己的哦";
    public static JSONObject doGetJson(String url) throws ClientProtocolException, IOException {
        JSONObject jsonObject= null;
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet httpGet= new HttpGet(url);
        HttpResponse response =client.execute(httpGet);
        HttpEntity entity =response.getEntity();
        if (entity != null) {
            String result = EntityUtils.toString(entity,"UTF-8");
            jsonObject=JSONObject.fromObject(result);    
        }
        httpGet.releaseConnection();
        return jsonObject;
    }

登陆拦截

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TODO Auto-generated method stub
    String backUrl="公网服务器的ip地址/WxAuth/callBack";
        String url="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+AuthUtil.APPID
                +"&redirect_uri="+URLEncoder.encode(backUrl)
                +"&response_type=code&scope=snsapi_userinfo"
                + "&state=STATE#wechat_redirect";
        
        resp.sendRedirect(url);


回调地址

String code = req.getParameter("code");
    String url =" https://api.weixin.qq.com/sns/oauth2/access_token?appid="+AuthUtil.APPID
             + "&secret="+AuthUtil.APPSECRET
             + "&code="+code
             + "&grant_type=authorization_code ";
    
    net.sf.json.JSONObject jsonObject =AuthUtil.doGetJson(url);
    String openid =jsonObject.getString("openid");
    String token =jsonObject.getString("access_token");
     String infoUrl =" https://api.weixin.qq.com/sns/userinfo?access_token="+token
           + "&openid="+openid
             + "&lang=zh_CN ";
     net.sf.json.JSONObject userInfo=AuthUtil.doGetJson(infoUrl);
     System.out.println(userInfo);


好了,到此就可以在浏览器访问了。

如有不懂的请留言。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值