Commit 4f983eaf authored by 周健威's avatar 周健威

Merge branch 'master' into feature-zjw

parents e4b87ede 98855f21
package com.github.wxiaoqi.security.common.util;
import javax.servlet.http.HttpServletRequest;
public class UserAgentUtil {
/**
* 关键字: 微信浏览器
*/
public static final String KEY_WEIXIN_BROWSER = "micromessenger";
/**
* 判断是否微信浏览器
*
* @param user_agent
* @return
*/
public static boolean isWexinBrowser(HttpServletRequest request) {
// 可能会出现npe
String user_agent = "";
user_agent = request.getHeader("user-agent");
// 修改如下
return user_agent != null && user_agent.toLowerCase().indexOf(KEY_WEIXIN_BROWSER) > 0;
}
}
......@@ -43,4 +43,7 @@ public class WalletCathListDTO {
@ApiModelProperty("单号")
private String cono;
@ApiModelProperty(value = "用户账号")
private String accountNumber;
}
......@@ -79,7 +79,7 @@ public class AppUserDTO {
private Integer buyCount;
private Integer lockDays;
private Integer discount;
private Integer memberLevel;
private Integer memberLevel = 0;
private String memberName;
//图标
private String icon;
......
......@@ -40,4 +40,7 @@ public class WalletCathAdminVo {
@ApiModelProperty("单号")
private String cono;
@ApiModelProperty(value = "用户账号")
private String accountNumber;
}
......@@ -84,6 +84,7 @@ public class BaseUserMemberExportBiz extends BaseBiz<BaseUserMemberExportMapper,
.memberLevel(userMemberSaveDTO.getMemberLevel())
.totalNumber(userMemberSaveDTO.getTotalNumber())
.rentFreeDays(userMemberSaveDTO.getRentFreeDays())
.memberName(userMemberSaveDTO.getMemberName())
.discount(level == null ? 0 : level.getDiscount() == null ? 0 : level.getDiscount())
.status(phoneAndUserIdMap == null ? 0 : (phoneAndUserIdMap.get(userMemberSaveDTO.getPhone()) == null ? 0 : 1))
.crtId(userId)
......
......@@ -14,7 +14,8 @@
wc.stauts,
wc.crt_time AS `crtTime`,
wc.finish_time AS `finishTime`,
wc.cono
wc.cono,
wc.account_number AS `accountNumber`
FROM
(SELECT * FROM `my_wallet_cath` <if test="state != null">
WHERE `stauts`=#{state}
......
......@@ -443,12 +443,14 @@ public class OrderAccountBiz extends BaseBiz<OrderAccountMapper,OrderAccount> {
csv.initParamJson();
//设置明细
orderRentVehicleBiz.updateSelectiveById(new OrderRentVehicleDetail(){{
orderRentVehicleBiz.updateSelectiveByIdRe(new OrderRentVehicleDetail(){{
setId(orderMQDTO.getDetailId());
handelCostDetailExtend(csv);
setBackFreeDays(inProgressVO.getBackFreeDays());
}});
orderMQDTO.setOrderRentVehicleDetail(orderRentVehicleBiz.selectById(orderMQDTO.getDetailId()));
//捕捉异常
try {
orderMsgBiz.handelMsgDeposit(orderMQDTO.getOrderRentVehicleDetail(), orderMQDTO, userFeign.userDetailById(orderMQDTO.getUserId()).getData());
......
......@@ -13,6 +13,7 @@ import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.xxfc.platform.activity.user.UserInfoBiz;
import com.xxfc.platform.order.biz.inner.OrderCalculateBiz;
import com.xxfc.platform.order.biz.inner.OrderMsgBiz;
import com.xxfc.platform.order.contant.enumerate.CrosstownTypeEnum;
import com.xxfc.platform.order.contant.enumerate.DepositRefundStatus;
import com.xxfc.platform.order.contant.enumerate.OrderStatusEnum;
......@@ -73,6 +74,8 @@ public class OrderVehicleCrosstownBiz extends BaseBiz<OrderVehicaleCrosstownMapp
BaseOrderBiz baseOrderBiz;
@Autowired
OrderItemBiz orderItemBiz;
@Autowired
OrderMsgBiz orderMsgBiz;
public OrderVehicleCrosstown get(Integer id) {
return selectById(id);
......@@ -287,12 +290,13 @@ public class OrderVehicleCrosstownBiz extends BaseBiz<OrderVehicaleCrosstownMapp
}
BeanUtil.copyProperties(orderVehicleCrosstownDto, oldValue.get(0), CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
getOrderLicense(orderVehicleCrosstownDto);
handleOrderStatus(baseOrder, orderRentVehicleDetail, oldValue.get(0));
handleOrderStatus(baseOrder, orderRentVehicleDetail, oldValue.get(0), appUserDTO);
updateSelectiveByIdRe(oldValue.get(0));
RestResponse<Vehicle> response = vehicleFeign.findById(orderRentVehicleDetail.getVehicleId());
if (response.getData() != null) {
orderVehicleCrosstownDto.setVehicleNumberPlat(response.getData().getNumberPlate());
}
return ObjectRestResponse.succ(oldValue.get(0));
} else if (oldValue.size() <= 0) {
orderVehicleCrosstownDto.setDeductionCost(amount);
......@@ -304,7 +308,7 @@ public class OrderVehicleCrosstownBiz extends BaseBiz<OrderVehicaleCrosstownMapp
getOrderLicense(orderVehicleCrosstownDto);
orderVehicleCrosstownBiz.insertSelective(orderVehicleCrosstownDto);
OrderVehicleCrosstown orderVehicleCrosstown = orderVehicleCrosstownBiz.selectOne(orderVehicleCrosstownDto);
handleOrderStatus(baseOrder, orderRentVehicleDetail, orderVehicleCrosstown);
handleOrderStatus(baseOrder, orderRentVehicleDetail, orderVehicleCrosstown, appUserDTO);
orderVehicleCrosstownBiz.updateSelectiveByIdRe(orderVehicleCrosstown);
RestResponse<Vehicle> response = vehicleFeign.findById(orderRentVehicleDetail.getVehicleId());
if (response.getData() != null) {
......@@ -312,15 +316,16 @@ public class OrderVehicleCrosstownBiz extends BaseBiz<OrderVehicaleCrosstownMapp
}
return ObjectRestResponse.succ(orderVehicleCrosstownDto);
}
return ObjectRestResponse.createDefaultFail();
}
private void handleOrderStatus(BaseOrder baseOrder, OrderRentVehicleDetail orderRentVehicleDetail, OrderVehicleCrosstown orderVehicleCrosstown) {
private void handleOrderStatus(BaseOrder baseOrder, OrderRentVehicleDetail orderRentVehicleDetail, OrderVehicleCrosstown orderVehicleCrosstown, AppUserDTO appUserDTO) {
//交车完成 设置订单状态为出行中
BigDecimal totalAmount = orderRentVehicleDetail.getDeposit();
if (baseOrder.getStatus() == OrderStatusEnum.ORDER_TOSTART.getCode()) {//交车
baseOrder.setStatus(OrderStatusEnum.ORDER_WAIT.getCode());
baseOrder = baseOrderBiz.updateSelectiveByIdReT(baseOrder);
orderMsgBiz.handelMsgWait(orderRentVehicleDetail, null, null, baseOrder, appUserDTO);
} else if (baseOrder.getStatus() == OrderStatusEnum.ORDER_WAIT.getCode()) { //还车
if (orderVehicleCrosstown.getType() == CrosstownTypeEnum.ARRIVE.getCode()) {//不定损直接还车
//添加非定损记录
......
......@@ -235,8 +235,8 @@ public class OrderMsgBiz {
sms2BgUser(startCompanyDetail.getVehiceServicePhone(), startCompanyDetail, endCompanyDetail, orvd, otd, baseOrder, appUserDTO, SmsTemplateDTO.PAY_D, smsParams);
//后台发送消息(收车人)
smsParams.clear();
sms2BgUser(endCompanyDetail.getVehiceServicePhone(), startCompanyDetail, endCompanyDetail, orvd, otd, baseOrder, appUserDTO, SmsTemplateDTO.PAY_E, smsParams);
// smsParams.clear();
// sms2BgUser(endCompanyDetail.getVehiceServicePhone(), startCompanyDetail, endCompanyDetail, orvd, otd, baseOrder, appUserDTO, SmsTemplateDTO.PAY_E, smsParams);
}else {
log.error("通知短信异常,开始公司id 不存在或者为0 订单号:{}", baseOrder.getId());
......@@ -338,7 +338,7 @@ public class OrderMsgBiz {
}
/**
* 取消订单处理提醒短信的发送
* 订单出发提前提醒短信的发送
* @param orvd
* @param baseOrder
* @param appUserDTO
......@@ -371,6 +371,39 @@ public class OrderMsgBiz {
}
}
/**
* 订单出发后提醒短信的发送
* @param orvd
* @param baseOrder
* @param appUserDTO
*/
public void handelMsgWait(OrderRentVehicleDetail orvd, OrderTourDetail otd, OrderMemberDetail omd, BaseOrder baseOrder, AppUserDTO appUserDTO) {
try {
OrderTypeEnum orderTypeEnum = OrderTypeEnum.codeAndDesc.get(baseOrder.getType());
List<String> smsParams = new ArrayList<String>();
switch (orderTypeEnum) {
case RENT_VEHICLE:
CompanyDetail startCompanyDetail = vehicleFeign.getCompanyDetail(orvd.getStartCompanyId()).getData();
CompanyDetail endCompanyDetail = vehicleFeign.getCompanyDetail(orvd.getEndCompanyId()).getData();
if(null != orvd.getEndCompanyId() && !SYS_FALSE.equals(orvd.getEndCompanyId())) {
//后台发送消息(收车人)
sms2BgUser(endCompanyDetail.getVehiceServicePhone(), startCompanyDetail, endCompanyDetail, orvd, otd, baseOrder, appUserDTO, SmsTemplateDTO.PAY_E, smsParams);
}else {
log.error("通知后台客户短信异常,结束公司id 不存在或者为0 订单号:{}", baseOrder.getId());
}
break;
case TOUR:
break;
case MEMBER:
break;
default:
break;
}
}catch (Exception e) {
log.error(e.getMessage(), e);
}
}
/**
* 订单完成后处理押金提醒短信的发送
* @param baseOrder
......@@ -616,8 +649,8 @@ public class OrderMsgBiz {
case SmsTemplateDTO.PAY_E :
smsParams.add(appUserDTO.getRealname());
smsParams.add(appUserDTO.getUsername());
smsParams.add(DateUtil.formatDateTime(DateUtil.date(orvd.getStartTime())));
smsParams.add(sCompany.getName());
smsParams.add(DateUtil.formatDateTime(DateUtil.date(orvd.getEndTime())));
smsParams.add(eCompany.getName());
smsParams.add(baseOrder.getName());
break;
case SmsTemplateDTO.CANCEL_E :
......
......@@ -33,7 +33,7 @@ import static com.github.wxiaoqi.security.common.constant.CommonConstants.*;
import static com.xxfc.platform.universal.constant.DictionaryKey.APP_ORDER;
/**
* 跨平台Http任务
* 订单出车短信提前提醒
*
* @author xuxueli 2018-09-16 03:48:34
*/
......
......@@ -16,6 +16,7 @@ import com.xxfc.platform.order.biz.OrderRefundBiz;
import com.xxfc.platform.order.biz.inner.OrderCalculateBiz;
import com.xxfc.platform.order.biz.inner.OrderCancelBiz;
import com.xxfc.platform.order.contant.enumerate.ItemTypeEnum;
import com.xxfc.platform.order.contant.enumerate.OrderStatusEnum;
import com.xxfc.platform.order.contant.enumerate.OrderTypeEnum;
import com.xxfc.platform.order.entity.OrderItem;
import com.xxfc.platform.order.entity.OrderRefund;
......@@ -155,10 +156,12 @@ public class OrderRefundController extends BaseController<OrderRefundBiz,OrderRe
OrderRefundPriceVO orpv = new OrderRefundPriceVO();
orpv.setRealAmount(orderPageVO.getRealAmount());
orpv.setRefundAmount(totalRefundAmount);
if(totalDeductAmount.compareTo(BigDecimal.ZERO) > 0) {
orpv.setRefundDesc(StrUtil.format("本次取消操作需要扣除{}元违约金,实际退款金额为{}元,您确定要取消订单吗?", totalDeductAmount, totalRefundAmount));
if(orderPageVO.getStatus().equals(OrderStatusEnum.ORDER_UNPAY.getCode())
|| orderPageVO.getStatus().equals(OrderStatusEnum.ORDER_CRT.getCode())
|| totalDeductAmount.compareTo(BigDecimal.ZERO) <= 0) {
orpv.setRefundDesc("是否确定取消订单");
}else {
orpv.setRefundDesc("取消操作可能会产生额外费用,是否确定取消订单");
orpv.setRefundDesc(StrUtil.format("本次取消操作需要扣除{}元违约金,实际退款金额为{}元,您确定要取消订单吗?", totalDeductAmount, totalRefundAmount));
}
return ObjectRestResponse.succ(orpv);
}
......
......@@ -266,11 +266,15 @@ public class OrderRentVehicleService extends AbstractOrderHandle<OrderRentVehicl
//计算车辆费用
//如果用户存在,并且为会员,并且车辆有优惠价
//默认折扣默认100
detail.setRebate(100);
if(null != dto && SYS_TRUE.equals(dto.getIsMember()) && !NONE.getCode().equals(dto.getMemberLevel()) && !DISCOUNT_STATUS_NONE.equals(vehicleModel.getRentDiscountStatus())) {
String[] prices = StrUtil.isBlank(vehicleModel.getRentDiscountPrice())
?new String[]{vehicleModel.getPrice().toString(),vehicleModel.getPrice().toString(),vehicleModel.getPrice().toString()}
:vehicleModel.getRentDiscountPrice().split(",");
HandleDiscountDTO handleDiscountDTO = new HandleDiscountDTO();
handleDiscountDTO.setRebate(100);
handleDiscountDTO.setModelAmount(vehicleModel.getPrice());
switch (MemberEnum.getByCode(dto.getMemberLevel())) {
case NORMAL:
handleDiscountDTO = handleDiscount(dto, vehicleModel, prices, NORMAL);
......@@ -284,6 +288,8 @@ public class OrderRentVehicleService extends AbstractOrderHandle<OrderRentVehicl
handleDiscountDTO = handleDiscount(dto, vehicleModel, prices, DIAMOND);
detail.getOrder().setHasMemberRight(SYS_TRUE);
break;
default:
break;
}
detail.setRebate(handleDiscountDTO.getRebate());
vehicleOrderItem.setUnitPrice(handleDiscountDTO.getModelAmount());
......
......@@ -130,6 +130,9 @@
</foreach>
</if>
<if test="userId != null">
and b.user_id = #{userId}
</if>
<if test="status != null">
and b.status = #{status}
</if>
......
......@@ -113,6 +113,7 @@ public class SummitActivityBiz extends BaseBiz<SummitActivityMapper, SummitActiv
public void publishSummitActivityById(Integer id, Integer state) {
SummitActivity summitActivity = new SummitActivity();
summitActivity.setIsPublish(state);
summitActivity.setUpdTime(Instant.now().toEpochMilli());
summitActivity.setId(id);
mapper.updateByPrimaryKeySelective(summitActivity);
}
......@@ -121,6 +122,7 @@ public class SummitActivityBiz extends BaseBiz<SummitActivityMapper, SummitActiv
SummitActivity summitActivity = new SummitActivity();
summitActivity.setIsShow(state);
summitActivity.setId(id);
summitActivity.setUpdTime(Instant.now().toEpochMilli());
mapper.updateByPrimaryKeySelective(summitActivity);
}
......@@ -128,6 +130,7 @@ public class SummitActivityBiz extends BaseBiz<SummitActivityMapper, SummitActiv
SummitActivity summitActivity = new SummitActivity();
summitActivity.setIsHomePage(state);
summitActivity.setId(id);
summitActivity.setUpdTime(Instant.now().toEpochMilli());
mapper.updateByPrimaryKeySelective(summitActivity);
}
......@@ -135,6 +138,7 @@ public class SummitActivityBiz extends BaseBiz<SummitActivityMapper, SummitActiv
SummitActivity summitActivity = new SummitActivity();
summitActivity.setIsOpenReg(state);
summitActivity.setId(id);
summitActivity.setUpdTime(Instant.now().toEpochMilli());
mapper.updateByPrimaryKeySelective(summitActivity);
}
......@@ -142,6 +146,7 @@ public class SummitActivityBiz extends BaseBiz<SummitActivityMapper, SummitActiv
SummitActivity summitActivity = new SummitActivity();
summitActivity.setIsDel(1);
summitActivity.setId(id);
summitActivity.setUpdTime(Instant.now().toEpochMilli());
mapper.updateByPrimaryKeySelective(summitActivity);
}
......@@ -162,6 +167,7 @@ public class SummitActivityBiz extends BaseBiz<SummitActivityMapper, SummitActiv
SummitActivity summitActivity = new SummitActivity();
summitActivity.setId(id);
summitActivity.setRank(rank);
summitActivity.setUpdTime(Instant.now().toEpochMilli());
mapper.updateByPrimaryKeySelective(summitActivity);
}
......
......@@ -83,6 +83,12 @@
<artifactId>jiguang-common</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
<scope>compile</scope>
</dependency>
</dependencies>
......
package com.xxfc.platform.universal.api;
import com.xxfc.platform.universal.api.pojo.Authentication;
import com.xxfc.platform.universal.entity.IdInformation;
/**
* 调用外部接口实现类。调用不同的外部接口,需要编写不同了类实现该类
*/
public interface BaseAuthentication {
Authentication getAuthentication(IdInformation idInformation);
}
package com.xxfc.platform.universal.api.impl;
import com.xxfc.platform.universal.api.BaseAuthentication;
import com.xxfc.platform.universal.api.pojo.Authentication;
import com.xxfc.platform.universal.entity.IdInformation;
public class FQAuthentication implements BaseAuthentication {
@Override
public Authentication getAuthentication(IdInformation idInformation) {
return null;
}
}
package com.xxfc.platform.universal.api.pojo;
public class Authentication {
}
......@@ -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前缀(子读取列表)
......
......@@ -71,6 +71,8 @@ public class SmsTemplateDTO {
public static final int PAY_I= 26;
//旅游(上车通知)27
public static final int PAY_J= 27;
//小程序密码通知
public static final int PWD= 28;
......
package com.xxfc.platform.universal.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.security.KeyStore;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import com.github.wxiaoqi.security.common.util.MyX509TrustManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
/**
* @Author vitoHuang
* @Time 2015年8月14日
* @Mark HTTPS请求工具
*/
@Slf4j
public class HTTPSUtils{
/**
* HTTPS json 请求
* @param requestUrl 请求地址
* @param requestMethod 请求方式 POST/GET
* @param msg json方式的请求参数
* @return 返回相应的字符串 异常会输出null
*/
public static String httpRequest(String requestUrl, String requestMethod, String msg){
log.error("进入方法httpRequest()httpRequest="+requestUrl);
OutputStream outputStream = null;
InputStream inputStream = 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(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
if ("GET".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
// 当有数据需要提交时
log.error("httpUrlConn="+httpUrlConn);
if (null != msg) {
outputStream = httpUrlConn.getOutputStream();
// 注意编码格式,防止中文乱码
outputStream.write(msg.getBytes("UTF-8"));
}
// 将返回的输入流转换成字符串
inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
log.error("inputStreamReader="+inputStreamReader);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer buffer = new StringBuffer();
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
httpUrlConn.disconnect();
return buffer.toString();
} catch (ConnectException ce) {
log.error("Weixin server connection timed out.");
} catch (Exception e) {
log.error("https request error:"+e.getMessage());
}finally{
if(outputStream != null)try{outputStream.close();}catch (Exception e) {}
if(inputStream != null)try{inputStream.close();;}catch (Exception e) {}
}
return null;
}
/**
* HTTPS json 请求
* @param requestUrl
* @param requestMethod
* @param msg
* @return 对字符串进行封装成JSON
*/
public static JSONObject httpRequestToJSON(String requestUrl, String requestMethod, String msg){
log.error("进入方法httpRequestToJSON-----");
String json = httpRequest(requestUrl, requestMethod, msg);
log.error("json-----"+json);
JSONObject jsonObject = null;
if(StringUtils.isNotBlank(json)) jsonObject = JSON.parseObject(json);
return jsonObject;
}
}
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.utils;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
public class HttpUtils {
/**
* get
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @return
* @throws Exception
*/
public static HttpResponse doGet(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpGet request = new HttpGet(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
return httpClient.execute(request);
}
/**
* post form
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param bodys
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
Map<String, String> bodys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (bodys != null) {
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
for (String key : bodys.keySet()) {
nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
request.setEntity(formEntity);
}
return httpClient.execute(request);
}
/**
* Post String
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (StringUtils.isNotBlank(body)) {
request.setEntity(new StringEntity(body, "utf-8"));
}
return httpClient.execute(request);
}
/**
* Post stream
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (body != null) {
request.setEntity(new ByteArrayEntity(body));
}
return httpClient.execute(request);
}
/**
* Put String
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPut(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (StringUtils.isNotBlank(body)) {
request.setEntity(new StringEntity(body, "utf-8"));
}
return httpClient.execute(request);
}
/**
* Put stream
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPut(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (body != null) {
request.setEntity(new ByteArrayEntity(body));
}
return httpClient.execute(request);
}
/**
* Delete
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @return
* @throws Exception
*/
public static HttpResponse doDelete(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
return httpClient.execute(request);
}
private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
StringBuilder sbUrl = new StringBuilder();
sbUrl.append(host);
if (!StringUtils.isBlank(path)) {
sbUrl.append(path);
}
if (null != querys) {
StringBuilder sbQuery = new StringBuilder();
for (Map.Entry<String, String> query : querys.entrySet()) {
if (0 < sbQuery.length()) {
sbQuery.append("&");
}
if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
sbQuery.append(query.getValue());
}
if (!StringUtils.isBlank(query.getKey())) {
sbQuery.append(query.getKey());
if (!StringUtils.isBlank(query.getValue())) {
sbQuery.append("=");
sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
}
}
}
if (0 < sbQuery.length()) {
sbUrl.append("?").append(sbQuery);
}
}
return sbUrl.toString();
}
private static HttpClient wrapClient(String host) {
HttpClient httpClient = new DefaultHttpClient();
if (host.startsWith("https://")) {
sslClient(httpClient);
}
return httpClient;
}
private static void sslClient(HttpClient httpClient) {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] xcs, String str) {
}
public void checkServerTrusted(X509Certificate[] xcs, String str) {
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx);
ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = httpClient.getConnectionManager();
SchemeRegistry registry = ccm.getSchemeRegistry();
registry.register(new Scheme("https", 443, ssf));
} catch (KeyManagementException ex) {
throw new RuntimeException(ex);
} catch (NoSuchAlgorithmException ex) {
throw new RuntimeException(ex);
}
}
}
\ No newline at end of file
package com.xxfc.platform.universal.utils;
import com.github.wxiaoqi.security.common.util.MD5Util;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/*
'微信支付服务器签名支付请求请求类
'============================================================================
'api说明:
'init(app_id, app_secret, partner_key, app_key);
'初始化函数,默认给一些参数赋值,如cmdno,date等。
'setKey(key_)'设置商户密钥
'getLasterrCode(),获取最后错误号
'GetToken();获取Token
'getTokenReal();Token过期后实时获取Token
'createMd5Sign(signParams);生成Md5签名
'genPackage(packageParams);获取package包
'createSHA1Sign(signParams);创建签名SHA1
'sendPrepay(packageParams);提交预支付
'getDebugInfo(),获取debug信息
'============================================================================
'*/
public class RequestHandler {
/** Token获取网关地址地址 */
private String tokenUrl;
/** 预支付网关url地址 */
private String gateUrl;
/** 查询支付通知网关URL */
private String notifyUrl;
/** 商户参数 */
private String appid;
private String appkey;
private String partnerkey;
private String appsecret;
private String key;
/** 请求的参数 */
private SortedMap parameters;
/** Token */
private String Token;
private String charset;
/** debug信息 */
private String debugInfo;
private String last_errcode;
private HttpServletRequest request;
private HttpServletResponse response;
/**
* 初始构造函数。
*
* @return
*/
public RequestHandler(HttpServletRequest request,
HttpServletResponse response) {
this.last_errcode = "0";
this.request = request;
this.response = response;
//this.charset = "GBK";
this.charset = "UTF-8";
this.parameters = new TreeMap();
// 验证notify支付订单网关
notifyUrl = "https://gw.tenpay.com/gateway/simpleverifynotifyid.xml";
}
/**
* 初始化函数。
*/
public void init(String app_id, String app_secret, String partner_key) {
this.last_errcode = "0";
this.Token = "token_";
this.debugInfo = "";
this.appid = app_id;
this.partnerkey = partner_key;
this.appsecret = app_secret;
this.key = partner_key;
}
public void init() {
}
/**
* 获取最后错误号
*/
public String getLasterrCode() {
return last_errcode;
}
/**
*获取入口地址,不包含参数值
*/
public String getGateUrl() {
return gateUrl;
}
/**
* 获取参数值
*
* @param parameter
* 参数名称
* @return String
*/
public String getParameter(String parameter) {
String s = (String) this.parameters.get(parameter);
return (null == s) ? "" : s;
}
//设置密钥
public void setKey(String key) {
this.partnerkey = key;
}
//设置微信密钥
public void setAppKey(String key){
this.appkey = key;
}
// 特殊字符处理
public String UrlEncode(String src) throws UnsupportedEncodingException {
return URLEncoder.encode(src, this.charset).replace("+", "%20");
}
// 获取package的签名包
public String genPackage(SortedMap<String, String> packageParams)
throws UnsupportedEncodingException {
String sign = createSign(packageParams);
StringBuffer sb = new StringBuffer();
Set es = packageParams.entrySet();
Iterator it = es.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
String v = (String) entry.getValue();
sb.append(k + "=" + UrlEncode(v) + "&");
}
// 去掉最后一个&
String packageValue = sb.append("sign=" + sign).toString();
// System.out.println("UrlEncode后 packageValue=" + packageValue);
return packageValue;
}
/**
* 创建md5摘要,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
*/
public String createSign(SortedMap<String, String> packageParams) {
StringBuffer sb = new StringBuffer();
Set es = packageParams.entrySet();
Iterator it = es.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
String v = (String) entry.getValue();
if (null != v && !"".equals(v) && !"sign".equals(k)
&& !"key".equals(k)) {
sb.append(k + "=" + v + "&");
}
}
sb.append("key=" + this.getKey());
System.out.println("md5 sb:" + sb);
String sign = MD5Util.MD5Encode(sb.toString(), this.charset).toUpperCase();
System.out.println("packge签名:" + sign);
return sign;
}
//输出XML
public String parseXML() {
StringBuffer sb = new StringBuffer();
sb.append("<xml>");
Set es = this.parameters.entrySet();
Iterator it = es.iterator();
while(it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
String k = (String)entry.getKey();
String v = (String)entry.getValue();
if(null != v && !"".equals(v) && !"appkey".equals(k)) {
sb.append("<" + k +">" + getParameter(k) + "</" + k + ">\n");
}
}
sb.append("</xml>");
return sb.toString();
}
/**
* 设置debug信息
*/
protected void setDebugInfo(String debugInfo) {
this.debugInfo = debugInfo;
}
public void setPartnerkey(String partnerkey) {
this.partnerkey = partnerkey;
}
public String getDebugInfo() {
return debugInfo;
}
public String getKey() {
return key;
}
}
package com.xxfc.platform.universal.utils;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XmlFriendlyReplacer;
import com.thoughtworks.xstream.io.xml.XppDriver;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class WeiXinPayUtil{
private final static String WeXinPay_URL ="https://api.mch.weixin.qq.com/pay/unifiedorder";
private final static String WeXinRefund_URL ="https://api.mch.weixin.qq.com/secapi/pay/refund";
public static String getPrepayId(String xml,String method){
return HTTPSUtils.httpRequest(WeXinPay_URL, method, xml);
}
@SuppressWarnings("deprecation")
private static XStream xstream = new XStream(/*new XppDriver() {
public HierarchicalStreamWriter createWriter(Writer out) {
return new PrettyPrintWriter(out) {
// 对所有xml节点的转换都增加CDATA标记
boolean cdata = true;
@SuppressWarnings({ "rawtypes" })
public void startNode(String name, Class clazz) {
super.startNode(name, clazz);
}
protected void writeText(QuickWriter writer, String text) {
if (cdata) {
writer.write("<![CDATA[");
writer.write(text);
writer.write("]]>");
} else {
writer.write(text);
}
}
};
}
}*/
new XppDriver(new
XmlFriendlyReplacer("_-", "_"){
public HierarchicalStreamWriter createWriter(Writer out) {
return new PrettyPrintWriter(out) {
// 对所有xml节点的转换都增加CDATA标记
boolean cdata = true;
@SuppressWarnings({ "rawtypes" })
public void startNode(String name, Class clazz) {
super.startNode(name, clazz);
}
protected void writeText(QuickWriter writer, String text) {
if (cdata) {
writer.write("<![CDATA[");
writer.write(text);
writer.write("]]>");
} else {
writer.write(text);
}
}
};
}
})
);
public static String toXml(WxPrepay wxPrepay){
xstream.alias("xml", wxPrepay.getClass());
return xstream.toXML(wxPrepay);
}
/**
* 获取随机字符串
* @return
*/
public static String getNonceStr() {
// 随机数
String currTime = getCurrTime();
// 8位日期
String strTime = currTime.substring(8, currTime.length());
// 四位随机数
String strRandom = buildRandom(4) + "";
// 10位序列号,可以自行调整。
return strTime + strRandom;
}
/**
* 获取当前时间 yyyyMMddHHmmss
* @return String
*/
public static String getCurrTime() {
Date now = new Date();
SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");
String s = outFormat.format(now);
return s;
}
/**
* 取出一个指定长度大小的随机正整数.
*
* @param length
* int 设定所取出随机数的长度。length小于11
* @return int 返回生成的随机数。
*/
public static int buildRandom(int length) {
int num = 1;
double random = Math.random();
if (random < 0.1) {
random = random + 0.1;
}
for (int i = 0; i < length; i++) {
num = num * 10;
}
return (int) ((random * num));
}
/**
* 元转换成分
* @param
* @return
*/
public static String getMoney(String amount) {
if(amount==null){
return "";
}
// 金额转化为分为单位
String currency = amount.replaceAll("\\$|\\¥|\\,", ""); //处理包含, ¥ 或者$的金额
int index = currency.indexOf(".");
int length = currency.length();
Long amLong = 0l;
if(index == -1){
amLong = Long.valueOf(currency+"00");
}else if(length - index >= 3){
amLong = Long.valueOf((currency.substring(0, index+3)).replace(".", ""));
}else if(length - index == 2){
amLong = Long.valueOf((currency.substring(0, index+2)).replace(".", "")+0);
}else{
amLong = Long.valueOf((currency.substring(0, index+1)).replace(".", "")+"00");
}
return amLong.toString();
}
/**
* ArrayToXml
* @param arr
* @return
*/
public static String ArrayToXml(Map<String, String> arr) {
String xml = "<xml>";
Iterator<Entry<String, String>> iter = arr.entrySet().iterator();
while (iter.hasNext()) {
Entry<String, String> entry = iter.next();
String key = entry.getKey();
String val = entry.getValue();
if (IsNumeric(val)) {
xml += "<" + key + ">" + val + "</" + key + ">";
} else
xml += "<" + key + "><![CDATA[" + val + "]]></" + key + ">";
}
xml += "</xml>";
return xml;
}
public static boolean IsNumeric(String str) {
if (str.matches("\\d *")) {
return true;
} else {
return false;
}
}
}
package com.xxfc.platform.universal.utils;
public class WxPrepay {
private String appid;
private String mch_id;
private String nonce_str;
private String sign;
private String body;
private String out_trade_no;
private String attach;
private String total_fee;
private String spbill_create_ip;
private String notify_url;
private String trade_type;
private String openid;
private String out_refund_no;
private String refund_fee;
private String op_user_id;
public WxPrepay(){};
public String getAppid() {
return appid;
}
public void setAppid(String appid) {
this.appid = appid;
}
public String getMch_id() {
return mch_id;
}
public void setMch_id(String mch_id) {
this.mch_id = mch_id;
}
public String getNonce_str() {
return nonce_str;
}
public void setNonce_str(String nonce_str) {
this.nonce_str = nonce_str;
}
public String getSign() {
return sign;
}
public void setSign(String sign) {
this.sign = sign;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getOut_trade_no() {
return out_trade_no;
}
public void setOut_trade_no(String out_trade_no) {
this.out_trade_no = out_trade_no;
}
public String getAttach() {
return attach;
}
public void setAttach(String attach) {
this.attach = attach;
}
public String getTotal_fee() {
return total_fee;
}
public void setTotal_fee(String total_fee) {
this.total_fee = total_fee;
}
public String getSpbill_create_ip() {
return spbill_create_ip;
}
public void setSpbill_create_ip(String spbill_create_ip) {
this.spbill_create_ip = spbill_create_ip;
}
public String getNotify_url() {
return notify_url;
}
public void setNotify_url(String notify_url) {
this.notify_url = notify_url;
}
public String getTrade_type() {
return trade_type;
}
public void setTrade_type(String trade_type) {
this.trade_type = trade_type;
}
public String getOpenid() {
return openid;
}
public void setOpenid(String openid) {
this.openid = openid;
}
public String getOut_refund_no() {
return out_refund_no;
}
public void setOut_refund_no(String out_refund_no) {
this.out_refund_no = out_refund_no;
}
public String getRefund_fee() {
return refund_fee;
}
public void setRefund_fee(String refund_fee) {
this.refund_fee = refund_fee;
}
public String getOp_user_id() {
return op_user_id;
}
public void setOp_user_id(String op_user_id) {
this.op_user_id = op_user_id;
}
}
package com.xxfc.platform.universal.weixin.api;
import java.util.Map.Entry;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.*;
import com.github.wxiaoqi.security.common.util.MD5;
import com.github.wxiaoqi.security.common.util.MD5Util;
import com.github.wxiaoqi.security.common.util.OrderUtil;
import com.github.wxiaoqi.security.common.util.process.SystemConfig;
import com.xxfc.platform.universal.utils.RequestHandler;
import com.xxfc.platform.universal.utils.WeiXinPayUtil;
import com.xxfc.platform.universal.utils.WxPrepay;
import com.xxfc.platform.universal.weixin.util.HTTPUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
/**
......@@ -43,10 +40,13 @@ public class WXPay {
* @param openid
* @return
*/
public static String webPay(String total_fee,String body,String notify_url,String orderNo,String spbill_create_ip,String openid){
public static String webPay(String total_fee,String body,String notify_url,String orderNo,String spbill_create_ip,String openid,String wyAppid){
WXPrepay prePay = new WXPrepay();
prePay.setAppid(SystemConfig.WINXIN_AppID);//pay.getAppId()
if (StringUtils.isBlank(wyAppid)){
wyAppid=SystemConfig.WINXIN_AppID;
}
prePay.setAppid(wyAppid);//pay.getAppId()
prePay.setBody(body);
prePay.setPartnerKey(SystemConfig.WINXIN_PARTNER_KEY);//pay.getPartnerKey()
prePay.setMch_id(SystemConfig.WINXIN_PARTNER);//pay.getPartnerId()
......@@ -65,7 +65,7 @@ public class WXPay {
String jsParam = "";
if (prepayid != null && prepayid.length() > 10) {
// 生成微信支付参数,此处拼接为完整的JSON格式,符合支付调起传入格式
jsParam = WXPay.createPackageValueWeb(SystemConfig.WINXIN_AppID, SystemConfig.WINXIN_PARTNER_KEY, prepayid);
jsParam = WXPay.createPackageValueWeb(wyAppid, SystemConfig.WINXIN_PARTNER_KEY, prepayid);
}
return jsParam;
......@@ -115,6 +115,7 @@ public class WXPay {
}
}
sb.append("key=" + AppKey);
log.info("-----签名sign==="+sb.toString());
String sign = MD5Util.MD5Encode(sb.toString(), "UTF-8").toUpperCase();
return sign;
}
......@@ -374,7 +375,93 @@ public class WXPay {
System.out.println(response_body);
}
public static String getPackage(String total_fee,String body,String notify_url,String orderNo,String spbill_create_ip,String openid,String appid,String appsecret){
Map<String,String> map = new LinkedHashMap<String,String>();
Random random = new Random();
String randomStr = MD5.GetMD5String(String.valueOf(random.nextInt(10000)));
String noceStr = MD5Util.MD5Encode(randomStr, "utf-8").toLowerCase();
SortedMap<String, String> packageParams = new TreeMap<String, String>();
packageParams.put("appid",appid);
packageParams.put("mch_id", SystemConfig.WINXIN_PARTNER);
packageParams.put("nonce_str", noceStr);
packageParams.put("body", body);
packageParams.put("attach", "");
packageParams.put("out_trade_no", orderNo);
// 这里写的金额为1 分到时修改
packageParams.put("total_fee",total_fee);
packageParams.put("spbill_create_ip", spbill_create_ip);
packageParams.put("notify_url", notify_url);
String trade_type = "JSAPI";
packageParams.put("trade_type", trade_type);
packageParams.put("openid", openid);
RequestHandler reqHandler = new RequestHandler(null, null);
reqHandler.init(appid, appsecret, SystemConfig.WINXIN_PARTNER_KEY);
String sign = reqHandler.createSign(packageParams);
WxPrepay wxPrepay = new WxPrepay();
wxPrepay.setAppid(appid);
wxPrepay.setMch_id(SystemConfig.WINXIN_PARTNER);
wxPrepay.setNonce_str(noceStr);
wxPrepay.setSign(sign);
wxPrepay.setBody(body);
wxPrepay.setOut_trade_no(orderNo);
wxPrepay.setTotal_fee(total_fee);
wxPrepay.setSpbill_create_ip(spbill_create_ip);
wxPrepay.setNotify_url(notify_url);
wxPrepay.setTrade_type(trade_type);
wxPrepay.setOpenid(openid);
wxPrepay.setAttach("");
String xml = WeiXinPayUtil.toXml(wxPrepay);
log.error("post_prepay_xml: " + xml);
//获取prepay_id
map = StringtoMap(WeiXinPayUtil.getPrepayId(xml,"POST"));
//获取prepay_id后,拼接最后请求支付所需要的package
SortedMap<String, String> finalpackage = new TreeMap<String, String>();
String timestamp = OrderUtil.GetTimestamp();
String packages = "prepay_id="+map.get("prepay_id");
finalpackage.put("appId", appid);
finalpackage.put("timeStamp", timestamp);
finalpackage.put("nonceStr", noceStr);
finalpackage.put("package", packages);
finalpackage.put("signType", "MD5");
//要签名
String finalsign = reqHandler.createSign(finalpackage);
String finaPackage = "\"appId\":\"" + appid + "\",\"timeStamp\":\"" + timestamp
+ "\",\"nonceStr\":\"" + noceStr + "\",\"package\":\""
+ packages + "\",\"signType\" : \"MD5" + "\",\"paySign\":\""
+ finalsign + "\"";
return finaPackage;
}
public static Map<String,String> StringtoMap(String str){
log.error("respon_prepay_xml: " + str);
Map<String,String> map = new LinkedHashMap<String,String>();
try {
Document document = DocumentHelper.parseText(str);
Element root = document.getRootElement();
List<Element> elementList = root.elements();
for(Element e : elementList){
map.put(e.getName(), e.getText());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return map;
}
}
\ No newline at end of file
......@@ -82,6 +82,9 @@ public class AliYunSmsBiz {
//旅游(上车通知)27
public static final String TEMPLATE_ID_PAY_J= "SMS_173345606";
//旅游(上车通知)27
public static final String PWD= "SMS_174990497";
//发送模板消息
......@@ -166,6 +169,9 @@ public class AliYunSmsBiz {
case 27 :
SmsService.sendTemplateToJson(phoneNumbers,params,TEMPLATE_ID_PAY_J);
break;
case 28 :
SmsService.sendTemplateToJson(phoneNumbers,params,PWD);
break;
}
......
......@@ -63,6 +63,11 @@ public class OrderPayBiz extends BaseBiz<OrderPayMapper, OrderPay> {
MQServiceBiZ mqServiceBiZ;
@Value("${universal.url}")
String weixinHost;
@Value("${wx.appid}")
private String wy_appid;
@Value("${wx.appSercet}")
private String wy_secret;
public JSONObject preparepay(OrderPayVo orderPayVo) {
......@@ -102,13 +107,16 @@ public class OrderPayBiz extends BaseBiz<OrderPayMapper, OrderPay> {
String sellerAccount = null;
if (type == 2 && payWay == 1) {
sellerAccount = SystemConfig.APP_PARTNER;
jsParam = WXPay.webPay(amount + "", orderPayVo.getBody(), notify_url, trade_no, orderPayVo.getBuyerIp(), orderPayVo.getBuyerAccount());
jsParam = WXPay.webPay(amount + "", orderPayVo.getBody(), notify_url, trade_no, orderPayVo.getBuyerIp(), orderPayVo.getBuyerAccount(),null);
} else if (type == 1 && payWay == 1) {
sellerAccount = SystemConfig.APP_PARTNER;
jsParam = WXPay.apppay(amount + "", orderPayVo.getBody(), notify_url, trade_no, orderPayVo.getBuyerIp(), 0);
} else if (type == 1 && payWay == 2) {
sellerAccount = SystemConfig.ALIPAY_PID;
jsParam = generateAliPayment(orderPayVo, notifyUrl);
}else if (type == 3 && payWay == 1){
sellerAccount = SystemConfig.APP_PARTNER;
jsParam = WXPay.webPay(amount + "", orderPayVo.getBody(), notify_url, trade_no, orderPayVo.getBuyerIp(), orderPayVo.getBuyerAccount(),wy_appid);
}
log.info("报名费回调路径jsParam:" + jsParam);
if (!StringUtils.isBlank(jsParam)) {
......@@ -294,7 +302,23 @@ public class OrderPayBiz extends BaseBiz<OrderPayMapper, OrderPay> {
"utf-8", SystemConfig.ALIPAY_PUBLIC_KEY, AlipayConstants.SIGN_TYPE_RSA2);
return alipayClient;
}
//balance 余额
//moneyFund 余额宝
//coupon 红包
//pcredit 花呗
//pcreditpayInstallment 花呗分期
//creditCard 信用卡
//creditCardExpress 信用卡快捷
//creditCardCartoon 信用卡卡通
//credit_group 信用支付类型(包含信用卡卡通、信用卡快捷、花呗、花呗分期)
//debitCardExpress 借记卡快捷
//mcard 商户预存卡
//pcard 个人预存卡
//promotion 优惠(包含实时优惠+商户优惠)
//voucher 营销券
//point 积分
//mdiscount 商户优惠
//bankPay
//支付宝APP支付方法
private String appOrderPay(AlipayClient alipayClient, OrderPayVo orderPayVo, String notifyUrl) {
BigDecimal realAmount = new BigDecimal(orderPayVo.getAmount().toString()).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_UP);
......@@ -303,6 +327,7 @@ public class OrderPayBiz extends BaseBiz<OrderPayMapper, OrderPay> {
request.setBizContent("{" +
"\"total_amount\":\"" + realAmount + "\"," +
"\"subject\":\"" + orderPayVo.getSubject() + "\"," +
"\"enable_pay_channels\":\"balance,coupon,creditCard,creditCardExpress,creditCardCartoon,pcredit,credit_group,moneyFund,debitCardExpress\"," +
"\"out_trade_no\":\"" + orderPayVo.getTradeNo() + "\"" +
" }");
request.setNotifyUrl(notifyUrl);
......
package com.xxfc.platform.universal.biz;
import lombok.Data;
/**
* 用户信息类
* @author Administrator
*/
@Data
public class UserMessage {
private String name;
private String idNumber;
}
package com.xxfc.platform.universal.biz;
import cn.hutool.core.codec.Base64;
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);
log.info("---session获取===="+frontSessionValue1+"---sessionId==="+session.getId());
if (StringUtils.isBlank(frontSessionValue1)) {
return null;
}
String openId = Base64.decodeStr(frontSessionValue1);
return openId;
}catch (Exception e){
e.printStackTrace();
return null;
}
}
}
......@@ -3,6 +3,7 @@ package com.xxfc.platform.universal.config;
import com.github.wxiaoqi.security.auth.client.interceptor.ServiceAuthRestInterceptor;
import com.github.wxiaoqi.security.auth.client.interceptor.UserAuthRestInterceptor;
import com.github.wxiaoqi.security.common.handler.GlobalExceptionHandler;
import com.xxfc.platform.universal.interceptor.WeChatH5LoginInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
......@@ -29,6 +30,10 @@ public class WebConfiguration implements WebMvcConfigurer {
addPathPatterns(getIncludePathPatterns()).addPathPatterns("/3p/**");
registry.addInterceptor(getUserAuthRestInterceptor()).
addPathPatterns(getIncludePathPatterns());
registry.addInterceptor(getUserAuthRestInterceptor()).
addPathPatterns(getIncludePathPatterns());
/* registry.addInterceptor(getWeChatH5LoginInterceptor()
).addPathPatterns(getWxIncludePathPatterns());*/
}
@Bean
......@@ -41,6 +46,10 @@ public class WebConfiguration implements WebMvcConfigurer {
return new UserAuthRestInterceptor();
}
@Bean
WeChatH5LoginInterceptor getWeChatH5LoginInterceptor() { return new WeChatH5LoginInterceptor();
}
/**
* 需要用户和服务认证判断的路径
* @return
......@@ -53,6 +62,14 @@ public class WebConfiguration implements WebMvcConfigurer {
Collections.addAll(list, urls);
return list;
}
private ArrayList<String> getWxIncludePathPatterns() {
ArrayList<String> list = new ArrayList<>();
String[] urls = {
"/info/**"
};
Collections.addAll(list, urls);
return list;
}
/* @Bean(name = "customTaskExecutor")
TaskExecutor getTaskExecutor(){
......
package com.xxfc.platform.universal.controller;
import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
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.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
/**
* 用户
*/
@RestController
@RequestMapping("info")
@IgnoreUserToken
@Slf4j
public class UserInfoController {
@Autowired
WeixinService weixinService;
@Value("${wx.sendUrl}")
private String sendUrl;
@RequestMapping(value = "getOpenId", method = RequestMethod.GET) //匹配的是href中的download请求
public ObjectRestResponse getOpenId(HttpServletRequest request) throws Exception {
boolean isWx = UserAgentUtil.isWexinBrowser(request);
if (isWx) {
//session里面获取用户信息
String openId=weixinService.getSession(request);
log.info("---进入方法getOpenId----openId===="+openId);
if (StringUtils.isBlank(openId)){
JSONObject json = new JSONObject();
json.put("sendUrl",sendUrl);
return ObjectRestResponse.createFailedResultWithObj(1001,"",json);
}
return ObjectRestResponse.succ(openId);
}
return ObjectRestResponse.succ();
}
}
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";
public static final String frontSessionKey = "frontWeixKey";
@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){
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;
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, HttpServletRequest request) {
log.info("-----微信回调userInfo---code=="+code+"----redirec_url==="+callback);
try {
authUser(code,request);
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,HttpServletRequest request){
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");
}
String encode = Base64.encode(openid);
HttpSession session = request.getSession();
session.removeAttribute(frontSessionKey);
session.setAttribute(frontSessionKey, encode);
}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 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;
}
}
......@@ -7,8 +7,10 @@ import com.github.wxiaoqi.security.admin.feign.UserFeign;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.xxfc.platform.universal.biz.UserMessage;
import com.xxfc.platform.universal.entity.IdInformation;
import com.xxfc.platform.universal.mapper.IdInformationMapper;
import com.xxfc.platform.universal.service.authenticationInterface.UserAuthentication;
import com.xxfc.platform.universal.utils.CertifHttpUtils;
import com.xxfc.platform.universal.utils.Validation;
import lombok.extern.slf4j.Slf4j;
......@@ -21,6 +23,7 @@ import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
......@@ -31,9 +34,16 @@ import java.text.SimpleDateFormat;
import java.util.*;
/**
* 认证业务
* @author Administrator
*/
@Service
@Slf4j
public class CertificationService {
@Autowired
private UserAuthentication authentication;
/**
* 认证相关的数据
*/
......@@ -209,17 +219,20 @@ public class CertificationService {
}
//map携带身份证和姓名进行认证
Map<String, String> authMap = new HashMap<>();
authMap.put(idCardName, (String) frontData.get(numberName));
authMap.put(cName, (String) frontData.get(cName));
//3.调用接口进行认证
String result = certificate(authMap);
// Map<String, String> authMap = new HashMap<>();
// authMap.put(idCardName, (String) frontData.get(numberName));
// authMap.put(cName, (String) frontData.get(cName));
// //3.调用接口进行认证
//
// boolean result = certificate(authMap);
boolean result = authentication.certificate(new UserMessage(){{
setIdNumber(number);
setName(name);
}} );
log.info("----认证结果result=========" + result);
//认证返回的参数是否为空
if (!StringUtils.isBlank(result)) {
Map<String, Object> map = (Map<String, Object>) JSONObject.parse(result);
log.info("----certifRet=========" + certifRet);
if (MapUtil.isNotEmpty(map) || certifResultCode.equals(map.get(certifRet))) {
if (result) {
//认证成功后存入保存到数据库
//获得身份证正面记录的身份证号和真实姓名
//设置姓名
......@@ -257,9 +270,6 @@ public class CertificationService {
// return ObjectRestResponse.succ(objRR.getData());
// }
}
}
return ObjectRestResponse.createFailedResult(ResultCode.INCOMPLETE_DATA,"网络异常,请稍后再试");
......@@ -267,7 +277,8 @@ public class CertificationService {
//认证
public String certificate(Map<String, String> querys) {
//认证
public boolean certificate(Map<String, String> querys) {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", "APPCODE " + cAppcode);
try {
......@@ -280,15 +291,27 @@ public class CertificationService {
*/
//获取response的body
if (statusCode == 200) {
return EntityUtils.toString(response.getEntity());
String result = EntityUtils.toString(response.getEntity());
log.info("----认证结果result=========" + result);
//认证返回的参数是否为空
if (!StringUtils.isBlank(result)) {
Map<String, Object> map = (Map<String, Object>) JSONObject.parse(result);
log.info("----certifRet=========" + certifRet);
if (MapUtil.isNotEmpty(map) || certifResultCode.equals(map.get(certifRet))) {
return true;
}
}
}
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
return null;
}
//身份证照片解析
public String imageParse(String imageUrl, String type) {
Map<String, String> headers = new HashMap<String, String>();
......@@ -317,10 +340,7 @@ public class CertificationService {
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
......
package com.xxfc.platform.universal.service.authenticationInterface;
import com.xxfc.platform.universal.biz.UserMessage;
import java.util.Map;
/**
* 用户认证类
* @author Administrator
*/
public interface UserAuthentication {
/**
* 用户认证方法
* @param message
* @return
*/
boolean certificate(UserMessage message) ;
}
package com.xxfc.platform.universal.service.authenticationInterface.impl;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONObject;
import com.xxfc.platform.universal.biz.UserMessage;
import com.xxfc.platform.universal.service.authenticationInterface.UserAuthentication;
import com.xxfc.platform.universal.utils.CertifHttpUtils;
import com.xxfc.platform.universal.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.util.EntityUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
/**
* 调用北京畅游互联科技有限公司接口
*
* @author Administrator
*/
@Service
@Slf4j
@Primary
public class BJCYAuthentication implements UserAuthentication {
private final String host = "http://aliyunverifyidcard.haoservice.com";
private final String path = "/idcard/VerifyIdcardv2";
private final String method = "GET";
private final String appcode = "ee7710ce92054cae9f6c040f6864e6a7";
private final String tokenHead = "Authorization";
private final String token="APPCODE " + appcode;
private final String cardNo ="cardNo";
private final String realName ="realName";
private final Integer resultCode=0;
private final String ret="error_code";
@Override
public boolean certificate(UserMessage message) {
Map<String, String> headers = new HashMap<String, String>();
headers.put(tokenHead, token);
Map<String, String> querys = new HashMap<String, String>();
querys.put(cardNo, message.getIdNumber());
querys.put(realName, message.getName());
try {
HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
StatusLine statusLine = response.getStatusLine();
log.error(response.toString());
int statusCode = statusLine.getStatusCode();
log.error(statusCode+"");
//获取response的body
if (statusCode == 200) {
String result = EntityUtils.toString(response.getEntity());
log.info("----认证结果result=========" + result);
//认证返回的参数是否为空
if (!StringUtils.isBlank(result)) {
Map<String, Object> map = (Map<String, Object>) JSONObject.parse(result);
log.info("----certifRet=========" + map);
if (MapUtil.isNotEmpty(map) || resultCode.equals(map.get(ret))) {
return true;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
package com.xxfc.platform.universal.service.authenticationInterface.impl;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONObject;
import com.xxfc.platform.universal.biz.UserMessage;
import com.xxfc.platform.universal.service.authenticationInterface.UserAuthentication;
import com.xxfc.platform.universal.utils.CertifHttpUtils;
import com.xxfc.platform.universal.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
/**
* 调用四川涪擎认证接口
*
* @author Administrator
*/
@Service
@Slf4j
public class XCFQAuthentication implements UserAuthentication {
private String cAppcode="acea1c8811f748b3a65815f11db357c4";
/**
* 认证相关的数据
*/
private String cHost = "https://idcert.market.alicloudapi.com";
private String cPath = "/idcard";
private String cMethod = "GET";
//响应:认证错误码字段名
private String certifRet = "status";
//响应:认证通过码
private String certifResultCode = "01";
//请求:身份证号字段名
private String idCardName = "idCard";
//请求:用户姓名字段名
private String cName = "name";
@Override
public boolean certificate(UserMessage message) {
//map携带身份证和姓名进行认证
Map<String, String> querys = new HashMap<>();
querys.put(idCardName, message.getIdNumber());
querys.put(cName, message.getName());
Map<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", "APPCODE " + cAppcode);
try {
log.info("----querys=========" + querys);
HttpResponse response = HttpUtils.doGet(cHost, cPath, cMethod, headers, querys);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
/**
* 状态码: 200 正常;400 URL无效;401 appCode错误; 403 次数用完; 500 API网管错误
*/
//获取response的body
if (statusCode == 200) {
String result = EntityUtils.toString(response.getEntity());
log.info("----认证结果result=========" + result);
//认证返回的参数是否为空
if (!StringUtils.isBlank(result)) {
Map<String, Object> map = (Map<String, Object>) JSONObject.parse(result);
log.info("----certifRet=========" + certifRet);
if (MapUtil.isNotEmpty(map) || certifResultCode.equals(map.get(certifRet))) {
return true;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
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