通过微信公众号获取用户信息(java版)

时间:2024-02-23 12:05:05

最近由于公司业务,就开始研究微信开发的流程,说实话,这东西刚开始看到时候和看天书的一样,总算,看了一天的文档,测试代码终于出来了。

1、首先需要到微信网站去设置一下,我是直接用的微信测试号。

          接口配置信息必须要填写的,所以说必须能将自己的服务发布出去

               

 

                    

 

            

            

 

                             到此微信配置完毕,接下来就是直接上代码了

2、获取用户信息的方式一共是两种,测试号必须关注微信公众号,正式的不用,一种是静默获取(snsapi_base,这种方式只能获取openid),另一种是授权获取(snsapi_userinfo,可以获取用户的详细信息)。

      先说第一种

  (1)首先需要先访问微信的链接

    https://open.weixin.qq.com/connect/oauth2/authorize?appid=xxxxxxxxxxxxxxxx&redirect_uri=http://xxxxxx/open/openid&response_type=code&scope=snsapi_base

           这里的 uri就是直接回掉我们的服务地址,一定要记住,服务校验的判断,我是按照来判断的echostr(第二种方式也是这样)

 1 package net.itraf.controller;
 2 
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5 import java.io.PrintWriter;
 6 import java.net.HttpURLConnection;
 7 import java.net.MalformedURLException;
 8 import java.net.URL;
 9 
10 import javax.servlet.http.HttpServletResponse;
11 
12 import org.springframework.stereotype.Controller;
13 import org.springframework.web.bind.annotation.RequestMapping;
14 import org.springframework.web.bind.annotation.ResponseBody;
15 
16 import com.alibaba.fastjson.JSONObject;
17 
18 @Controller
19 @RequestMapping("/open")
20 public class OpenController {
21     @RequestMapping("/toOpenId")
22     public @ResponseBody String getOpenId(String code,String echostr,HttpServletResponse res) throws IOException{
23         if(echostr==null){
24             String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx24d47d2080f54c5b&secret=95011ac70909e8cca2786217dd80ee3f&code="+code+"&grant_type=authorization_code";
25             System.out.println(code);
26             String openId="";
27             try {
28                 URL getUrl=new URL(url);
29                 HttpURLConnection http=(HttpURLConnection)getUrl.openConnection();
30                 http.setRequestMethod("GET"); 
31                 http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
32                 http.setDoOutput(true);
33                 http.setDoInput(true);
34     
35     
36                 http.connect();
37                 InputStream is = http.getInputStream(); 
38                 int size = is.available(); 
39                 byte[] b = new byte[size];
40                 is.read(b);
41     
42     
43                 String message = new String(b, "UTF-8");
44     
45                 JSONObject json = JSONObject.parseObject(message);
46                 openId = json.getString("openid");
47                 } catch (MalformedURLException e) {
48                     e.printStackTrace();
49                 } catch (IOException e) {
50                     e.printStackTrace();
51                 }
52             return openId;
53         }else{
54             PrintWriter out = res.getWriter();
55             out.print(echostr);
56             return null;
57         }
58     }
59     //做服务器校验
60     @RequestMapping("/tovalid")
61     public void valid(String echostr,HttpServletResponse res) throws IOException{
62         PrintWriter out = res.getWriter();
63         out.print(echostr);
64     }
65 }

    第二种

    (1)https://open.weixin.qq.com/connect/oauth2/authorize?appid=xxxxxxxx&redirect_uri=http://域名/open/openid&response_type=code&scope=snsapi_userinfo&state=1&connect_redirect=1#wechat_redirect

package net.itraf.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
@RequestMapping("/weixin")
public class Oauth2Action {

    @RequestMapping("/oauth")
    public void auth(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String echostr = request.getParameter("echostr");
        if(echostr==null){
            String appId = "wx24d47d2080f54c5b";
            String appSecret = "95011ac70909e8cca2786217dd80ee3f";
            //拼接
            String get_access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?"
                    + "appid="
                    + appId
                    + "&secret="
                    + appSecret
                    + "&code=CODE&grant_type=authorization_code";
            String get_userinfo = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            String code = request.getParameter("code");
            System.out.println("******************code=" + code);
            get_access_token_url = get_access_token_url.replace("CODE", code);
            String json = HttpsGetUtil.doHttpsGetJson(get_access_token_url);
            JSONObject jsonObject = JSONObject.fromObject(json);
            String access_token = jsonObject.getString("access_token");
            String openid = jsonObject.getString("openid");
            get_userinfo = get_userinfo.replace("ACCESS_TOKEN", access_token);
            get_userinfo = get_userinfo.replace("OPENID", openid);
            String userInfoJson = HttpsGetUtil.doHttpsGetJson(get_userinfo);
            JSONObject userInfoJO = JSONObject.fromObject(userInfoJson);
            String user_openid = userInfoJO.getString("openid");
            String user_nickname = userInfoJO.getString("nickname");
            String user_sex = userInfoJO.getString("sex");
            String user_province = userInfoJO.getString("province");
            String user_city = userInfoJO.getString("city");
            String user_country = userInfoJO.getString("country");
            String user_headimgurl = userInfoJO.getString("headimgurl");
            response.setContentType("text/html; charset=utf-8");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
            out.println("<HTML>");
            out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
            out.println(" <BODY>");
            out.print(" This is ");
            out.print(this.getClass());
            out.println(", using the POST method \n");
            out.println("openid:" + user_openid + "\n\n");
            out.println("nickname:" + user_nickname + "\n\n");
            out.println("sex:" + user_sex + "\n\n");
            out.println("province:" + user_province + "\n\n");
            out.println("city:" + user_city + "\n\n");
            out.println("country:" + user_country + "\n\n");
            out.println("<img src=/" + user_headimgurl + "/");
            out.println(">");
            out.println(" </BODY>");
            out.println("</HTML>");
            out.flush();
            out.close();
        }else{
            PrintWriter out = response.getWriter();
            out.print(echostr);
        }
    }
        
}
 1 package net.itraf.controller;
 2 
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5 import java.net.HttpURLConnection;
 6 import java.net.MalformedURLException;
 7 import java.net.URL;
 8 
 9 public class HttpsGetUtil {
10     public static String doHttpsGetJson(String Url)
11     {
12         String message = "";
13         try
14         {
15             System.out.println("doHttpsGetJson");//TODO:dd
16             URL urlGet = new URL(Url);
17             HttpURLConnection http = (HttpURLConnection) urlGet.openConnection(); 
18             http.setRequestMethod("GET");      //必须是get方式请求    24           
19             http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");  
20             http.setDoOutput(true);  
21             http.setDoInput(true);
22             System.setProperty("sun.net.client.defaultConnectTimeout", "30000");//连接超时30秒28     
23             System.setProperty("sun.net.client.defaultReadTimeout", "30000"); //读取超时30秒29 30       
24             http.connect();
25             InputStream is =http.getInputStream();
26             int size =is.available();
27             byte[] jsonBytes =new byte[size];
28             is.read(jsonBytes);
29             message=new String(jsonBytes,"UTF-8");
30         } 
31         catch (MalformedURLException e)
32         {
33               e.printStackTrace();
34           }
35         catch (IOException e)
36           {
37               e.printStackTrace();
38           } 
39         return message;
40     }
41 }

到此,两种方式都介绍完了,拿到用户信息后那就是你自己的事了。。。。。。