java微信公众号支付授权
2017-07-21 16:01
579 查看
微信公众号支付需要进行授权
1、微信公众号授权
(1)静默授权(用户看不到授权页面 ) scope=snsapi_base 获取不到微信用户基本信息
(2)正常授权(弹出授权页面,需要用户同意授权) scope=snsapi_userinfo 可以获取微信用户的基本信息
domain : 域名, redirect_uri必须是外网能够访问的地址,且必须是域名,不能是IP地址
gotoUrl : 授权之后要跳转的页面
@RequestMapping("/auth")
public void auth(String gotoUrl, HttpServletResponse response) throws Exception {
// 共账号及商户相关参数
String backUri = domain + "/wx/redirectWithOpenId?gotoUrl=" + gotoUrl;
// URLEncoder.encode 后可以在backUri 的url里面获取传递的所有参数
backUri = URLEncoder.encode(backUri);
logger.debug("********************backUri:" + backUri);
// scope 参数视各自需求而定,这里用scope=snsapi_userinfo 弹出授权页面直接授权目的获取统一支付接口的openid以及网页授权accesstoken snsapi_base
String url = "https://open.weixin.qq.com/connect/oauth2/authorize?"
+ "appid="
+ appid
+ "&redirect_uri="
+ backUri
+ "&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
response.sendRedirect(url);
}
2、授权 获取openId 以及 access_token
@RequestMapping("/redirectWithOpenId")
public ModelAndView redirectWithOpenId(String code, String gotoUrl,HttpServletRequest request) {
Integer userId = SystemHelper.currUserId();
ModelAndView mv = new ModelAndView();
String openId = "";
String access_token = "";
//获取openid 以及 网页授权accesstoken
String URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
+ appid + "&secret=" + appsecret + "&code=" + code
+ "&grant_type=authorization_code";
JSONObject jsonObject = HttpClientUtil.httpsRequest(URL, "GET", null);
if (null != jsonObject) {
//获取openid
openId = jsonObject.getString("openid");
//获取网页授权accesstoken
access_token = jsonObject.getString("access_token");
logger.debug("********************openId" + openId+",access_token="+access_token);
}
// //获取用户信息 若scope=snsapi_base 静默授权,不能获取到用户基本信息
// if (StringUtils.isNotEmpty(openId) && StringUtils.isNoneBlank(access_token)) {
// String InfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="
// +access_token+"&openid="+openId+"&lang=zh_CN";
// JSONObject jsonInfo = HttpClientUtil.httpsRequest(InfoUrl, "GET", null);
// logger.debug(InfoUrl+"********************jsonInfo\n" + jsonInfo);
// if(null != jsonInfo){
// WxAccount wxAccount = JSON.parseObject(jsonInfo.toJSONString(), WxAccount.class);
// //保存用户的基本信息
// }
// }
request.getSession().setAttribute("openId",openId);//保存openId到session中
mv.setViewName("redirect:" + gotoUrl);
mv.addObject("openId", openId);
return mv;
3、工具类 HttpClientUtil
/**
* 发送https请求
*
* @param requestUrl
* 请求地址
* @param requestMethod
* 请求方式(GET、POST)
* @param outputStr
* 提交的数据
* @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
*/
public static JSONObject httpsRequest(String requestUrl,
String requestMethod, String outputStr) {
JSONObject jsonObject = null;
try {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(null,requestUrl,new sun.net.www.protocol.https.Handler());
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(ssf);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
// 设置请求方式(GET/POST)
conn.setRequestMethod(requestMethod);
// 当outputStr不为null时向输出流写数据
if (null != outputStr) {
OutputStream outputStream = conn.getOutputStream();
// 注意编码格式
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 从输入流读取返回内容
InputStream inputStream = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
String str = null;
StringBuffer buffer = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
// 释放资源
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
conn.disconnect();
jsonObject = JSONObject.parseObject(buffer.toString());
} catch (ConnectException ce) {
} catch (Exception e) {
e.printStackTrace();
}
return jsonObject;
}
1、微信公众号授权
(1)静默授权(用户看不到授权页面 ) scope=snsapi_base 获取不到微信用户基本信息
(2)正常授权(弹出授权页面,需要用户同意授权) scope=snsapi_userinfo 可以获取微信用户的基本信息
domain : 域名, redirect_uri必须是外网能够访问的地址,且必须是域名,不能是IP地址
gotoUrl : 授权之后要跳转的页面
@RequestMapping("/auth")
public void auth(String gotoUrl, HttpServletResponse response) throws Exception {
// 共账号及商户相关参数
String backUri = domain + "/wx/redirectWithOpenId?gotoUrl=" + gotoUrl;
// URLEncoder.encode 后可以在backUri 的url里面获取传递的所有参数
backUri = URLEncoder.encode(backUri);
logger.debug("********************backUri:" + backUri);
// scope 参数视各自需求而定,这里用scope=snsapi_userinfo 弹出授权页面直接授权目的获取统一支付接口的openid以及网页授权accesstoken snsapi_base
String url = "https://open.weixin.qq.com/connect/oauth2/authorize?"
+ "appid="
+ appid
+ "&redirect_uri="
+ backUri
+ "&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
response.sendRedirect(url);
}
2、授权 获取openId 以及 access_token
@RequestMapping("/redirectWithOpenId")
public ModelAndView redirectWithOpenId(String code, String gotoUrl,HttpServletRequest request) {
Integer userId = SystemHelper.currUserId();
ModelAndView mv = new ModelAndView();
String openId = "";
String access_token = "";
//获取openid 以及 网页授权accesstoken
String URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
+ appid + "&secret=" + appsecret + "&code=" + code
+ "&grant_type=authorization_code";
JSONObject jsonObject = HttpClientUtil.httpsRequest(URL, "GET", null);
if (null != jsonObject) {
//获取openid
openId = jsonObject.getString("openid");
//获取网页授权accesstoken
access_token = jsonObject.getString("access_token");
logger.debug("********************openId" + openId+",access_token="+access_token);
}
// //获取用户信息 若scope=snsapi_base 静默授权,不能获取到用户基本信息
// if (StringUtils.isNotEmpty(openId) && StringUtils.isNoneBlank(access_token)) {
// String InfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="
// +access_token+"&openid="+openId+"&lang=zh_CN";
// JSONObject jsonInfo = HttpClientUtil.httpsRequest(InfoUrl, "GET", null);
// logger.debug(InfoUrl+"********************jsonInfo\n" + jsonInfo);
// if(null != jsonInfo){
// WxAccount wxAccount = JSON.parseObject(jsonInfo.toJSONString(), WxAccount.class);
// //保存用户的基本信息
// }
// }
request.getSession().setAttribute("openId",openId);//保存openId到session中
mv.setViewName("redirect:" + gotoUrl);
mv.addObject("openId", openId);
return mv;
3、工具类 HttpClientUtil
/**
* 发送https请求
*
* @param requestUrl
* 请求地址
* @param requestMethod
* 请求方式(GET、POST)
* @param outputStr
* 提交的数据
* @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
*/
public static JSONObject httpsRequest(String requestUrl,
String requestMethod, String outputStr) {
JSONObject jsonObject = null;
try {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(null,requestUrl,new sun.net.www.protocol.https.Handler());
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(ssf);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
// 设置请求方式(GET/POST)
conn.setRequestMethod(requestMethod);
// 当outputStr不为null时向输出流写数据
if (null != outputStr) {
OutputStream outputStream = conn.getOutputStream();
// 注意编码格式
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 从输入流读取返回内容
InputStream inputStream = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
String str = null;
StringBuffer buffer = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
// 释放资源
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
conn.disconnect();
jsonObject = JSONObject.parseObject(buffer.toString());
} catch (ConnectException ce) {
} catch (Exception e) {
e.printStackTrace();
}
return jsonObject;
}
相关文章推荐
- 微信公众号支付开发 --Java
- 多个域名使用一个微信公众号支付,设置了授权目录,为什么还提示“当前页面的URL未注册”
- 微信公众号开发-公众号支付-设置支付授权目录
- 微信公众号支付开发全过程----JAVA
- 微信公众号支付开发全过程(java版)
- java实现微信公众号授权登录获取用户信息流程
- JSAPI-------微信公众号支付 java 之 第一篇
- Java基于微信公众号接口实现授权登录源码及原理分析
- java微信公众号支付开发之现金红包
- Java微信公众号支付
- java开发微信公众号支付
- Java版微信公众号支付开发全过程
- java项目中使用angularjs1.X,解决微信内置h5支付授权目录配置
- java微信公众号支付
- 微信公众号支付(java版)
- 微信公众号开发《五》基于Java实现微信支付(公众号支付)简单教程
- 微信公众号授权,支付,退款总结
- 【转】微信公众号支付开发全过程 --JAVA
- 微信公众号开发---实现微信扫一扫支付 (java)
- Java微信公众号--3--网页授权的一些问题