溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

微信公眾號(hào)開發(fā)中使用Java如何實(shí)現(xiàn)獲取用戶的信息

發(fā)布時(shí)間:2020-11-19 16:23:18 來(lái)源:億速云 閱讀:280 作者:Leah 欄目:編程語(yǔ)言

微信公眾號(hào)開發(fā)中使用Java如何實(shí)現(xiàn)獲取用戶的信息?針對(duì)這個(gè)問題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問題的小伙伴找到更簡(jiǎn)單易行的方法。

1、首先需要到微信網(wǎng)站去設(shè)置一下,我是直接用的微信測(cè)試號(hào)。

        接口配置信息必須要填寫的,所以說必須能將自己的服務(wù)發(fā)布出去

微信公眾號(hào)開發(fā)中使用Java如何實(shí)現(xiàn)獲取用戶的信息

          微信公眾號(hào)開發(fā)中使用Java如何實(shí)現(xiàn)獲取用戶的信息

            微信公眾號(hào)開發(fā)中使用Java如何實(shí)現(xiàn)獲取用戶的信息

            微信公眾號(hào)開發(fā)中使用Java如何實(shí)現(xiàn)獲取用戶的信息

                             到此微信配置完畢,接下來(lái)就是直接上代碼了

2、獲取用戶信息的方式一共是兩種,前提都是用戶關(guān)注微信公眾號(hào),一種是靜默獲取(snsapi_base,這種方式只能獲取openid),另一種是授權(quán)獲取(snsapi_userinfo,可以獲取用戶的詳細(xì)信息)。

      先說第一種

  (1)首先需要先訪問微信的鏈接

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

           這里的 uri就是直接回掉我們的服務(wù)地址,一定要記住,服務(wù)校驗(yàn)的判斷,我是按照來(lái)判斷的echostr(第二種方式也是這樣)

package net.itraf.controller;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONObject;
@Controller
@RequestMapping("/open")
public class OpenController {
  @RequestMapping("/toOpenId")
  public @ResponseBody String getOpenId(String code,String echostr,HttpServletResponse res) throws IOException{
    if(echostr==null){
      String url="https://api.weixin.qq.com/sns/oauth3/access_token?appid=wx24d47d2080f54c5b&secret=95011ac70909e8cca2786217dd80ee3f&code="+code+"&grant_type=authorization_code";
      System.out.println(code);
      String openId="";
      try {
        URL getUrl=new URL(url);
        HttpURLConnection http=(HttpURLConnection)getUrl.openConnection();
        http.setRequestMethod("GET"); 
        http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
        http.setDoOutput(true);
        http.setDoInput(true);
        http.connect();
        InputStream is = http.getInputStream(); 
        int size = is.available(); 
        byte[] b = new byte[size];
        is.read(b);
        String message = new String(b, "UTF-8");
        JSONObject json = JSONObject.parseObject(message);
        openId = json.getString("openid");
        } catch (MalformedURLException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
      return openId;
    }else{
      PrintWriter out = res.getWriter();
      out.print(echostr);
      return null;
    }
  }
  //做服務(wù)器校驗(yàn)
  @RequestMapping("/tovalid")
  public void valid(String echostr,HttpServletResponse res) throws IOException{
    PrintWriter out = res.getWriter();
    out.print(echostr);
  }
}

第二種

    (1)

https://open.weixin.qq.com/connect/oauth3/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 Oauth3Action {
  @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/oauth3/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);
    }
  }
}
package net.itraf.controller;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class HttpsGetUtil {
  public static String doHttpsGetJson(String Url)
  {
    String message = "";
    try
    {
      System.out.println("doHttpsGetJson");//TODO:dd
      URL urlGet = new URL(Url);
      HttpURLConnection http = (HttpURLConnection) urlGet.openConnection(); 
      http.setRequestMethod("GET");   //必須是get方式請(qǐng)求  24      
      http.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); 
      http.setDoOutput(true); 
      http.setDoInput(true);
      System.setProperty("sun.net.client.defaultConnectTimeout", "30000");//連接超時(shí)30秒28   
      System.setProperty("sun.net.client.defaultReadTimeout", "30000"); //讀取超時(shí)30秒29 30    
      http.connect();
      InputStream is =http.getInputStream();
      int size =is.available();
      byte[] jsonBytes =new byte[size];
      is.read(jsonBytes);
      message=new String(jsonBytes,"UTF-8");
    } 
    catch (MalformedURLException e)
    {
       e.printStackTrace();
     }
    catch (IOException e)
     {
       e.printStackTrace();
     } 
    return message;
  }
}

關(guān)于微信公眾號(hào)開發(fā)中使用Java如何實(shí)現(xiàn)獲取用戶的信息問題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識(shí)。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI