java 获取微信 页面授权 获取用户openid

先调用微信的地址 跳转https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx4b4009c4fce00e0c&redirect_uri=这里填写你要跳到请求页面授权域名l&response_type=code&scope=snsapi_base&state=123#wechat_redirect

返回redirect_uri/?code=""&status="";

拿到code就可获取openid以及用户信息

先上 工具类

  1 package com.yulv.utils;
  2
  3 import java.io.BufferedReader;
  4 import java.io.IOException;
  5 import java.io.InputStream;
  6 import java.io.InputStreamReader;
  7 import java.io.OutputStream;
  8 import java.io.OutputStreamWriter;
  9 import java.net.HttpURLConnection;
 10 import java.net.InetSocketAddress;
 11 import java.net.Proxy;
 12 import java.net.URL;
 13 import java.net.URLConnection;
 14 import java.util.Iterator;
 15 import java.util.Map;
 16
 17
 18 public class HttpRequestor {
 19      private String charset = "utf-8";
 20         private Integer connectTimeout = null;
 21         private Integer socketTimeout = null;
 22         private String proxyHost = null;
 23         private Integer proxyPort = null;
 24
 25         /**
 26          * Do GET request
 27          * @param url
 28          * @return
 29          * @throws Exception
 30          * @throws IOException
 31          */
 32         public String doGet(String url) throws Exception {
 33
 34             URL localURL = new URL(url);
 35
 36             URLConnection connection = openConnection(localURL);
 37             HttpURLConnection httpURLConnection = (HttpURLConnection)connection;
 38
 39             httpURLConnection.setRequestProperty("Accept-Charset", charset);
 40             httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
 41
 42             InputStream inputStream = null;
 43             InputStreamReader inputStreamReader = null;
 44             BufferedReader reader = null;
 45             StringBuffer resultBuffer = new StringBuffer();
 46             String tempLine = null;
 47
 48             if (httpURLConnection.getResponseCode() >= 300) {
 49                 throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
 50             }
 51
 52             try {
 53                 inputStream = httpURLConnection.getInputStream();
 54                 inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
 55                 reader = new BufferedReader(inputStreamReader);
 56
 57                 while ((tempLine = reader.readLine()) != null) {
 58                     resultBuffer.append(tempLine);
 59                 }
 60
 61             } finally {
 62
 63                 if (reader != null) {
 64                     reader.close();
 65                 }
 66
 67                 if (inputStreamReader != null) {
 68                     inputStreamReader.close();
 69                 }
 70
 71                 if (inputStream != null) {
 72                     inputStream.close();
 73                 }
 74
 75             }
 76
 77             return resultBuffer.toString();
 78         }
 79
 80         /**
 81          * Do POST request
 82          * @param url
 83          * @param parameterMap
 84          * @return
 85          * @throws Exception
 86          */
 87         public String doPost(String url, Map parameterMap) throws Exception {
 88
 89             /* Translate parameter map to parameter date string */
 90             StringBuffer parameterBuffer = new StringBuffer();
 91             if (parameterMap != null) {
 92                 Iterator iterator = parameterMap.keySet().iterator();
 93                 String key = null;
 94                 String value = null;
 95                 while (iterator.hasNext()) {
 96                     key = (String)iterator.next();
 97                     if (parameterMap.get(key) != null) {
 98                         value = (String)parameterMap.get(key);
 99                     } else {
100                         value = "";
101                     }
102
103                     parameterBuffer.append(key).append("=").append(value);
104                     if (iterator.hasNext()) {
105                         parameterBuffer.append("&");
106                     }
107                 }
108             }
109
110             System.out.println("POST parameter : " + parameterBuffer.toString());
111
112             URL localURL = new URL(url);
113
114             URLConnection connection = openConnection(localURL);
115             HttpURLConnection httpURLConnection = (HttpURLConnection)connection;
116
117             httpURLConnection.setDoOutput(true);
118             httpURLConnection.setRequestMethod("POST");
119             httpURLConnection.setRequestProperty("Accept-Charset", charset);
120             httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
121             httpURLConnection.setRequestProperty("Content-Length", String.valueOf(parameterBuffer.length()));
122
123             OutputStream outputStream = null;
124             OutputStreamWriter outputStreamWriter = null;
125             InputStream inputStream = null;
126             InputStreamReader inputStreamReader = null;
127             BufferedReader reader = null;
128             StringBuffer resultBuffer = new StringBuffer();
129             String tempLine = null;
130
131             try {
132                 outputStream = httpURLConnection.getOutputStream();
133                 outputStreamWriter = new OutputStreamWriter(outputStream);
134
135                 outputStreamWriter.write(parameterBuffer.toString());
136                 outputStreamWriter.flush();
137
138                 if (httpURLConnection.getResponseCode() >= 300) {
139                     throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
140                 }
141
142                 inputStream = httpURLConnection.getInputStream();
143                 inputStreamReader = new InputStreamReader(inputStream);
144                 reader = new BufferedReader(inputStreamReader);
145
146                 while ((tempLine = reader.readLine()) != null) {
147                     resultBuffer.append(tempLine);
148                 }
149
150             } finally {
151
152                 if (outputStreamWriter != null) {
153                     outputStreamWriter.close();
154                 }
155
156                 if (outputStream != null) {
157                     outputStream.close();
158                 }
159
160                 if (reader != null) {
161                     reader.close();
162                 }
163
164                 if (inputStreamReader != null) {
165                     inputStreamReader.close();
166                 }
167
168                 if (inputStream != null) {
169                     inputStream.close();
170                 }
171
172             }
173
174             return resultBuffer.toString();
175         }
176
177         private URLConnection openConnection(URL localURL) throws IOException {
178             URLConnection connection;
179             if (proxyHost != null && proxyPort != null) {
180                 Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
181                 connection = localURL.openConnection(proxy);
182             } else {
183                 connection = localURL.openConnection();
184             }
185             return connection;
186         }
187
188         /**
189          * Render request according setting
190          * @param request
191          */
192         private void renderRequest(URLConnection connection) {
193
194             if (connectTimeout != null) {
195                 connection.setConnectTimeout(connectTimeout);
196             }
197
198             if (socketTimeout != null) {
199                 connection.setReadTimeout(socketTimeout);
200             }
201
202         }
203
204         /*
205          * Getter & Setter
206          */
207         public Integer getConnectTimeout() {
208             return connectTimeout;
209         }
210
211         public void setConnectTimeout(Integer connectTimeout) {
212             this.connectTimeout = connectTimeout;
213         }
214
215         public Integer getSocketTimeout() {
216             return socketTimeout;
217         }
218
219         public void setSocketTimeout(Integer socketTimeout) {
220             this.socketTimeout = socketTimeout;
221         }
222
223         public String getProxyHost() {
224             return proxyHost;
225         }
226
227         public void setProxyHost(String proxyHost) {
228             this.proxyHost = proxyHost;
229         }
230
231         public Integer getProxyPort() {
232             return proxyPort;
233         }
234
235         public void setProxyPort(Integer proxyPort) {
236             this.proxyPort = proxyPort;
237         }
238
239         public String getCharset() {
240             return charset;
241         }
242
243         public void setCharset(String charset) {
244             this.charset = charset;
245         }
246 }

直接获取

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String code = request.getParameter("code");
        String appid = "wx4b4009c4fce00e0c";
        String secret = "4d3aea976157935e563f8ef01c7a4293";
        String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+secret+"&code="+wxCode+"&grant_type=authorization_code";
        //第一次请求 获取access_token 和 openid
        String  oppid = new HttpRequestor().doGet(requestUrl);
        JSONObject oppidObj =JSONObject.fromObject(oppid);
        String access_token = (String) oppidObj.get("access_token");
        String openid = (String) oppidObj.get("openid");
        String requestUrl2 = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid+"&lang=zh_CN";
        String userInfoStr = new HttpRequestor().doGet(requestUrl2);
        JSONObject wxUserInfo =JSONObject.fromObject(userInfoStr);
}
时间: 2024-08-29 03:42:28

java 获取微信 页面授权 获取用户openid的相关文章

微信网页授权-获取用户信息

第一步:修改网页授权安全域名,什么叫安全域名?安全域名就是说只有这个域名的网页才可以安全的进行网页授权以及获取用户信息. 第二步:下载下这个 MP_verify_Sb2ASLINFP09cMn6.txt(点击下载)放到你的服务器根目录下,可以通过你上面配置的域名直接访问的到,即:http://www.zheyue.me/MP_verify_Sb2ASLINFP09cMn6.txt  可以访问的到.点击确认完成. 第三步: 对自己做的网页地址进行包装,引导客户点击新包装的地址即可.例: https

微信 oauth授权 获取用户的信息

应用场景 (1)点击菜单直接链接跳转,这样直接跳是获取不到用户的openid的,需要用到这个 (2)获取用户的一些基本信息,头像,呢称,需要用到这个 准备 需要在公众号里面配置一个应用域名,不配置这个的话,跳转后就是空白页面 步骤 (一) //$callback="一个回调的网址比如http://www.baidu.com/auth.php"; $param ['redirect_uri'] = $callback . '&getOpenId=1';//&getOpen

微信网页授权获取用户基本信息

微信公众号可以通过微信网页授权机制,来获取用户基本信息,可以用于微信登录功能 关于网页授权的两种scope的区别说明 1.静默授权:以snsapi_base为scope发起的网页授权,是用来获取进入页面的用户的openid的,并且是静默授权并自动跳转到回调页的.用户感知的就是直接进入了回调页(往往是业务页面) 2.显示授权:以snsapi_userinfo为scope发起的网页授权,是用来获取用户的基本信息的.但这种授权需要用户手动同意,并且由于用户同意过,所以无须关注,就可在授权后获取该用户的

微信网页授权获取用户基本信息--PHP

现在就说说怎么通过网页授权获取用户基本信息(国家,省,市,昵称)等. 必要条件: 1)公众号认证 2)有网页授权获取用户基本信息的权限接口 注意:最近有朋友说:在公众平台申请的测试号,会出现无法取到用户信息.换到认证的公众账号就正常了! 如果您也遇到这个问题,可以试试在认证的公众账号里测试一下! 感谢大家的支持! 填写授权回调页面的域名 登录公众平台-->开发者中心-->接口权限表 找到 网页授权获取用户基本信息  然后修改-->填写你的域名.如下: 保存即可! ------------

微信网页授权——获取code、access_token、openid,及跨域问题解决

首先在微信开发文档中有提到微信网页授权的操作步骤: 第一步:用户同意授权,获取code 在确保微信公众账号拥有授权作用域(scope参数)的权限的前提下(服务号获得高级接口后,默认拥有scope参数中的snsapi_base和snsapi_userinfo),引导关注者打开如下页面: https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri = REDIRECT_URL&response_typ

微信网页授权获取用户信息等机制

参考官方文档 https://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html 1.用户进入授权界面(APP?WeChat) 引导用户打开链接: https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=S

php微信网页授权获取用户信息

配置回调域名: 1. 引导用户进入授权页面同意授权,获取code 2. 通过code换取网页授权access_token(与基础支持中的access_token不同) 3. 如果需要,开发者可以刷新网页授权access_token,避免过期 4. 通过网页授权access_token和openid获取用户基本信息 先自己建立两个文件: index.php  和  getUser.php 代码实例 index.php如下: 1 <?php 2 $appid = "公众号的appid"

Java实现微信网页授权

开发前的准备: 1.需要有一个公众号(我这里用的测试号),拿到AppID和AppSecret: 2.进入公众号开发者中心页配置授权回调域名.具体位置:接口权限-网页服务-网页账号-网页授权获取用户基本信息-修改 注意,这里仅需填写全域名(如www.qq.com.www.baidu.com),勿加 http:// 等协议头及具体的地址字段:  我们可以通过使用Ngrok来虚拟一个域名映射到本地开发环境,网址https://www.ngrok.cc/,大家自己去下载学习怎么使用 同时还需要扫一下这个

微信oauth2授权获得用户信息

<?php session_start(); header("Content-type: text/html; charset=utf-8"); $home = 'index.php'; class db{ private $host; private $user; private $pass; private $database; private $charset; function __construct($host,$user,$pass,$database,$charse