Commit 6ffc0a56 authored by hezhen's avatar hezhen

添加微信支付

parent 9f91092a
......@@ -7,7 +7,7 @@ public class RedisKey {
/**
* 常量缓存key前缀
*/
public static final String CONSTANT_CACHE_PREFIX ="cache:constant:";
public static final String TOKEN_CACHE_PREFIX ="cache:token:";
/**
* 地区常量缓存key前缀(子读取列表)
......
package com.xxfc.platform.universal.utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URLDecoder;
@Slf4j
public class HttpRequestUtil {
/**
* post请求
* @param url url地址
* @return
*/
public static String httpPost(String url){
//post请求返回结果
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
String str = "";
try {
HttpResponse result = httpClient.execute(method);
url = URLDecoder.decode(url, "UTF-8");
/**请求发送成功,并得到响应**/
if (result.getStatusLine().getStatusCode() == 200) {
try {
/**读取服务器返回过来的json字符串数据**/
str = EntityUtils.toString(result.getEntity(),"UTF-8");
} catch (Exception e) {
log.error("post请求提交失败:" + url, e);
}
}
} catch (IOException e) {
log.error("post请求提交失败:" + url, e);
}
return str;
}
/**
* 发送get请求
* @param url 路径
* @return
*/
public static String httpGet(String url){
//get请求返回结果
String strResult = null;
try {
DefaultHttpClient client = new DefaultHttpClient();
//发送get请求
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
/**请求发送成功,并得到响应**/
if (response.getStatusLine().getStatusCode() == org.apache.http.HttpStatus.SC_OK) {
/**读取服务器返回过来的json字符串数据**/
strResult = EntityUtils.toString(response.getEntity(),"UTF-8");
} else {
log.error("get请求提交失败:" + url);
}
} catch (IOException e) {
log.error("get请求提交失败:" + url, e);
}
return strResult;
}
}
package com.xxfc.platform.universal.biz;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.xxfc.platform.universal.utils.HttpRequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
@Service
@Slf4j
public class WeixinService {
/**
* 网页
*/
@Value("${wx.appid}")
private String wy_appid;
@Value("${wx.appSercet}")
private String wy_secret;
public static final String frontSessionKey = "frontWeixKey";
public JSONObject getAccessToken(String code){
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?";
String params = "appid="+wy_appid+"&secret="+wy_secret+"&code="+code+"&grant_type=authorization_code";
String result = HttpRequestUtil.httpGet(url + params);
JSONObject data = JSON.parseObject(result);
return data;
}
public JSONObject getValidateData(String access_token,String openid){
String url = "https://api.weixin.qq.com/sns/auth?access_token=" + access_token + "&openid=" + openid;
String result = HttpRequestUtil.httpGet(url);
JSONObject data = JSON.parseObject(result);
return data;
}
public JSONObject getRefreshToken(String refresh_token){
String url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + wy_appid + "&grant_type=refresh_token&refresh_token=" + refresh_token;
String result = HttpRequestUtil.httpGet(url);
JSONObject data = JSON.parseObject(result);
return data;
}
public JSONObject getUserInfo(String access_token,String openid){
String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN";
String result = HttpRequestUtil.httpGet(url);
JSONObject data = JSON.parseObject(result);
return data;
}
public String getAuthorize(String redirec_url){
String oauth_api = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={APPID}&redirect_uri={REDIRECT_URI}&response_type=code&scope={SCOPE}&state={STATE}#wechat_redirect";
oauth_api = oauth_api.replace("{APPID}", wy_appid)
.replace("{REDIRECT_URI}", redirec_url)
.replace("{SCOPE}", "snsapi_base").replace("{STATE}", "state");
log.info("---oauth_api===="+oauth_api);
return oauth_api;
}
//获取缓存
public String getSession(HttpServletRequest request){
try {
HttpSession session = request.getSession();
String frontSessionValue1 = (String) session.getAttribute(frontSessionKey);
if (StringUtils.isBlank(frontSessionValue1)) {
return null;
}
return frontSessionValue1;
}catch (Exception e){
e.printStackTrace();
return null;
}
}
}
......@@ -20,7 +20,7 @@ import org.springframework.data.redis.serializer.StringRedisSerializer;
public class RedisConfiguration {
@Bean
public RedisTemplate<String, Object> customRedisTemplate(RedisConnectionFactory factory) {
public RedisTemplate<String, Object> universalRedisTemplate(RedisConnectionFactory factory) {
RedisTemplate redisTemplate = new RedisTemplate();
redisTemplate.setConnectionFactory(factory);
RedisSerializer<String> stringSerializer = new StringRedisSerializer();
......
package com.xxfc.platform.universal.controller;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.xxfc.platform.universal.biz.WeixinService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
/**
* 用户
*/
@RestController
@RequestMapping("info")
public class UserInfoController {
@Autowired
WeixinService weixinService;
@RequestMapping(value = "getOpenId", method = RequestMethod.GET) //匹配的是href中的download请求
public ObjectRestResponse sendSms(HttpServletRequest request) throws Exception {
return ObjectRestResponse.succ(weixinService.getSession(request));
}
}
package com.xxfc.platform.universal.controller;
import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.xxfc.platform.universal.biz.WeixinService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.mockito.internal.util.collections.Sets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* @author Administrator
*/
@Controller
@RequestMapping("/auth")
@Slf4j
public class WeixinController {
public static final String WECHAT_AUTOLOGIN_CALLBACKURL_KEY = "callback";
@Autowired
WeixinService weixinService;
@Value("${wx.url}")
private String url;
@RequestMapping(value ="/app/unauth/wxLogin",method = RequestMethod.GET)
@IgnoreUserToken
public String wxLogin(@RequestParam(value = "redirec_url")String redirec_url,
@RequestParam(value = "orderNo")String orderNo,
@RequestParam(value = "type",defaultValue = "1")Integer type){
log.info("-----微信wxLogin---redirec_url=="+redirec_url);
if (StringUtils.isBlank(redirec_url)){
redirec_url="";
}
try {
String encrypt_curr_url = Base64.encode(redirec_url.getBytes("utf-8"));
redirec_url=url+"?" + WECHAT_AUTOLOGIN_CALLBACKURL_KEY+ "=" + encrypt_curr_url+"&orderNo="+orderNo+"&type="+type;
String oauth_api=weixinService.getAuthorize(redirec_url);
return String.format("redirect:"+oauth_api);
}catch (Exception e){
e.printStackTrace();
log.info("网络异常===" + e.getMessage());
return String.format("网络异常");
}
}
/**
* 微信浏览器获取用户信息
* @param code
* @param callback
* @return
*/
@GetMapping(value = "/app/unauth/userInfo")
public String getUserInformation(String code, String callback,String key, HttpServletRequest request) {
log.info("-----微信回调userInfo---code=="+code+"----redirec_url==="+callback+"---key==="+key);
try {
authUser(code);
callback =new String(Base64.decode(callback), "utf-8");
log.info("callback===" + callback);
}catch (Exception e){
e.printStackTrace();
log.info("网络异常===" + e.getMessage());
}
return String.format("redirect:"+callback);
}
public void authUser(String code){
if (StringUtils.isBlank(code)){
log.info("----code为空---");
throw new BaseException(ResultCode.FAILED_CODE, Sets.newSet("code为空"));
}
String openid = null;
String access_token = null;
try {
JSONObject jsonData = weixinService.getAccessToken(code);
openid = jsonData.getString("openid");
access_token = jsonData.getString("access_token");
String refresh_token = jsonData.getString("refresh_token");
log.info("-----微信回调userInfo---openid=="+openid+"----access_token==="+access_token);
//验证access_token是否失效
JSONObject validateData = weixinService.getValidateData(access_token, openid);
if (!"0".equals(validateData.getString("errcode"))){
//刷新access_token
JSONObject refreshData= weixinService.getRefreshToken(refresh_token);
access_token = refreshData.getString("access_token");
}
}catch (Exception e){
e.printStackTrace();
log.info("网络异常===" + e.getMessage());
throw new BaseException(ResultCode.FAILED_CODE, Sets.newSet("网络异常"));
}
}
}
package com.xxfc.platform.universal.interceptor;
import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.common.util.UserAgentUtil;
import com.xxfc.platform.universal.biz.WeixinService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
/**
* 微信登陆拦截器
*
* @author
*
*/
@Slf4j
public class WeChatH5LoginInterceptor extends HandlerInterceptorAdapter {
@Value("${wx.sendUrl}")
private String sendUrl;
@Autowired
WeixinService weixinService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String curr_domain = request.getServerName();
log.info("curr_domain:" + curr_domain);
log.info("address:" + request.getRequestURL().toString());
log.info("params:" + request.getQueryString());
boolean isWx = UserAgentUtil.isWexinBrowser(request);
if (isWx) {
//session里面获取用户信息
String openId=weixinService.getSession(request);
if (StringUtils.isNotBlank(openId)){
return true;
}
Map<String,Object> result=new HashMap<>();
result.put("status",1001);
JSONObject json = new JSONObject();
json.put("sendUrl",sendUrl);
result.put("data",json);
response.getWriter().write(result.toString());
return false;
}
return true;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment