經過微信公衆號獲取用戶信息(java版)

最近因爲公司業務,就開始研究微信開發的流程,說實話,這東西剛開始看到時候和看天書的同樣,總算,看了一天的文檔,測試代碼終於出來了。html

一、首先須要到微信網站去設置一下,我是直接用的微信測試號。java

          接口配置信息必需要填寫的,因此說必須能將本身的服務發佈出去web

               

 

                    

 

            

            

 

                             到此微信配置完畢,接下來就是直接上代碼了spring

二、獲取用戶信息的方式一共是兩種,測試號必須關注微信公衆號,正式的不用,一種是靜默獲取(snsapi_base,這種方式只能獲取openid),另外一種是受權獲取(snsapi_userinfo,能夠獲取用戶的詳細信息)。json

      先說第一種api

  (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 }

    第二種app

    (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 }

到此,兩種方式都介紹完了,拿到用戶信息後那就是你本身的事了。。。。。。

相關文章
相關標籤/搜索