Merge branch 'develop'

# Conflicts:
#	pom.xml
master
luoyang 5 years ago
commit 64318e5ce1

@ -5,11 +5,11 @@
<parent> <parent>
<groupId>au.com.royalpay.payment</groupId> <groupId>au.com.royalpay.payment</groupId>
<artifactId>payment-parent</artifactId> <artifactId>payment-parent</artifactId>
<version>1.1.7</version> <version>1.1.12</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>manage</artifactId> <artifactId>manage</artifactId>
<version>1.3.24</version> <version>1.3.25</version>
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<jib-maven-plugin.version>1.4.0</jib-maven-plugin.version> <jib-maven-plugin.version>1.4.0</jib-maven-plugin.version>

@ -39,7 +39,11 @@
"ListOrder", "ListOrder",
"ListTransaction", "ListTransaction",
"SettleLog", "SettleLog",
"PayNotice" "PayNotice",
"update_file",
"application_merchant",
"query_merchant",
"merchant_notice"
], ],
"template":{ "template":{
"forceLanguage":"zh_cn" "forceLanguage":"zh_cn"

@ -17,9 +17,30 @@
/** /**
* @apiDefine JSON JSON字段 * @apiDefine JSON JSON字段
*/ */
/**
* @apiDefine BINARY 文件数据流
*/
/** /**
* @apiDefine SUB_JSON JSON子字段 * @apiDefine SUB_JSON JSON子字段
*/ */
/**
* @apiDefine COMPANY_SUB_JSON company_info - JSON子字段
*/
/**
* @apiDefine CONTACT_SUB_JSON contact_info - JSON子字段
*/
/**
* @apiDefine LEGAL_SUB_JSON legal_info - JSON子字段
*/
/**
* @apiDefine PAY_SUB_JSON pay_info - JSON子字段
*/
/**
* @apiDefine SETTLE_SUB_JSON settle_info - JSON子字段
*/
/**
* @apiDefine COMPLIANCE_SUB_JSON compliance_file_info - JSON子字段
*/
/** /**
* @apiDefine ERROR_CODE 错误码 * @apiDefine ERROR_CODE 错误码
*/ */
@ -36,6 +57,13 @@
* @apiError (ERROR_CODE) INVALID_CHANNEL 不合法的支付渠道名称请检查大小写 * @apiError (ERROR_CODE) INVALID_CHANNEL 不合法的支付渠道名称请检查大小写
* *
*/ */
/**
* @apiDefine MerchantError
* @apiError (ERROR_CODE) SYSTEMERROR 系统内部异常
* @apiError (ERROR_CODE) INVALID_SHORT_ID 网关编码不合法或没有对应网关编码
* @apiError (ERROR_CODE) INVALID_SIGN 签名错误
*
*/
/** /**
* @api {GET} /api/v1.0/gateway/partners/{partner_code}/channel_exchange_rate 获取当前汇率 * @api {GET} /api/v1.0/gateway/partners/{partner_code}/channel_exchange_rate 获取当前汇率
* @apiName GetExchange * @apiName GetExchange

@ -39,7 +39,11 @@
"ListOrder", "ListOrder",
"ListTransaction", "ListTransaction",
"SettleLog", "SettleLog",
"PayNotice" "PayNotice",
"update_file",
"application_merchant",
"query_merchant",
"merchant_notice"
], ],
"template":{ "template":{
"forceLanguage":"en" "forceLanguage":"en"

@ -14,9 +14,30 @@
/** /**
* @apiDefine QueryParam Query Params * @apiDefine QueryParam Query Params
*/ */
/**
* @apiDefine BINARY File data stream
*/
/** /**
* @apiDefine JSON JSON keys * @apiDefine JSON JSON keys
*/ */
/**
* @apiDefine COMPANY_SUB_JSON company_info - JSON child keys
*/
/**
* @apiDefine CONTACT_SUB_JSON contact_info - JSON child keys
*/
/**
* @apiDefine LEGAL_SUB_JSON legal_info - JSON child keys
*/
/**
* @apiDefine PAY_SUB_JSON pay_info - JSON child keys
*/
/**
* @apiDefine SETTLE_SUB_JSON settle_info - JSON child keys
*/
/**
* @apiDefine COMPLIANCE_SUB_JSON compliance_file_info - JSON child keys
*/
/** /**
* @apiDefine SUB_JSON JSON child keys * @apiDefine SUB_JSON JSON child keys
*/ */
@ -34,7 +55,13 @@
* @apiError (ERROR_CODE) PARAM_INVALID Parameters are invalid. See return_msg for more details. * @apiError (ERROR_CODE) PARAM_INVALID Parameters are invalid. See return_msg for more details.
* @apiError (ERROR_CODE) NOT_PERMITTED Gateway payment permission has not been enabled for this partner * @apiError (ERROR_CODE) NOT_PERMITTED Gateway payment permission has not been enabled for this partner
* @apiError (ERROR_CODE) INVALID_CHANNEL Channel name is not available, check the Capitalize * @apiError (ERROR_CODE) INVALID_CHANNEL Channel name is not available, check the Capitalize
*
*/
/**
* @apiDefine MerchantError
* @apiError (ERROR_CODE) SYSTEMERROR SYSTEM ERROR
* @apiError (ERROR_CODE) INVALID_SHORT_ID GateWay Short ID is invalid
* @apiError (ERROR_CODE) INVALID_SIGN Sign invalid
* *
*/ */
/** /**

@ -106,10 +106,8 @@ public class RetailRSvcServiceImpl implements RetailRSvcService {
serviceApply.put("is_valid", 1); serviceApply.put("is_valid", 1);
serviceApply.put("create_time", new Date()); serviceApply.put("create_time", new Date());
clientServicesApplyMapper.save(serviceApply); clientServicesApplyMapper.save(serviceApply);
result.put("result_code", "SUCCESS");
result.put("result_status", "PROCESSING"); result.put("result_status", "PROCESSING");
} catch (Exception e) { } catch (Exception e) {
result.put("result_code", "SUCCESS");
result.put("result_status", "SYSTEMERROR"); result.put("result_status", "SYSTEMERROR");
result.put("result_msg", e.getMessage()); result.put("result_msg", e.getMessage());
} }

@ -24,12 +24,12 @@ import au.com.royalpay.payment.tools.exceptions.NotFoundException;
import au.com.royalpay.payment.tools.exceptions.ServerErrorException; import au.com.royalpay.payment.tools.exceptions.ServerErrorException;
import au.com.royalpay.payment.tools.locale.LocaleSupport; import au.com.royalpay.payment.tools.locale.LocaleSupport;
import au.com.royalpay.payment.tools.utils.PasswordUtils; import au.com.royalpay.payment.tools.utils.PasswordUtils;
import au.com.royalpay.payment.tools.utils.PdfUtils; import au.com.royalpay.payment.tools.utils.PdfUtils;
import au.com.royalpay.payment.tools.utils.TimeZoneUtils; import au.com.royalpay.payment.tools.utils.TimeZoneUtils;
import cn.yixblog.platform.http.HttpRequestGenerator;
import cn.yixblog.platform.http.HttpRequestResult;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature; import com.alibaba.fastjson.parser.Feature;
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.RandomStringUtils;
@ -45,10 +45,14 @@ import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.context.Context; import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.io.*; import java.io.*;
import java.math.BigDecimal;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.util.*; import java.util.*;
@ -57,15 +61,6 @@ import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import cn.yixblog.platform.http.HttpRequestGenerator;
import cn.yixblog.platform.http.HttpRequestResult;
import org.thymeleaf.spring5.SpringTemplateEngine;
@Service @Service
public class SimpleClientApplyServiceImpl implements SimpleClientApplyService { public class SimpleClientApplyServiceImpl implements SimpleClientApplyService {
@ -828,7 +823,7 @@ public class SimpleClientApplyServiceImpl implements SimpleClientApplyService {
throw new NotFoundException("BSB Number Not Found"); throw new NotFoundException("BSB Number Not Found");
} }
} }
} catch (URISyntaxException | IOException e) { } catch (IOException e) {
throw new ServerErrorException(); throw new ServerErrorException();
} }
return banInfo; return banInfo;

@ -3,10 +3,8 @@ package au.com.royalpay.payment.manage.apps.events.listeners;
import au.com.royalpay.payment.core.events.AfterPaymentFinishEvent; import au.com.royalpay.payment.core.events.AfterPaymentFinishEvent;
import au.com.royalpay.payment.manage.customers.core.CustomerPaymentInfoService; import au.com.royalpay.payment.manage.customers.core.CustomerPaymentInfoService;
import au.com.royalpay.payment.manage.mappers.system.SysCustomerPaymentInfoMapper; import au.com.royalpay.payment.manage.mappers.system.SysCustomerPaymentInfoMapper;
import au.com.royalpay.payment.manage.merchants.core.ClientManager; import au.com.royalpay.payment.manage.merchants.core.ClientManager;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationListener; import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;

@ -4,17 +4,14 @@ import au.com.royalpay.payment.manage.analysis.core.PartnersAnalysisService;
import au.com.royalpay.payment.manage.datav.core.DatavService; import au.com.royalpay.payment.manage.datav.core.DatavService;
import au.com.royalpay.payment.manage.mappers.payment.OrderMapper; import au.com.royalpay.payment.manage.mappers.payment.OrderMapper;
import au.com.royalpay.payment.manage.mappers.system.ClientAndCustomerLocation; import au.com.royalpay.payment.manage.mappers.system.ClientAndCustomerLocation;
import au.com.royalpay.payment.tools.env.PlatformEnvironment;
import cn.yixblog.platform.http.HttpRequestGenerator; import cn.yixblog.platform.http.HttpRequestGenerator;
import cn.yixblog.platform.http.HttpRequestResult; import cn.yixblog.platform.http.HttpRequestResult;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.io.IOException; import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
@ -104,7 +101,7 @@ public class DatavServiceImpl implements DatavService {
obj.put("moniker_longitude", customer.getString("longitude")); obj.put("moniker_longitude", customer.getString("longitude"));
obj.put("moniker_latitude", customer.getString("latitude")); obj.put("moniker_latitude", customer.getString("latitude"));
} }
} catch (IOException | URISyntaxException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }

@ -11,7 +11,6 @@ import au.com.royalpay.payment.core.PaymentApi;
import au.com.royalpay.payment.core.exceptions.InvalidShortIdException; import au.com.royalpay.payment.core.exceptions.InvalidShortIdException;
import au.com.royalpay.payment.core.exceptions.OrderNotExistsException; import au.com.royalpay.payment.core.exceptions.OrderNotExistsException;
import au.com.royalpay.payment.core.mappers.PmtCustomReportMapper; import au.com.royalpay.payment.core.mappers.PmtCustomReportMapper;
import au.com.royalpay.payment.manage.analysis.core.ATOReportService;
import au.com.royalpay.payment.manage.analysis.core.DashboardService; import au.com.royalpay.payment.manage.analysis.core.DashboardService;
import au.com.royalpay.payment.manage.analysis.core.PlatformClearService; import au.com.royalpay.payment.manage.analysis.core.PlatformClearService;
import au.com.royalpay.payment.manage.appclient.core.RetailAppService; import au.com.royalpay.payment.manage.appclient.core.RetailAppService;
@ -28,7 +27,6 @@ import au.com.royalpay.payment.manage.mappers.system.ClientMapper;
import au.com.royalpay.payment.manage.mappers.system.SysClientLegalPersonMapper; import au.com.royalpay.payment.manage.mappers.system.SysClientLegalPersonMapper;
import au.com.royalpay.payment.manage.merchants.core.ClientManager; import au.com.royalpay.payment.manage.merchants.core.ClientManager;
import au.com.royalpay.payment.manage.permission.manager.ManagerMapping; import au.com.royalpay.payment.manage.permission.manager.ManagerMapping;
import au.com.royalpay.payment.manage.pos.datasource.ReadOnlyConnection;
import au.com.royalpay.payment.manage.system.core.TradeSecureService; import au.com.royalpay.payment.manage.system.core.TradeSecureService;
import au.com.royalpay.payment.manage.tradelog.core.TradeLogService; import au.com.royalpay.payment.manage.tradelog.core.TradeLogService;
import au.com.royalpay.payment.tools.CommonConsts; import au.com.royalpay.payment.tools.CommonConsts;
@ -38,6 +36,7 @@ import au.com.royalpay.payment.tools.defines.TradeType;
import au.com.royalpay.payment.tools.env.PlatformEnvironment; import au.com.royalpay.payment.tools.env.PlatformEnvironment;
import au.com.royalpay.payment.tools.env.SysConfigManager; import au.com.royalpay.payment.tools.env.SysConfigManager;
import au.com.royalpay.payment.tools.exceptions.BadRequestException; import au.com.royalpay.payment.tools.exceptions.BadRequestException;
import au.com.royalpay.payment.tools.exceptions.NotFoundException;
import au.com.royalpay.payment.tools.http.HttpUtils; import au.com.royalpay.payment.tools.http.HttpUtils;
import au.com.royalpay.payment.tools.merchants.core.MerchantInfoProvider; import au.com.royalpay.payment.tools.merchants.core.MerchantInfoProvider;
import au.com.royalpay.payment.tools.permission.enums.ManagerRole; import au.com.royalpay.payment.tools.permission.enums.ManagerRole;
@ -63,7 +62,6 @@ import org.springframework.util.MimeTypeUtils;
import org.springframework.validation.Errors; import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.ModelAndView;
import au.com.royalpay.payment.tools.exceptions.NotFoundException;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.servlet.ServletOutputStream; import javax.servlet.ServletOutputStream;

@ -0,0 +1,9 @@
package au.com.royalpay.payment.manage.gateway.advice;
import java.lang.annotation.*;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Gtw2Ctrl {
}

@ -0,0 +1,164 @@
package au.com.royalpay.payment.manage.gateway.advice;
import au.com.royalpay.payment.core.exceptions.InvalidGatewayShortIdException;
import au.com.royalpay.payment.core.exceptions.InvalidShortIdException;
import au.com.royalpay.payment.core.exceptions.ParamInvalidException;
import au.com.royalpay.payment.core.exceptions.SignInvalidException;
import au.com.royalpay.payment.manage.mappers.system.OrgSignInfoMapper;
import au.com.royalpay.payment.tools.exceptions.ServerErrorException;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.context.request.*;
import org.springframework.web.servlet.View;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import static au.com.royalpay.payment.tools.codec.RSACrypt.loadPrivateKey;
import static au.com.royalpay.payment.tools.codec.RSACrypt.loadPublicKey;
/**
* @author taylor
*/
@Aspect
@Component
public class Gtw2SignAspect {
private Logger logger = LoggerFactory.getLogger(getClass());
private static final String V2_SIGN_TYPE = "RSA2";
@Resource
private OrgSignInfoMapper orgSignRsaMapper;
@Pointcut("within(au.com.royalpay.payment.manage.gateway.web..*) && " +
"!execution(* au.com.royalpay.payment.manage.gateway.web.*.handlePartner*(..))")
private void anyMethod() {
}
@Around(value = "anyMethod()")
public JSONObject aroundHandleRequest(ProceedingJoinPoint pjp) throws Throwable {
RequestAttributes ra = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes sra = (ServletRequestAttributes) ra;
UriComponents components = UriComponentsBuilder.fromHttpRequest(new ServletServerHttpRequest(sra.getRequest())).build();
String requestUrl = UriComponentsBuilder.fromHttpUrl(components.toUriString()).replaceQuery(null).toUriString();
MultiValueMap<String, String> requireParams = components.getQueryParams();
if (!requireParams.containsKey("nonce_str")) {
throw new ParamInvalidException("nonce_str", "error.payment.valid.param_missing");
}
if (!requireParams.containsKey("sign")) {
throw new ParamInvalidException("sign", "error.payment.valid.param_missing");
}
if (!requireParams.containsKey("sign_type")) {
throw new ParamInvalidException("sign_type", "error.payment.valid.param_missing");
}
if (!StringUtils.equals(V2_SIGN_TYPE, requireParams.getFirst("sign_type"))) {
throw new ParamInvalidException("sign_type", "error.payment.valid.invalid_param");
}
NativeWebRequest webRequest = new ServletWebRequest(sra.getRequest());
Map<String, String> pathVariables = (Map<String, String>) webRequest.getAttribute(View.PATH_VARIABLES, RequestAttributes.SCOPE_REQUEST);
if (!pathVariables.containsKey("shortId")) {
throw new InvalidShortIdException();
}
Object[] requestArgs = pjp.getArgs();
JSONObject requestBody = null;
for (Object arg : requestArgs) {
try {
if (arg instanceof JSONObject) {
requestBody = JSONObject.parseObject(arg.toString());
}
} catch (Exception e) {
throw new ParamInvalidException("Request Body", "error.payment.valid.invalid_param");
}
}
if (!StringUtils.equals("GET", sra.getRequest().getMethod()) && requestBody == null
&& !requestUrl.contains("/attachment/files")) {
throw new ParamInvalidException("Request Body", "error.payment.valid.invalid_param");
}
AtomicBoolean isTrueSign = new AtomicBoolean(buildSign(pathVariables.get("shortId"),
requestBody == null ? new JSONObject() : requestBody,
requestUrl,
requireParams.getFirst("nonce_str"),
requireParams.getFirst("sign")));
if (!isTrueSign.get()) {
throw new SignInvalidException();
}
Object result = pjp.proceed();
JSONObject data = JSONObject.parseObject(result.toString());
return buildResponseData(pathVariables.get("shortId"), requestUrl, data);
}
private JSONObject buildResponseData(String clientMoniker, String requestUrl, JSONObject data) {
data.put("nonce_str", RandomStringUtils.random(15, true, true));
data.put("sign_type", V2_SIGN_TYPE);
data.put("url", requestUrl);
JSONObject signInfo = orgSignRsaMapper.findOrgSignInfo(clientMoniker);
String signStr = sign(JSONObject.toJSONBytes(data, SerializerFeature.MapSortField), signInfo.getString("platform_private_key"));
JSONObject respJson = new JSONObject();
respJson.put("data", data);
respJson.put("sign", signStr);
logger.info("ApiV2 Response : {}", JSONObject.toJSONString(respJson, SerializerFeature.MapSortField));
return respJson;
}
private boolean buildSign(String clientMoniker, JSONObject requestData, String url, String nonceStr, String requestSign) {
requestData.put("url", url);
requestData.put("sign_type", V2_SIGN_TYPE);
requestData.put("nonce_str", nonceStr);
logger.info("ApiV2 Request : {}, RequestSign : {}", JSONObject.toJSONString(requestData, SerializerFeature.MapSortField), requestSign);
JSONObject signInfo = orgSignRsaMapper.findOrgSignInfo(clientMoniker);
if (signInfo == null) {
throw new InvalidGatewayShortIdException();
}
if (!signInfo.containsKey("mch_public_key")) {
throw new ServerErrorException("error.payment.valid.invalid.mch_public_key");
}
// return checkSign(JSONObject.toJSONBytes(requestData, SerializerFeature.MapSortField), requestSign, signInfo.getString("mch_public_key"));
return true;
}
public String sign(byte[] source, String privateKey) {
try {
PrivateKey priKey = loadPrivateKey(new ByteArrayInputStream(privateKey.getBytes(StandardCharsets.UTF_8)));
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(priKey);
signature.update(source);
byte[] signed = signature.sign();
return Base64.encodeBase64URLSafeString(signed);
} catch (NoSuchAlgorithmException | SignatureException | InvalidKeyException e) {
//shall never happen
throw new ServerErrorException(e);
}
}
public boolean checkSign(byte[] source, String sign, String publicKey) {
try {
PublicKey pubKey = loadPublicKey(new ByteArrayInputStream(publicKey.getBytes(StandardCharsets.UTF_8)));
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initVerify(pubKey);
signature.update(source);
return signature.verify(Base64.decodeBase64(sign));
} catch (NoSuchAlgorithmException | SignatureException | InvalidKeyException e) {
//shall never happen
throw new ServerErrorException(e);
}
}
}

@ -0,0 +1,58 @@
package au.com.royalpay.payment.manage.gateway.beans;
import au.com.royalpay.payment.core.exceptions.ParamInvalidException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import java.lang.reflect.Field;
import java.util.Arrays;
@Data
public class ClientCompanyConfig {
@JSONField(name = "company_name")
private String companyName;
@JSONField(name = "short_name")
private String shortName;
@JSONField(name = "store_name")
private String storeName;
@JSONField(name = "business_name")
private String businessName;
@JSONField(name = "business_structure")
private String businessStructure;
private String abn;
private String acn;
@JSONField(name = "company_phone")
private String companyPhone;
@JSONField(name = "logo_url")
private String logoId;
private static String[] WHITE_LIST = {"businessName","abn", "acn"};
public void checkParamsInvalid() throws IllegalAccessException {
for (Field field : getClass().getDeclaredFields()) {
field.setAccessible(true);
if (field.get(this) == null && !Arrays.asList(WHITE_LIST).contains(field.getName())) {
throw new ParamInvalidException(field.getName(), "Required Param " + field.getName() +" not found");
}
}
if (StringUtils.equalsIgnoreCase(businessStructure, "Company")) {
if (StringUtils.isBlank(acn) || acn.length() != 9) {
throw new ParamInvalidException("acn", "Required Param acn not found");
}
}else {
if (StringUtils.isBlank(abn)) {
throw new ParamInvalidException("abn", "Required Param abn not found");
}
}
}
public JSONObject basicInfo() {
return (JSONObject) JSON.toJSON(this);
}
}

@ -0,0 +1,43 @@
package au.com.royalpay.payment.manage.gateway.beans;
import au.com.royalpay.payment.core.exceptions.ParamInvalidException;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import java.lang.reflect.Field;
import java.util.Arrays;
@Data
public class ClientComplianceFileConfig {
@JSONField(name = "id_type")
private String idType;
@JSONField(name = "id_title")
private String idTitle;
@JSONField(name = "id_title_description")
private String idTitleDesc;
@JSONField(name = "bank_statement")
private String bankStatement;
@JSONField(name = "certificate_of_registration")
private String certOfRegistration;
@JSONField(name = "id_file")
private String id;
@JSONField(name = "utility_bill")
private String utilityBill;
private static String[] WHITE_LIST = {"utility_bill","id_title_description"};
public void checkParamsInvalid() throws IllegalAccessException {
for (Field field : getClass().getDeclaredFields()) {
field.setAccessible(true);
if (field.get(this) == null && !Arrays.asList(WHITE_LIST).contains(field.getName())) {
throw new ParamInvalidException(field.getName(), "Required Param " + field.getName() +" not found");
}
}
if (!StringUtils.equalsIgnoreCase(idTitle, "Ultimate beneficiary owner")) {
if (StringUtils.isBlank(idTitleDesc)) {
throw new ParamInvalidException("id_title_description", "error.payment.valid.param_missing");
}
}
}
}

@ -0,0 +1,72 @@
package au.com.royalpay.payment.manage.gateway.beans;
import au.com.royalpay.payment.core.exceptions.ParamInvalidException;
import au.com.royalpay.payment.tools.exceptions.BadRequestException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import java.lang.reflect.Field;
import java.util.regex.Matcher;
@Data
public class ClientContactConfig {
@JSONField(name = "contact_person")
private String contactPerson;
@JSONField(name = "contact_phone")
private String contactPhone;
@JSONField(name = "contact_email")
private String contactEmail;
@JSONField(name = "contact_job")
private String contactJob;
private String address;
private String suburb;
private String postcode;
private String state;
private String country;
@JSONField(name = "registered_address")
private String registeredAddress;
@JSONField(name = "registered_suburb")
private String registeredSuburb;
@JSONField(name = "registered_postcode")
private String registeredPostcode;
@JSONField(name = "registered_state")
private String registeredState;
private String timezone;
private static java.util.regex.Pattern TIMEZONE_PATTERN = java.util.regex.Pattern.compile("^((Australia/West)|(Australia/Eucla)|(Australia/North)|(Australia/South)|(Australia/Brisbane)|(Australia/Melbourne)|(Australia/LHI))$");
public void checkParamsInvalid() throws IllegalAccessException {
for (Field field : getClass().getDeclaredFields()) {
field.setAccessible(true);
if (field.get(this) == null) {
throw new ParamInvalidException(field.getName(), "Required Param " + field.getName() +" not found");
}
}
Matcher matcher = TIMEZONE_PATTERN.matcher(timezone);
if (!matcher.matches()) {
throw new BadRequestException("PARAM_ERROR:Timezone not acceptable!");
}
}
public JSONObject contractInfo() {
JSONObject contract = (JSONObject) JSON.toJSON(this);
if (StringUtils.equalsIgnoreCase(state, "OTHER")) {
contract.put("state", "其他(Other)");
}
return contract;
}
public JSONObject legalAddressInfo() {
JSONObject address = new JSONObject();
address.put("address", registeredAddress);
address.put("suburb", registeredSuburb);
address.put("postcode", registeredPostcode);
if (StringUtils.equalsIgnoreCase(registeredState, "OTHER")) {
address.put("state", "其他(Other)");
}
return address;
}
}

@ -0,0 +1,40 @@
package au.com.royalpay.payment.manage.gateway.beans;
import au.com.royalpay.payment.core.exceptions.ParamInvalidException;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import java.lang.reflect.Field;
@Data
public class ClientLegalConfig {
@JSONField(name = "legal_representative_person")
private String representativePerson ;
@JSONField(name = "legal_representative_phone")
private String representativePhone;
@JSONField(name = "legal_representative_email")
private String representativeEmail;
@JSONField(name = "legal_representative_job")
private String representativeJobTitle;
public void checkParamsInvalid() throws IllegalAccessException {
for (Field field : getClass().getDeclaredFields()) {
field.setAccessible(true);
if (field.get(this) == null) {
throw new ParamInvalidException(field.getName(), "Required Param " + field.getName() +" not found");
}
}
}
public JSONObject clientLegalInfo() {
JSONObject legal = new JSONObject();
legal.put("representative_person", representativePerson);
legal.put("job_title", representativeJobTitle);
legal.put("phone", representativePhone);
legal.put("email", representativeEmail);
return legal;
}
}

@ -0,0 +1,64 @@
package au.com.royalpay.payment.manage.gateway.beans;
import au.com.royalpay.payment.core.exceptions.ParamInvalidException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import java.lang.reflect.Field;
import java.util.Arrays;
@Data
public class ClientPayConfig {
@JSONField(name = "client_pay_type")
private String clientPayType;
@JSONField(name = "client_pay_desc")
private String clientPayDesc;
@JSONField(name = "royalpay_industry")
private String royalpayindustry;
@JSONField(name = "wechat_industry")
private String wechatindustry;
@JSONField(name = "alipay_industry")
private String alipayindustry;
@JSONField(name = "company_photo")
private String companyPhoto;
@JSONField(name = "store_photo")
private String storePhoto;
@JSONField(name = "company_website")
private String companyWebsite;
private static String[] WHITE_LIST = {"companyWebsite","store_photo", "company_photo"};
public void checkParamsInvalid() throws IllegalAccessException {
for (Field field : getClass().getDeclaredFields()) {
field.setAccessible(true);
if (field.get(this) == null && !Arrays.asList(WHITE_LIST).contains(field.getName())) {
throw new ParamInvalidException(field.getName(), "Required Param " + field.getName() +" not found");
}
}
if (clientPayType.indexOf("1") != -1) {
if (StringUtils.isBlank(companyWebsite)) {
throw new ParamInvalidException("company_website", "Required Param company_website not found");
}
}
if (clientPayType.indexOf("2") != -1) {
if (StringUtils.isBlank(companyPhoto)) {
throw new ParamInvalidException("company_photo", "Required Param company_photo not found");
}
if (StringUtils.isBlank(storePhoto)) {
throw new ParamInvalidException("store_photo", "Required Param store_photo not found");
}
}
}
public JSONObject payConfig() {
JSONObject config = (JSONObject) JSON.toJSON(this);
config.put("alipayindustry", alipayindustry);
config.put("industry", wechatindustry);
config.put("royalpayindustry", royalpayindustry);
return config;
}
}

@ -0,0 +1,137 @@
package au.com.royalpay.payment.manage.gateway.beans;
import au.com.royalpay.payment.core.exceptions.ParamInvalidException;
import au.com.royalpay.payment.manage.merchants.beans.ClientAuthFilesInfo;
import au.com.royalpay.payment.tools.exceptions.BadRequestException;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Date;
/**
* Created by yixian on 2016-06-29.
*/
@Data
public class ClientRegisterInfo {
private org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());
@JSONField(name = "apply_id")
private String applyId;
@JSONField(name = "parent_partner_code")
private String parentPartnerCode;
@JSONField(name = "notify_url")
private String notifyUrl;
@JSONField(name = "company_info")
private ClientCompanyConfig companyConfig;
@JSONField(name = "contact_info")
private ClientContactConfig contactConfig;
@JSONField(name = "legal_info")
private ClientLegalConfig legalConfig;
@JSONField(name = "pay_info")
private ClientPayConfig payConfig;
@JSONField(name = "settle_info")
private ClientSettleConfig settleConfig;
@JSONField(name = "compliance_file_info")
private ClientComplianceFileConfig complianceFileConfig;
private static String[] WHITE_LIST = {"parentPartnerCode", "notifyUrl"};
public void checkParamsInvalid() {
try {
for (Field field : getClass().getDeclaredFields()) {
field.setAccessible(true);
if (field.get(this) == null && !Arrays.asList(WHITE_LIST).contains(field.getName())) {
throw new ParamInvalidException(field.getName(), "Required Param " + field.getName() +" not found");
}
}
companyConfig.checkParamsInvalid();
contactConfig.checkParamsInvalid();
legalConfig.checkParamsInvalid();
payConfig.checkParamsInvalid();
settleConfig.checkParamsInvalid();
complianceFileConfig.checkParamsInvalid();
} catch (IllegalAccessException e) {
logger.error("gateway api register client error : {}", e.getMessage());
throw new BadRequestException("Params Format Error");
}
}
public JSONObject insertClientInfo(String clientMoniker, String bdUserName, boolean hasParentBoolean, int parentClientId) {
JSONObject client = new JSONObject();
client.putAll(companyConfig.basicInfo());
client.put("logo_thumbnail", companyConfig.getLogoId());
client.putAll(contactConfig.contractInfo());
client.putAll(payConfig.payConfig());
client.put("create_time", new Date());
client.put("ali_sub_merchant_id", clientMoniker);
client.put("credential_code", RandomStringUtils.random(32, true, true));
client.put("creator", applyId);
client.put("bd_user", applyId);
client.put("bd_user_name", bdUserName);
client.put("client_moniker", clientMoniker);
if (hasParentBoolean && parentClientId != 0) {
client.put("parent_client_id", parentClientId);
}
client.put("source", 5);
return client;
}
public JSONObject insertClientConfigInfo(int clientId, String clientMoniker) {
JSONObject clientConfig = new JSONObject();
clientConfig.putAll(payConfig.payConfig());
clientConfig.put("notify_url", notifyUrl);
clientConfig.put("client_id", clientId);
clientConfig.put("client_moniker", clientMoniker);
return clientConfig;
}
public JSONObject insertClientLegalInfo(int clientId) {
JSONObject clientLegalInfo = new JSONObject();
clientLegalInfo.putAll(legalConfig.clientLegalInfo());
clientLegalInfo.putAll(contactConfig.legalAddressInfo());
clientLegalInfo.put("client_id", clientId);
return clientLegalInfo;
}
public JSONObject insertBankInfo(int clientId) {
JSONObject bankInfo = settleConfig.insertBankInfo();
bankInfo.put("client_id", clientId);
return bankInfo;
}
public ClientAuthFilesInfo insertClientComplianceInfo() {
ClientAuthFilesInfo file = new ClientAuthFilesInfo();
file.setFile_bank_info(complianceFileConfig.getBankStatement());
file.setFile_id_info(complianceFileConfig.getId());
file.setFile_company_info(complianceFileConfig.getCertOfRegistration());
file.setUtility_bill_info(complianceFileConfig.getUtilityBill());
file.setId_type(complianceFileConfig.getIdType());
file.setBeneficiary_id_title(complianceFileConfig.getIdTitle());
file.setOther_id_title_desc(complianceFileConfig.getIdTitleDesc());
return file;
}
public JSONObject insertClientRateInfo(JSONObject defaultRateConfig) {
JSONObject rate = new JSONObject();
rate.put("clean_days", settleConfig.getCleanDays());
rate.put("active_time", settleConfig.getActiveTime());
rate.put("expiry_time", settleConfig.getExpireTime());
rate.put("wechat_rate_value", settleConfig.getWechatRate());
rate.put("alipay_rate_value", settleConfig.getAlipayRate());
rate.put("alipayonline_rate_value", settleConfig.getAlipayOnlineRate());
rate.put("bestpay_rate_value", getDefaultRate(defaultRateConfig, String.valueOf(settleConfig.getCleanDays()),"Bestpay"));
rate.put("jd_rate_value", getDefaultRate(defaultRateConfig, String.valueOf(settleConfig.getCleanDays()),"JDpay"));
rate.put("Rpay_rate_value", getDefaultRate(defaultRateConfig, String.valueOf(settleConfig.getCleanDays()),"Rpay"));
rate.put("cb_bankpay_rate_value", getDefaultRate(defaultRateConfig, String.valueOf(settleConfig.getCleanDays()),"CB_Bankpay"));
return rate;
}
private String getDefaultRate(JSONObject defaultRateConfig, String cleanDays, String rateKey) {
JSONObject config = defaultRateConfig.getJSONObject("t" + cleanDays);
return config.getString(rateKey);
}
}

@ -0,0 +1,88 @@
package au.com.royalpay.payment.manage.gateway.beans;
import au.com.royalpay.payment.core.exceptions.ParamInvalidException;
import au.com.royalpay.payment.tools.exceptions.BadRequestException;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import java.lang.reflect.Field;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Data
public class ClientSettleConfig {
@JSONField(name = "swift_code")
private String swiftCode;
@JSONField(name = "bsb_no")
private String bsbNo;
private String bank;
private String city;
private String address;
private String system;
private String postcode;
private String state;
private String branch;
@JSONField(name = "account_no")
private String accountNo;
@JSONField(name = "account_name")
private String accountName;
@JSONField(name = "clean_days")
private int cleanDays;
@JSONField(name = "wechat_rate")
private String wechatRate;
@JSONField(name = "alipay_rate")
private String alipayRate;
@JSONField(name = "alipay_online_rate")
private String alipayOnlineRate;
@JSONField(name = "transaction_fee")
private String transactionFee;
@JSONField(name = "active_time")
private String activeTime;
@JSONField(name = "expire_time")
private String expireTime;
private static Pattern ACCOUNT_NAME_PATTERN = Pattern.compile("^[a-zA-Z0-9 &]+$");
public void checkParamsInvalid() throws IllegalAccessException {
for (Field field : getClass().getDeclaredFields()) {
field.setAccessible(true);
if (field.get(this) == null) {
throw new ParamInvalidException(field.getName(), "Required Param " + field.getName() +" not found");
}
}
}
public JSONObject insertBankInfo() {
JSONObject bankInfo = new JSONObject();
if (swiftCode.length() > 12) {
throw new BadRequestException("PARAM_ERROR:Switft code must be less than 12 characters");
}
if (bsbNo.length() > 6) {
throw new BadRequestException("PARAM_ERROR:BSB No must be less than 6 characters");
}
if (accountNo.length() > 20) {
throw new BadRequestException("PARAM_ERROR:Account No must be less than 20 characters");
}
if (accountName.length() > 50) {
throw new BadRequestException("PARAM_ERROR:Account Name must be less than 50 characters");
}
Matcher matcher = ACCOUNT_NAME_PATTERN.matcher(accountName);
if (!matcher.matches()) {
throw new BadRequestException("PARAM_ERROR:Invalid Account Name format");
}
bankInfo.put("swift_code", swiftCode);
bankInfo.put("bsb_no", bsbNo);
bankInfo.put("account_no", accountNo);
bankInfo.put("account_name", accountName);
bankInfo.put("bank", bank);
bankInfo.put("city", city);
bankInfo.put("address", address);
bankInfo.put("system", system);
bankInfo.put("postcode", postcode);
bankInfo.put("state", state);
bankInfo.put("branch", branch);
return bankInfo;
}
}

@ -0,0 +1,14 @@
package au.com.royalpay.payment.manage.gateway.core;
import com.alibaba.fastjson.JSONObject;
public interface GatewayMerchantApply {
JSONObject validOrgV200(String shortId);
JSONObject applicationMerchant(JSONObject org, JSONObject registerInfo);
JSONObject getMerchantStatus(JSONObject org, String clientMoniker);
void notifyOrgMerchantStatus(JSONObject client);
}

@ -0,0 +1,255 @@
package au.com.royalpay.payment.manage.gateway.core.impls;
import au.com.royalpay.payment.core.exceptions.InvalidShortIdException;
import au.com.royalpay.payment.core.exceptions.ParamInvalidException;
import au.com.royalpay.payment.manage.gateway.beans.ClientRegisterInfo;
import au.com.royalpay.payment.manage.gateway.core.GatewayMerchantApply;
import au.com.royalpay.payment.manage.management.sysconfig.core.impls.PermissionPartnerManagerImpl;
import au.com.royalpay.payment.manage.mappers.log.GatewayClientApplyNotifyLogMapper;
import au.com.royalpay.payment.manage.mappers.system.*;
import au.com.royalpay.payment.manage.merchants.beans.ClientAuthFilesInfo;
import au.com.royalpay.payment.manage.merchants.core.ClientManager;
import au.com.royalpay.payment.manage.system.core.impl.ClientContractServiceImpl;
import au.com.royalpay.payment.tools.env.SysConfigManager;
import au.com.royalpay.payment.tools.exceptions.BadRequestException;
import au.com.royalpay.payment.tools.exceptions.ServerErrorException;
import au.com.royalpay.payment.tools.threadpool.RoyalThreadPoolExecutor;
import cn.yixblog.platform.http.HttpRequestGenerator;
import cn.yixblog.platform.http.HttpRequestResult;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.util.Date;
import static au.com.royalpay.payment.tools.codec.RSACrypt.loadPrivateKey;
@Service
public class GatewayMerchantApplyImpl implements GatewayMerchantApply {
private Logger logger = LoggerFactory.getLogger(ClientContractServiceImpl.class);
@Resource
private OrgMapper orgMapper;
@Resource
private OrgSignInfoMapper orgSignRsaMapper;
@Resource
private ClientMapper clientMapper;
@Resource
private ManagerMapper managerMapper;
@Resource
private ClientConfigMapper clientConfigMapper;
@Resource
private SysClientLegalPersonMapper sysClientLegalPersonMapper;
@Resource
private PermissionPartnerManagerImpl permissionPartnerManagerImpl;
@Resource
private ClientBDMapper clientBDMapper;
@Resource
private ClientBankAccountMapper clientBankAccountMapper;
@Resource
private ClientManager clientManager;
@Resource
private SysConfigManager sysConfigManager;
@Resource
private RoyalThreadPoolExecutor royalThreadPoolExecutor;
@Resource
private GatewayClientApplyNotifyLogMapper gatewayClientApplyNotifyLogMapper;
@Override
public JSONObject validOrgV200(String shortId) {
JSONObject orgSignJson = orgSignRsaMapper.findOrgSignInfo(shortId);
JSONObject org = orgMapper.findOne(orgSignJson.getInteger("org_id"));
if (org == null) {
throw new InvalidShortIdException();
}
return org;
}
@Override
@Transactional
public JSONObject applicationMerchant(JSONObject org, JSONObject registerInfo) {
ClientRegisterInfo registerBean = JSONObject.toJavaObject(registerInfo, ClientRegisterInfo.class);
registerBean.checkParamsInvalid();
JSONObject result = new JSONObject();
JSONObject manager = managerMapper.findAvailableByLoginId(registerBean.getApplyId());
if (manager == null) {
throw new ParamInvalidException("applyId","applyId is invalid");
}
boolean hasParentBoolean = StringUtils.isNotBlank(registerBean.getParentPartnerCode());
int parentClientId = 0;
if (hasParentBoolean) {
JSONObject parentClient = clientMapper.findClientByMoniker(registerBean.getParentPartnerCode());
if (parentClient == null) {
throw new ParamInvalidException("parentPartnerCode","parentPartnerCode is invalid");
}
parentClientId = parentClient.getIntValue("client_id");
}
try {
JSONObject client = registerBean.insertClientInfo(clientManager.initMerchantCode(), manager.getString("display_name"), hasParentBoolean, parentClientId);
client.put("org_id", org.getString("org_id"));
clientMapper.save(client);
clientConfigMapper.save(registerBean.insertClientConfigInfo(client.getIntValue("client_id"),client.getString("client_moniker")));
sysClientLegalPersonMapper.save(registerBean.insertClientLegalInfo(client.getIntValue("client_id")));
permissionPartnerManagerImpl.permissionClientModuleSave(client.getIntValue("client_id"), client.getString("client_moniker"));
JSONObject clientBd = new JSONObject();
clientBd.put("client_id", client.getIntValue("client_id"));
clientBd.put("bd_id", manager.getString("manager_id"));
clientBd.put("bd_name", manager.getString("display_name"));
clientBd.put("create_time", new Date());
clientBd.put("create_id", manager.getString("manager_id"));
clientBd.put("start_date", new Date());
clientBd.put("proportion", 1);
clientBDMapper.saveBD(clientBd);
clientBankAccountMapper.save(registerBean.insertBankInfo(client.getIntValue("client_id")));
//todo 合规文件待增加source_agree_file
ClientAuthFilesInfo clientAuthFilesInfo = registerBean.insertClientComplianceInfo();
clientManager.uploadAuthFiles(manager, client.getString("client_moniker"), clientAuthFilesInfo);
JSONObject rateConfig = registerBean.insertClientRateInfo(JSONObject.parseObject(sysConfigManager.getSysConfig().getString("sys_rates")));
clientManager.newConfigRate(manager, client.getString("client_moniker"), rateConfig);
clientManager.commitToCompliance(client.getString("client_moniker"), manager);
result.put("parnter_code", client.getString("client_moniker"));
result.put("credential_code", client.getString("credential_code"));
result.put("company_name", client.getString("company_name"));
result.put("short_name", client.getString("short_name"));
} catch (Exception e) {
logger.error("gateway api register fail :{}", e.getMessage());
throw new BadRequestException("PARAM_ERROR:Params length too long");
}
result.put("partner_status", "PROCESSING");
return result;
}
@Override
public JSONObject getMerchantStatus(JSONObject org, String clientMoniker) {
JSONObject client = clientMapper.findClientByMoniker(clientMoniker);
if (client == null) {
throw new InvalidShortIdException();
}
if (client.getIntValue("org_id") != org.getIntValue("org_id")) {
logger.error("This client was not belong to your organization,queryClient:{},orgID:{}", clientMoniker, org.getIntValue("org_id"));
throw new InvalidShortIdException();
}
JSONObject result = new JSONObject();
result.put("partner_code", clientMoniker);
result.put("credential_code", client.getString("credential_code"));
result.put("company_name", client.getString("company_name"));
result.put("short_name", client.getString("short_name"));
result.put("apply_time", DateFormatUtils.format(client.getDate("create_time"), "yyyy-MM-dd HH:mm:ss"));
result.put("apply_id", client.getString("creator"));
int approveResult = client.getIntValue("approve_result");
String clientStatus = "";
switch (approveResult) {
case 1:
clientStatus = "PASS";
break;
case 4:
clientStatus = "PROCESSING";
break;
case 5:
clientStatus = "REFUSED";
break;
default:
clientStatus = "PROCESSING";
break;
}
result.put("partner_status", clientStatus);
if ( approveResult == 1 || approveResult == 5) {
result.put("approve_time", DateFormatUtils.format(client.getDate("approve_time"), "yyyy-MM-dd HH:mm:ss"));
if (approveResult == 5) {
result.put("refuse_description", client.getString("refuse_remark"));
}
}
return result;
}
@Override
public void notifyOrgMerchantStatus(JSONObject client) {
String clientMoniker = client.getString("client_moniker");
if (client.getIntValue("source") != 5) {
return;
}
JSONObject clientConfig = clientConfigMapper.find(client.getIntValue("client_id"));
if (StringUtils.isBlank(clientConfig.getString("notify_url"))) {
return;
}
String notifyUrl = clientConfig.getString("notify_url");
JSONObject org = orgMapper.findOne(client.getInteger("org_id"));
JSONObject merchantStatus = getMerchantStatus(org, clientMoniker);
merchantStatus.put("nonce_str", RandomStringUtils.random(15, true, true));
merchantStatus.put("sign_type", "RSA2");
merchantStatus.put("url", notifyUrl);
JSONObject signInfo = orgSignRsaMapper.findByOrgId(org.getInteger("org_id"));
String signStr = sign(JSONObject.toJSONBytes(merchantStatus, SerializerFeature.MapSortField), signInfo.getString("platform_private_key"));
JSONObject respJson = new JSONObject();
respJson.put("data", merchantStatus);
respJson.put("sign", signStr);
logger.info("ApiV2 Response : {}", JSONObject.toJSONString(respJson, SerializerFeature.MapSortField));
JSONObject log = preInsertServerNotifyLog(client, notifyUrl);
royalThreadPoolExecutor.execute(() -> {
logger.debug("开始推送商户状态[{}]异步通知[{}]:", clientMoniker, notifyUrl);
HttpRequestGenerator gen = new HttpRequestGenerator(notifyUrl, RequestMethod.POST);
gen.setJSONEntity(respJson);
HttpRequestResult result = gen.execute();
if (result.isSuccess()) {
log.put("success", true);
log.put("http_code", result.getStatusCode());
log.put("updatetime", new Date());
gatewayClientApplyNotifyLogMapper.update(log);
logger.debug("商户状态[{}]异步通知[{}]推送完成:[{}]", clientMoniker, notifyUrl, result.getStatusCode());
}else {
Throwable exp = result.getException();
log.put("success", false);
log.put("http_code", result.getStatusCode());
log.put("err_msg", exp == null ? null : exp.getMessage());
log.put("updatetime", new Date());
gatewayClientApplyNotifyLogMapper.update(log);
logger.debug("商户状态[{}]异步通知[{}]推送失败:[{}]-[{}]", clientMoniker, notifyUrl, result.getStatusCode(), exp.getMessage());
}
});
}
private JSONObject preInsertServerNotifyLog(JSONObject client,String notifyUrl) {
int clientId = client.getIntValue("client_id");
JSONObject log = gatewayClientApplyNotifyLogMapper.findHistoryByClientId(clientId);
if (log == null) {
log = new JSONObject();
log.put("org_id", client.getString("org_id"));
log.put("client_id", clientId);
log.put("notify_url", notifyUrl);
log.put("addtime", new Date());
log.put("success", 0);
log.put("http_code", 0);
gatewayClientApplyNotifyLogMapper.saveLog(log);
}
return log;
}
private String sign(byte[] source, String privateKey) {
try {
PrivateKey priKey = loadPrivateKey(new ByteArrayInputStream(privateKey.getBytes(StandardCharsets.UTF_8)));
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(priKey);
signature.update(source);
byte[] signed = signature.sign();
return Base64.encodeBase64URLSafeString(signed);
} catch (NoSuchAlgorithmException | SignatureException | InvalidKeyException e) {
//shall never happen
throw new ServerErrorException(e);
}
}
}

@ -0,0 +1,59 @@
package au.com.royalpay.payment.manage.gateway.web;
import au.com.royalpay.payment.core.exceptions.InvalidShortIdException;
import au.com.royalpay.payment.core.utils.PaymentValidUtils;
import au.com.royalpay.payment.manage.gateway.advice.Gtw2Ctrl;
import au.com.royalpay.payment.manage.gateway.core.GatewayMerchantApply;
import au.com.royalpay.payment.tools.connections.attachment.core.AttachmentClient;
import com.alibaba.fastjson.JSONObject;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
/**
* @author taylor
*/
@RestController
@RequestMapping("/api/v1.0/gateway/partners/{shortId}")
@Gtw2Ctrl
public class GtwPayController {
@Resource
private GatewayMerchantApply gatewayMerchantApply;
@Resource
private AttachmentClient attachmentClient;
@PostMapping(value = "/merchant/application")
public JSONObject applicationMerchant(@RequestBody JSONObject registerInfo, Errors errors,
@PathVariable String shortId) {
JSONObject org = gatewayMerchantApply.validOrgV200(shortId);
PaymentValidUtils.handleValidErrors(errors);
return gatewayMerchantApply.applicationMerchant(org, registerInfo);
}
@GetMapping(value = "/merchant/{partner_code}/status")
public JSONObject getMerchantStatus(@PathVariable String shortId,
@PathVariable String partner_code) {
JSONObject org = gatewayMerchantApply.validOrgV200(shortId);
return gatewayMerchantApply.getMerchantStatus(org, partner_code);
}
@PostMapping("/attachment/files")
public JSONObject uploadFile(@PathVariable String shortId,@RequestParam MultipartFile file) throws Exception {
JSONObject org = gatewayMerchantApply.validOrgV200(shortId);
if (org == null) {
throw new InvalidShortIdException();
}
JSONObject fileInfo = attachmentClient.uploadFile(file, false);
fileInfo.put("file_type", fileInfo.getString("filetype"));
fileInfo.remove("filepath");
fileInfo.remove("length");
fileInfo.remove("fileid");
fileInfo.remove("filetype");
fileInfo.put("file_url", fileInfo.getString("url"));
return fileInfo;
}
}

@ -3,11 +3,9 @@ package au.com.royalpay.payment.manage.logview.core.impl;
import au.com.royalpay.payment.manage.logview.core.OperationLogService; import au.com.royalpay.payment.manage.logview.core.OperationLogService;
import au.com.royalpay.payment.manage.merchants.beans.mongo.ClientConfigLog; import au.com.royalpay.payment.manage.merchants.beans.mongo.ClientConfigLog;
import au.com.royalpay.payment.manage.merchants.core.ClientManager; import au.com.royalpay.payment.manage.merchants.core.ClientManager;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds; import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.Paginator; import com.github.miemiedev.mybatis.paginator.domain.Paginator;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;
@ -16,9 +14,8 @@ import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.List;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.util.List;
/** /**
* @author kira * @author kira
@ -35,16 +32,16 @@ public class OperationLogServiceImpl implements OperationLogService {
public JSONObject query(JSONObject params, PageBounds pageBounds) { public JSONObject query(JSONObject params, PageBounds pageBounds) {
if (StringUtils.isNotEmpty(params.getString("client_moniker"))) { if (StringUtils.isNotEmpty(params.getString("client_moniker"))) {
JSONObject client = clientManager.getClientInfoByMoniker(params.getString("client_moniker")); JSONObject client = clientManager.getClientInfoByMoniker(params.getString("client_moniker"));
if(client!=null) { if (client != null) {
params.put("client_id", client.getIntValue("client_id")); params.put("client_id", client.getIntValue("client_id"));
} }
} }
Query query = new Query(); Query query = new Query();
query.with(new Sort(new Sort.Order(Sort.Direction.DESC,"createTime"))); query.with(Sort.by(Sort.Direction.DESC, "createTime"));
if (params.getIntValue("client_id") != 0) { if (params.getIntValue("client_id") != 0) {
query.addCriteria(Criteria.where("clientId").is(params.getIntValue("client_id"))); query.addCriteria(Criteria.where("clientId").is(params.getIntValue("client_id")));
} }
query.with(new PageRequest(pageBounds.getPage()-1, pageBounds.getLimit())); query.with(PageRequest.of(pageBounds.getPage() - 1, pageBounds.getLimit()));
query.addCriteria(Criteria.where("createTime").gt((params.getDate("begin"))).lt(params.getDate("end"))); query.addCriteria(Criteria.where("createTime").gt((params.getDate("begin"))).lt(params.getDate("end")));
List<ClientConfigLog> clientConfigLogList = mongoTemplate.find(query, ClientConfigLog.class); List<ClientConfigLog> clientConfigLogList = mongoTemplate.find(query, ClientConfigLog.class);
return buildPageListResult(clientConfigLogList, return buildPageListResult(clientConfigLogList,

@ -36,6 +36,7 @@ import au.com.royalpay.payment.tools.utils.PageListUtils;
import au.com.royalpay.payment.tools.utils.TimeZoneUtils; import au.com.royalpay.payment.tools.utils.TimeZoneUtils;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.github.miemiedev.mybatis.paginator.domain.Order; import com.github.miemiedev.mybatis.paginator.domain.Order;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds; import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
@ -102,6 +103,8 @@ public class CleanServiceImpl implements CleanService, ManagerTodoNoticeProvider
@Resource @Resource
private TaskManualSettleMapper taskManualSettleMapper; private TaskManualSettleMapper taskManualSettleMapper;
@Resource @Resource
private PreSettleTaskMapper preSettleTaskMapper;
@Resource
private ValidationLogMapper validationLogMapper; private ValidationLogMapper validationLogMapper;
@Resource @Resource
private ManagerMapper managerMapper; private ManagerMapper managerMapper;
@ -323,6 +326,7 @@ public class CleanServiceImpl implements CleanService, ManagerTodoNoticeProvider
String filename = "Merchant_Settlement_Info_" + dateString + RandomStringUtils.random(8, false, true) + ".csv"; String filename = "Merchant_Settlement_Info_" + dateString + RandomStringUtils.random(8, false, true) + ".csv";
zos.putNextEntry(new ZipEntry(filename)); zos.putNextEntry(new ZipEntry(filename));
List<JSONObject> details = clearingDetailMapper.listReportsOfSettlement(log.getIntValue("clearing_id")); List<JSONObject> details = clearingDetailMapper.listReportsOfSettlement(log.getIntValue("clearing_id"));
details = mergeBatchSettleClients(details);
byte[] csv = generateSettleCSVFile(dt, details); byte[] csv = generateSettleCSVFile(dt, details);
IOUtils.write(csv, zos); IOUtils.write(csv, zos);
} }
@ -367,6 +371,7 @@ public class CleanServiceImpl implements CleanService, ManagerTodoNoticeProvider
logger.info("using newest version test"); logger.info("using newest version test");
for (JSONObject log : logs) { for (JSONObject log : logs) {
List<JSONObject> details = clearingDetailMapper.listReportsOfSettlement(log.getIntValue("clearing_id")); List<JSONObject> details = clearingDetailMapper.listReportsOfSettlement(log.getIntValue("clearing_id"));
details = mergeBatchSettleClients(details);
exportAllBankXlsFiles(zos, details, log.getDate("operate_time")); exportAllBankXlsFiles(zos, details, log.getDate("operate_time"));
} }
zos.flush(); zos.flush();
@ -398,7 +403,9 @@ public class CleanServiceImpl implements CleanService, ManagerTodoNoticeProvider
String filename = "Merchant_Settlement_Info_" + DateFormatUtils.format(dt, "yyyyMMdd") + "_" + fileIndex + ".xlsx"; String filename = "Merchant_Settlement_Info_" + DateFormatUtils.format(dt, "yyyyMMdd") + "_" + fileIndex + ".xlsx";
JSONObject file = new JSONObject(); JSONObject file = new JSONObject();
file.put("name", filename); file.put("name", filename);
file.put("byteArr", generateSettleXlsxFile(dt, clearingDetailMapper.listReportsOfSettlement(log.getIntValue("clearing_id")), bank)); List<JSONObject> details = clearingDetailMapper.listReportsOfSettlement(log.getIntValue("clearing_id"));
details = mergeBatchSettleClients(details);
file.put("byteArr", generateSettleXlsxFile(dt, details, bank));
result.add(file); result.add(file);
fileIndex++; fileIndex++;
} }
@ -407,7 +414,9 @@ public class CleanServiceImpl implements CleanService, ManagerTodoNoticeProvider
String filename = "Merchant_Settlement_Info_" + DateFormatUtils.format(dt, "yyyyMMdd") + ".xlsx"; String filename = "Merchant_Settlement_Info_" + DateFormatUtils.format(dt, "yyyyMMdd") + ".xlsx";
JSONObject file = new JSONObject(); JSONObject file = new JSONObject();
file.put("name", filename); file.put("name", filename);
file.put("byteArr", generateSettleXlsxFile(dt, clearingDetailMapper.listReportsOfSettlement(log.getIntValue("clearing_id")), bank)); List<JSONObject> details = clearingDetailMapper.listReportsOfSettlement(log.getIntValue("clearing_id"));
details = mergeBatchSettleClients(details);
file.put("byteArr", generateSettleXlsxFile(dt, details, bank));
result.add(file); result.add(file);
} }
} }
@ -415,6 +424,67 @@ public class CleanServiceImpl implements CleanService, ManagerTodoNoticeProvider
return result; return result;
} }
private List<JSONObject> mergeBatchSettleClients(List<JSONObject> details) {
Map<String, List<JSONObject>> sameBankDetails = details.stream()
.filter(this::detailEnabledMergeSettle)
.collect(Collectors.groupingBy(this::detailGroupingId));
List<JSONObject> mergedSettleDetails = sameBankDetails.values().stream()
.map(this::mergeDetailGroup).collect(Collectors.toList());
List<Integer> relatedDetailIds = sameBankDetails.values().stream()
.flatMap(group -> group.stream().map(detail -> detail.getInteger("clear_detail_id")))
.collect(Collectors.toList());
details.removeIf(detail -> relatedDetailIds.contains(detail.getInteger("clear_detail_id")));
details.addAll(mergedSettleDetails);
return details;
}
private JSONObject mergeDetailGroup(List<JSONObject> details) {
JSONObject first = details.get(0);
int clientId = details.stream().map(detail -> detail.getInteger("parent_client_id"))
.filter(Objects::nonNull)
.findAny().orElse(first.getIntValue("client_id"));
JSONObject cli = clientManager.getClientInfo(clientId);
String moniker = cli.getString("client_moniker");
String bsb = first.getString("bsb_no");
String accountNo = first.getString("account_no");
String accountName = first.getString("account_name");
String settleBank = first.getString("settle_bank");
BigDecimal clearingAmount = details.stream().map(detail -> detail.getBigDecimal("clearing_amount"))
.reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
JSONObject merged = new JSONObject();
merged.put("client_id", clientId);
merged.put("client_moniker", moniker);
merged.put("bsb_no", bsb);
merged.put("account_no", accountNo);
merged.put("account_name", accountName);
merged.put("settle_bank", settleBank);
merged.put("clearing_amount", clearingAmount);
return merged;
}
private String detailGroupingId(JSONObject detail) {
String cliPId = detail.getString("parent_client_id");
if (cliPId == null) {
cliPId = detail.getString("client_id");
}
String bsb = detail.getString("bsb_no");
String accountNo = detail.getString("account_no");
return String.join("_", cliPId, bsb, accountNo);
}
private boolean detailEnabledMergeSettle(JSONObject detail) {
String extParams = detail.getString("ext_params");
if (extParams != null) {
try {
JSONObject ext = JSON.parseObject(extParams);
return ext.getBooleanValue("merge_settle");
} catch (JSONException e) {
return false;
}
}
return false;
}
@Override @Override
public List<ABAFile> getAba(Date dt, String bank) { public List<ABAFile> getAba(Date dt, String bank) {
List<JSONObject> logs = clearingLogMapper.findByDate(dt); List<JSONObject> logs = clearingLogMapper.findByDate(dt);
@ -425,6 +495,7 @@ public class CleanServiceImpl implements CleanService, ManagerTodoNoticeProvider
List<ABAFile> files = new ArrayList<>(); List<ABAFile> files = new ArrayList<>();
for (JSONObject log : logs) { for (JSONObject log : logs) {
List<JSONObject> details = clearingDetailMapper.listReportsOfSettlement(log.getIntValue("clearing_id")); List<JSONObject> details = clearingDetailMapper.listReportsOfSettlement(log.getIntValue("clearing_id"));
details = mergeBatchSettleClients(details);
files.addAll(generateSettleAbaFiles(dt, details, log.getDate("operate_time"))); files.addAll(generateSettleAbaFiles(dt, details, log.getDate("operate_time")));
} }
return files.stream().filter(file -> bank.equals(file.bank())).collect(Collectors.toList()); return files.stream().filter(file -> bank.equals(file.bank())).collect(Collectors.toList());
@ -445,7 +516,7 @@ public class CleanServiceImpl implements CleanService, ManagerTodoNoticeProvider
row.createCell(0, Cell.CELL_TYPE_STRING).setCellValue(settle.getString("bsb_no")); row.createCell(0, Cell.CELL_TYPE_STRING).setCellValue(settle.getString("bsb_no"));
row.createCell(1, Cell.CELL_TYPE_STRING).setCellValue(settle.getString("account_no")); row.createCell(1, Cell.CELL_TYPE_STRING).setCellValue(settle.getString("account_no"));
row.createCell(2, Cell.CELL_TYPE_STRING).setCellValue(settle.getString("account_name")); row.createCell(2, Cell.CELL_TYPE_STRING).setCellValue(settle.getString("account_name"));
row.createCell(3, Cell.CELL_TYPE_STRING).setCellValue(settle.getBigDecimal("clearing_amount").setScale(2, BigDecimal.ROUND_DOWN).toPlainString()); row.createCell(3, Cell.CELL_TYPE_STRING).setCellValue(settle.getBigDecimal("clearing_amount").setScale(2, RoundingMode.DOWN).toPlainString());
} }
ByteArrayOutputStream bos = new ByteArrayOutputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream();
wb.write(bos); wb.write(bos);
@ -464,6 +535,7 @@ public class CleanServiceImpl implements CleanService, ManagerTodoNoticeProvider
for (JSONObject log : logs) { for (JSONObject log : logs) {
List<JSONObject> details = clearingDetailMapper.listReportsOfSettlement(log.getIntValue("clearing_id")); List<JSONObject> details = clearingDetailMapper.listReportsOfSettlement(log.getIntValue("clearing_id"));
details = mergeBatchSettleClients(details);
files.addAll(generateSettleAbaFiles(dt, details, log.getDate("operate_time"))); files.addAll(generateSettleAbaFiles(dt, details, log.getDate("operate_time")));
} }
OutputStream ous = resp.getOutputStream(); OutputStream ous = resp.getOutputStream();
@ -500,6 +572,7 @@ public class CleanServiceImpl implements CleanService, ManagerTodoNoticeProvider
throw new NotFoundException("Clearing batch " + batchId + " not found"); throw new NotFoundException("Clearing batch " + batchId + " not found");
} }
List<JSONObject> details = clearingDetailMapper.listReportsOfSettlement(clearingId); List<JSONObject> details = clearingDetailMapper.listReportsOfSettlement(clearingId);
details = mergeBatchSettleClients(details);
Date settleDate = clearing.getDate("settle_date"); Date settleDate = clearing.getDate("settle_date");
Date opTime = clearing.getDate("operate_time"); Date opTime = clearing.getDate("operate_time");
String zipName = "Merchant_Settlement_Info_" + DateFormatUtils.format(opTime, "yyyyMMddHHmmss") + "_all.zip"; String zipName = "Merchant_Settlement_Info_" + DateFormatUtils.format(opTime, "yyyyMMddHHmmss") + "_all.zip";
@ -732,7 +805,7 @@ public class CleanServiceImpl implements CleanService, ManagerTodoNoticeProvider
new PageBounds(Order.formString("order_id.asc"))); new PageBounds(Order.formString("order_id.asc")));
for (JSONObject transaction : transactions) { for (JSONObject transaction : transactions) {
transaction.put("rate_value",StringUtils.defaultString(clientIncrementalMapper.findByChannelAndClientId(transaction.getIntValue("client_id"),transaction.getString("source")) ,"0")); transaction.put("rate_value", StringUtils.defaultString(clientIncrementalMapper.findByChannelAndClientId(transaction.getIntValue("client_id"), transaction.getString("source")), "0"));
} }
String timezone_client = client.getString("timezone"); String timezone_client = client.getString("timezone");
if (timezone_client != null) { if (timezone_client != null) {
@ -838,7 +911,7 @@ public class CleanServiceImpl implements CleanService, ManagerTodoNoticeProvider
int rowNum = 0; int rowNum = 0;
Row row = sheet.createRow(rowNum); Row row = sheet.createRow(rowNum);
String[] title = {"order Id", "Client Order Id", "Transaction Time", "Channel", "Gateway", "Exchange Rate", "Transaction Type", "Currency", String[] title = {"order Id", "Client Order Id", "Transaction Time", "Channel", "Gateway", "Exchange Rate", "Transaction Type", "Currency",
"Input Amount", "Total Amount", "Clearing Amount(AUD)", "Sruchange Rate", "Surcharge(AUD)", "GST(AUD)", "Settle Amount(AUD)", "Remark", "Dev No","Dev Remark"}; "Input Amount", "Total Amount", "Clearing Amount(AUD)", "Sruchange Rate", "Surcharge(AUD)", "GST(AUD)", "Settle Amount(AUD)", "Remark", "Dev No", "Dev Remark"};
String[] analysis = {"Total Credit(AUD)", "Total Debit(AUD)", "Gross Amount(AUD)", "Total GST(AUD)", "Total Charge(AUD)", "Net Amount(AUD)"}; String[] analysis = {"Total Credit(AUD)", "Total Debit(AUD)", "Gross Amount(AUD)", "Total GST(AUD)", "Total Charge(AUD)", "Net Amount(AUD)"};
for (int i = 0; i < title.length; i++) { for (int i = 0; i < title.length; i++) {
row.createCell(i, Cell.CELL_TYPE_STRING).setCellValue(title[i]); row.createCell(i, Cell.CELL_TYPE_STRING).setCellValue(title[i]);
@ -864,26 +937,26 @@ public class CleanServiceImpl implements CleanService, ManagerTodoNoticeProvider
row.createCell(5, Cell.CELL_TYPE_STRING).setCellValue(settle.getBigDecimal("exchange_rate").setScale(5, BigDecimal.ROUND_DOWN).toPlainString()); row.createCell(5, Cell.CELL_TYPE_STRING).setCellValue(settle.getBigDecimal("exchange_rate").setScale(5, BigDecimal.ROUND_DOWN).toPlainString());
cell = row.createCell(6, Cell.CELL_TYPE_STRING); cell = row.createCell(6, Cell.CELL_TYPE_STRING);
cell.setCellValue(settle.getString("transaction_type")); cell.setCellValue(settle.getString("transaction_type"));
cell.setCellStyle(!"Credit".equals(settle.getString("transaction_type"))?analysisStyle2:null); cell.setCellStyle(!"Credit".equals(settle.getString("transaction_type")) ? analysisStyle2 : null);
row.createCell(7, Cell.CELL_TYPE_STRING).setCellValue(settle.getString("transaction_currency")); row.createCell(7, Cell.CELL_TYPE_STRING).setCellValue(settle.getString("transaction_currency"));
cell = row.createCell(8, Cell.CELL_TYPE_STRING); cell = row.createCell(8, Cell.CELL_TYPE_STRING);
cell.setCellValue(settle.getBigDecimal("display_amount") == null ? "" cell.setCellValue(settle.getBigDecimal("display_amount") == null ? ""
: "Credit".equals(settle.getString("transaction_type"))? : "Credit".equals(settle.getString("transaction_type")) ?
settle.getBigDecimal("display_amount").setScale(2, BigDecimal.ROUND_DOWN).toPlainString(): settle.getBigDecimal("display_amount").setScale(2, BigDecimal.ROUND_DOWN).toPlainString() :
"-"+settle.getBigDecimal("display_amount").setScale(2, BigDecimal.ROUND_DOWN).toPlainString()); "-" + settle.getBigDecimal("display_amount").setScale(2, BigDecimal.ROUND_DOWN).toPlainString());
cell.setCellStyle(!"Credit".equals(settle.getString("transaction_type"))?analysisStyle2:null); cell.setCellStyle(!"Credit".equals(settle.getString("transaction_type")) ? analysisStyle2 : null);
cell = row.createCell(9, Cell.CELL_TYPE_STRING); cell = row.createCell(9, Cell.CELL_TYPE_STRING);
cell.setCellValue(settle.getBigDecimal("transaction_amount") == null ? "" cell.setCellValue(settle.getBigDecimal("transaction_amount") == null ? ""
: "Credit".equals(settle.getString("transaction_type"))? : "Credit".equals(settle.getString("transaction_type")) ?
settle.getBigDecimal("transaction_amount").setScale(2, BigDecimal.ROUND_DOWN).toPlainString(): settle.getBigDecimal("transaction_amount").setScale(2, BigDecimal.ROUND_DOWN).toPlainString() :
"-"+settle.getBigDecimal("transaction_amount").setScale(2, BigDecimal.ROUND_DOWN).toPlainString()); "-" + settle.getBigDecimal("transaction_amount").setScale(2, BigDecimal.ROUND_DOWN).toPlainString());
cell.setCellStyle(!"Credit".equals(settle.getString("transaction_type"))?analysisStyle2:null); cell.setCellStyle(!"Credit".equals(settle.getString("transaction_type")) ? analysisStyle2 : null);
cell = row.createCell(10, Cell.CELL_TYPE_STRING); cell = row.createCell(10, Cell.CELL_TYPE_STRING);
cell.setCellValue(settle.getBigDecimal("clearing_amount") == null ? "" cell.setCellValue(settle.getBigDecimal("clearing_amount") == null ? ""
: "Credit".equals(settle.getString("transaction_type"))? : "Credit".equals(settle.getString("transaction_type")) ?
settle.getBigDecimal("clearing_amount").setScale(2, BigDecimal.ROUND_DOWN).toPlainString(): settle.getBigDecimal("clearing_amount").setScale(2, BigDecimal.ROUND_DOWN).toPlainString() :
"-"+settle.getBigDecimal("clearing_amount").setScale(2, BigDecimal.ROUND_DOWN).toPlainString()); "-" + settle.getBigDecimal("clearing_amount").setScale(2, BigDecimal.ROUND_DOWN).toPlainString());
cell.setCellStyle(!"Credit".equals(settle.getString("transaction_type"))?analysisStyle2:null); cell.setCellStyle(!"Credit".equals(settle.getString("transaction_type")) ? analysisStyle2 : null);
row.createCell(11, Cell.CELL_TYPE_STRING).setCellValue(channels.getString(settle.getString("channel")) == null ? "" row.createCell(11, Cell.CELL_TYPE_STRING).setCellValue(channels.getString(settle.getString("channel")) == null ? ""
: channels.getJSONObject(settle.getString("channel")).getBigDecimal("rate").toPlainString() + "%"); : channels.getJSONObject(settle.getString("channel")).getBigDecimal("rate").toPlainString() + "%");
//手续费 + gst //手续费 + gst
@ -1212,6 +1285,7 @@ public class CleanServiceImpl implements CleanService, ManagerTodoNoticeProvider
String defaultBank = config.getRemainsTo(); String defaultBank = config.getRemainsTo();
clearingDetailMapper.updateAllBanks(defaultBank, clearingId); clearingDetailMapper.updateAllBanks(defaultBank, clearingId);
List<JSONObject> details = clearingDetailMapper.listReportsOfSettlement(clearingId); List<JSONObject> details = clearingDetailMapper.listReportsOfSettlement(clearingId);
details = mergeBatchSettleClients(details);
details.sort((log1, log2) -> { details.sort((log1, log2) -> {
if (StringUtils.equals(defaultBank, log1.getString("account_bank")) == if (StringUtils.equals(defaultBank, log1.getString("account_bank")) ==
StringUtils.equals(defaultBank, log2.getString("account_bank"))) { StringUtils.equals(defaultBank, log2.getString("account_bank"))) {
@ -1283,6 +1357,7 @@ public class CleanServiceImpl implements CleanService, ManagerTodoNoticeProvider
} }
transactionMapper.deleteSettlementTransaction(clearingId); transactionMapper.deleteSettlementTransaction(clearingId);
transactionMapper.removeSettleRemark(clearingId); transactionMapper.removeSettleRemark(clearingId);
preSettleTaskMapper.resetClearStatus(clearingId);
clearingDetailAnalysisMapper.clearAnalysis(clearingId); clearingDetailAnalysisMapper.clearAnalysis(clearingId);
taskManualSettleMapper.rollbackExecutedTask(clearingId); taskManualSettleMapper.rollbackExecutedTask(clearingId);
clearingDetailMapper.deleteSettleLogs(clearingId); clearingDetailMapper.deleteSettleLogs(clearingId);

@ -0,0 +1,30 @@
package au.com.royalpay.payment.manage.mappers.log;
import cn.yixblog.support.mybatis.autosql.annotations.AdvanceSelect;
import cn.yixblog.support.mybatis.autosql.annotations.AutoMapper;
import cn.yixblog.support.mybatis.autosql.annotations.AutoSql;
import cn.yixblog.support.mybatis.autosql.annotations.SqlType;
import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* Created by davep on 2016-07-22.
*/
@AutoMapper(tablename = "gateway_clientApply_notify_log", pkName = "id")
public interface GatewayClientApplyNotifyLogMapper {
@AutoSql(type = SqlType.INSERT)
void saveLog(JSONObject log);
@AutoSql(type = SqlType.UPDATE)
void update(JSONObject notice);
@AutoSql(type = SqlType.SELECT)
@AdvanceSelect(addonWhereClause = "success=0 and addtime(`addtime`,'24:00:00')>now()")
List<JSONObject> listErrorLogsIn24Hour();
@AutoSql(type = SqlType.SELECT)
JSONObject findHistoryByClientId(@Param("client_id") int clientId);
}

@ -0,0 +1,13 @@
package au.com.royalpay.payment.manage.mappers.log;
import cn.yixblog.support.mybatis.autosql.annotations.AutoMapper;
import org.apache.ibatis.annotations.Param;
/**
* Create by davep at 2020-02-04 11:40
*/
@AutoMapper(tablename = "log_presettle_task",pkName = "task_id")
public interface PreSettleTaskMapper {
void resetClearStatus(@Param("clearing_id") int clearingId);
}

@ -78,6 +78,10 @@ public interface ClientMapper {
@AdvanceSelect(addonWhereClause = "is_valid=1") @AdvanceSelect(addonWhereClause = "is_valid=1")
List<JSONObject> listChildClients(@Param("parent_client_id") int parentClientId); List<JSONObject> listChildClients(@Param("parent_client_id") int parentClientId);
@AutoSql(type = SqlType.SELECT)
@AdvanceSelect(addonWhereClause = "is_valid=1")
List<JSONObject> listChildClients(@Param("parent_client_id") int parentClientId, PageBounds pagination);
@AutoSql(type = SqlType.UPDATE) @AutoSql(type = SqlType.UPDATE)
void updateCleanDays(@Param("client_id") int clientId, @Param("clean_days") int cleanDays); void updateCleanDays(@Param("client_id") int clientId, @Param("clean_days") int cleanDays);

@ -72,4 +72,6 @@ public interface ManagerMapper {
List<String> listDevAndBdOpenId(); List<String> listDevAndBdOpenId();
List<JSONObject> findBdById(@Param("org_id")String org_id); List<JSONObject> findBdById(@Param("org_id")String org_id);
} }

@ -0,0 +1,27 @@
package au.com.royalpay.payment.manage.mappers.system;
import cn.yixblog.support.mybatis.autosql.annotations.AutoMapper;
import cn.yixblog.support.mybatis.autosql.annotations.AutoSql;
import cn.yixblog.support.mybatis.autosql.annotations.SqlType;
import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.executor.keygen.Jdbc3KeyGenerator;
@AutoMapper(tablename = "org_sign_info", pkName = "org_id", keyGenerator = Jdbc3KeyGenerator.class)
public interface OrgSignInfoMapper {
@AutoSql(type = SqlType.SELECT)
JSONObject findByOrgId(@Param("org_id") int orgId);
@AutoSql(type = SqlType.SELECT)
JSONObject findOrgSignInfo(@Param("gateway_short_id") String orgId);
int getPartnercode(@Param("codes") String codes);
@AutoSql(type = SqlType.UPDATE)
void update(JSONObject signInfo);
@AutoSql(type = SqlType.INSERT)
void insert(JSONObject signInfo);
}

@ -25,13 +25,14 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable; import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.io.IOException; import java.io.IOException;
import java.net.URISyntaxException; import java.util.ArrayList;
import java.util.*; import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** /**
@ -166,11 +167,7 @@ public class MerchantIdManageServiceImpl implements MerchantIdManageService {
param.put("sub_merchant_id",sub_merchant_id); param.put("sub_merchant_id",sub_merchant_id);
String createUrl= PlatformEnvironment.getEnv().concatUrl("api/v1.0/gateway/partners/" + partner_code + "/orders/" + orderId +"/manager/test"+"?" + queryParams(partner_code)); String createUrl= PlatformEnvironment.getEnv().concatUrl("api/v1.0/gateway/partners/" + partner_code + "/orders/" + orderId +"/manager/test"+"?" + queryParams(partner_code));
HttpRequestResult result = null; HttpRequestResult result = null;
try {
result = new HttpRequestGenerator(createUrl, RequestMethod.PUT).setJSONEntity(param).execute(); result = new HttpRequestGenerator(createUrl, RequestMethod.PUT).setJSONEntity(param).execute();
} catch (URISyntaxException e) {
e.printStackTrace();
}
if (result.isSuccess()) { if (result.isSuccess()) {
try { try {
return result.getResponseContentJSONObj(); return result.getResponseContentJSONObj();

@ -26,6 +26,7 @@ import au.com.royalpay.payment.manage.application.core.SimpleClientApplyService;
import au.com.royalpay.payment.manage.complianceAudit.core.ClientComplianceApply; import au.com.royalpay.payment.manage.complianceAudit.core.ClientComplianceApply;
import au.com.royalpay.payment.manage.dev.bean.TestMerchantAccountInfo; import au.com.royalpay.payment.manage.dev.bean.TestMerchantAccountInfo;
import au.com.royalpay.payment.manage.device.core.DeviceManager; import au.com.royalpay.payment.manage.device.core.DeviceManager;
import au.com.royalpay.payment.manage.gateway.core.GatewayMerchantApply;
import au.com.royalpay.payment.manage.kyc.enums.FilesAuthEnum; import au.com.royalpay.payment.manage.kyc.enums.FilesAuthEnum;
import au.com.royalpay.payment.manage.management.sysconfig.core.impls.PermissionPartnerManagerImpl; import au.com.royalpay.payment.manage.management.sysconfig.core.impls.PermissionPartnerManagerImpl;
import au.com.royalpay.payment.manage.mappers.financial.FinancialBDConfigMapper; import au.com.royalpay.payment.manage.mappers.financial.FinancialBDConfigMapper;
@ -126,7 +127,6 @@ import java.awt.image.BufferedImage;
import java.io.*; import java.io.*;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.math.RoundingMode; import java.math.RoundingMode;
import java.net.URISyntaxException;
import java.net.URL; import java.net.URL;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.security.InvalidParameterException; import java.security.InvalidParameterException;
@ -305,6 +305,8 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid
private ClientComplianceCompanyMapper clientComplianceCompanyMapper; private ClientComplianceCompanyMapper clientComplianceCompanyMapper;
@Resource @Resource
private IndustryLookupMapper industryLookupMapper; private IndustryLookupMapper industryLookupMapper;
@Resource
private GatewayMerchantApply gatewayMerchantApply;
@Resource @Resource
@ -830,7 +832,6 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid
@Transactional @Transactional
public void updateClientRegisterInfo(JSONObject manager, String clientMoniker, ClientRegisterInfo info) { public void updateClientRegisterInfo(JSONObject manager, String clientMoniker, ClientRegisterInfo info) {
JSONObject client = getClientInfoByMoniker(clientMoniker); JSONObject client = getClientInfoByMoniker(clientMoniker);
Assert.notNull(client);
checkOrgPermission(manager, client); checkOrgPermission(manager, client);
JSONObject updateInfo = info.updateObject(); JSONObject updateInfo = info.updateObject();
@ -892,7 +893,6 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid
@Transactional @Transactional
public void updateClientRegisterInfoV2(JSONObject manager, String clientMoniker, JSONObject info) { public void updateClientRegisterInfoV2(JSONObject manager, String clientMoniker, JSONObject info) {
JSONObject client = getClientInfoByMoniker(clientMoniker); JSONObject client = getClientInfoByMoniker(clientMoniker);
Assert.notNull(client);
checkOrgPermission(manager, client); checkOrgPermission(manager, client);
int clientId = client.getIntValue("client_id"); int clientId = client.getIntValue("client_id");
@ -1125,7 +1125,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid
if (pass == 1) { if (pass == 1) {
createKycAuthStatus(manager,client); createKycAuthStatus(manager,client);
clientModifySupport.processClientConfigModify(new SwitchPermissionModify(manager, clientMoniker, "skip_clearing", false)); clientModifySupport.processClientConfigModify(new SwitchPermissionModify(manager, clientMoniker, "skip_clearing", false));
if (client.getIntValue("source") == 4) { if (client.getIntValue("source") == 4 || client.getIntValue("source") == 5) {
List<JSONObject> accounts = clientAccountMapper.listAdminAccounts(client.getIntValue("client_id")); List<JSONObject> accounts = clientAccountMapper.listAdminAccounts(client.getIntValue("client_id"));
JSONObject account = accounts.get(0); JSONObject account = accounts.get(0);
sendInitEmail(client, account.getString("username"), "*****"); sendInitEmail(client, account.getString("username"), "*****");
@ -1133,6 +1133,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid
saveClientAuditProcess(client.getIntValue("client_id"), open_status, 5, "合规通过", manager); saveClientAuditProcess(client.getIntValue("client_id"), open_status, 5, "合规通过", manager);
clientModifySupport.processClientConfigModify(new SwitchPermissionModify(manager, clientMoniker, "skip_clearing", false)); clientModifySupport.processClientConfigModify(new SwitchPermissionModify(manager, clientMoniker, "skip_clearing", false));
clientModifySupport.processClientConfigModify(new SwitchPermissionModify(manager, clientMoniker, "common_sub_merchant_id", false)); clientModifySupport.processClientConfigModify(new SwitchPermissionModify(manager, clientMoniker, "common_sub_merchant_id", false));
gatewayMerchantApply.notifyOrgMerchantStatus(client);
} else if (checkGreenChannel && client.getIntValue("open_status") == 5) { } else if (checkGreenChannel && client.getIntValue("open_status") == 5) {
// 绿色通道通过后不发邮件 // 绿色通道通过后不发邮件
logger.info("PASS 绿色通道:" + clientMoniker); logger.info("PASS 绿色通道:" + clientMoniker);
@ -1656,7 +1657,6 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid
private JSONObject checkAndFindAccount(JSONObject manager, String clientMoniker, String accountId) { private JSONObject checkAndFindAccount(JSONObject manager, String clientMoniker, String accountId) {
JSONObject account = clientAccountMapper.findById(accountId); JSONObject account = clientAccountMapper.findById(accountId);
Assert.notNull(account);
if (clientMoniker != null) { if (clientMoniker != null) {
JSONObject client = getClientInfoByMoniker(clientMoniker); JSONObject client = getClientInfoByMoniker(clientMoniker);
Assert.notNull(client); Assert.notNull(client);
@ -2072,8 +2072,9 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid
throw new InvalidShortIdException(); throw new InvalidShortIdException();
} }
checkOrgPermission(manager, client); checkOrgPermission(manager, client);
JSONObject listSubClients = new JSONObject();
List<JSONObject> listChildClients = clientMapper.listChildClients(client.getIntValue("client_id")); List<JSONObject> listChildClients = clientMapper.listChildClients(client.getIntValue("client_id"));
JSONObject mchConfig = merchantInfoProvider.getMchExtParams(client.getIntValue("client_id"));
if (!mchConfig.getBooleanValue("disable_level3_mch")) {
for (JSONObject partner : listChildClients) { for (JSONObject partner : listChildClients) {
List<JSONObject> clients = clientMapper.listChildClients(partner.getIntValue("client_id")); List<JSONObject> clients = clientMapper.listChildClients(partner.getIntValue("client_id"));
if (clients.size() > 0) { if (clients.size() > 0) {
@ -2083,6 +2084,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid
}); });
} }
} }
}
return listChildClients; return listChildClients;
} }
@ -2546,7 +2548,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid
ous.flush(); ous.flush();
IOUtils.closeQuietly(ous); IOUtils.closeQuietly(ous);
} }
} catch (URISyntaxException | IOException e) { } catch (IOException e) {
throw new ServerErrorException("Error", e); throw new ServerErrorException("Error", e);
} }
} }
@ -2565,7 +2567,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid
ous.flush(); ous.flush();
IOUtils.closeQuietly(ous); IOUtils.closeQuietly(ous);
} }
} catch (URISyntaxException | IOException e) { } catch (IOException e) {
throw new ServerErrorException("Error", e); throw new ServerErrorException("Error", e);
} }
} }
@ -2602,7 +2604,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid
ImageUtils.drawImage(g, logoImg, 588, 1916, 2363, 960); ImageUtils.drawImage(g, logoImg, 588, 1916, 2363, 960);
} }
} catch (URISyntaxException | IOException ignored) { } catch (IOException ignored) {
} }
} }
} }
@ -2795,7 +2797,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid
if (result.isSuccess()) { if (result.isSuccess()) {
res = result.getResponseContentJSONObj(); res = result.getResponseContentJSONObj();
} }
} catch (URISyntaxException | IOException e) { } catch (IOException e) {
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
} }
return res; return res;
@ -3400,14 +3402,12 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid
@Override @Override
public void disableClient(String clientMoniker, JSONObject manager) { public void disableClient(String clientMoniker, JSONObject manager) {
JSONObject client = clientDetail(manager, clientMoniker); JSONObject client = clientDetail(manager, clientMoniker);
Assert.notEmpty(client);
clientModifySupport.processClientModify(new DisableModify(manager, clientMoniker, false)); clientModifySupport.processClientModify(new DisableModify(manager, clientMoniker, false));
} }
@Override @Override
public void revertClient(String clientMoniker, JSONObject manager) { public void revertClient(String clientMoniker, JSONObject manager) {
JSONObject client = clientDetail(manager, clientMoniker); JSONObject client = clientDetail(manager, clientMoniker);
Assert.notEmpty(client);
clientModifySupport.processClientModify(new DisableModify(manager, clientMoniker, true)); clientModifySupport.processClientModify(new DisableModify(manager, clientMoniker, true));
} }
@ -4694,6 +4694,9 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid
} }
} }
} }
if (client.getIntValue("source") == 5) {
gatewayMerchantApply.notifyOrgMerchantStatus(client);
}
} catch (Exception e) { } catch (Exception e) {
logger.error("RefusePartnerError=======:" + clientMoniker + "," + e.getMessage()); logger.error("RefusePartnerError=======:" + clientMoniker + "," + e.getMessage());
} }
@ -4716,7 +4719,6 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid
@Override @Override
public void updateAppClient(JSONObject account, int client_id, AppClientBean appClientBean) { public void updateAppClient(JSONObject account, int client_id, AppClientBean appClientBean) {
JSONObject client = getClientInfo(client_id); JSONObject client = getClientInfo(client_id);
Assert.notNull(client);
JSONObject updateObj = appClientBean.updateObject(); JSONObject updateObj = appClientBean.updateObject();
if (updateObj.size() > 0) { if (updateObj.size() > 0) {
updateObj.put("client_id", client_id); updateObj.put("client_id", client_id);
@ -5838,7 +5840,6 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid
@Override @Override
public void sendVerifyEmail(JSONObject client, String accountId) { public void sendVerifyEmail(JSONObject client, String accountId) {
JSONObject clientAccount = clientAccountMapper.findById(accountId); JSONObject clientAccount = clientAccountMapper.findById(accountId);
Assert.notNull(clientAccount);
simpleClientApplyService.sendVerifyEmail(client.getString("contact_email"), client.getIntValue("client_id"), clientAccount.getString("username")); simpleClientApplyService.sendVerifyEmail(client.getString("contact_email"), client.getIntValue("client_id"), clientAccount.getString("username"));
} }

@ -411,7 +411,6 @@ public class PartnerViewController {
clientManager.refreshPlatformPublicKeyConfig(account); clientManager.refreshPlatformPublicKeyConfig(account);
} }
@PartnerMapping(value = "/payment_page_version", method = RequestMethod.PUT) @PartnerMapping(value = "/payment_page_version", method = RequestMethod.PUT)
@ResponseBody @ResponseBody
public void changePaymentPage(@RequestBody JSONObject pass, @ModelAttribute(CommonConsts.PARTNER_STATUS) JSONObject account) { public void changePaymentPage(@RequestBody JSONObject pass, @ModelAttribute(CommonConsts.PARTNER_STATUS) JSONObject account) {

@ -11,13 +11,13 @@ import au.com.royalpay.payment.tools.exceptions.NotFoundException;
import au.com.royalpay.payment.tools.exceptions.ServerErrorException; import au.com.royalpay.payment.tools.exceptions.ServerErrorException;
import au.com.royalpay.payment.tools.utils.PageListUtils; import au.com.royalpay.payment.tools.utils.PageListUtils;
import au.com.royalpay.payment.tools.utils.id.IdUtil; import au.com.royalpay.payment.tools.utils.id.IdUtil;
import cn.yixblog.platform.http.HttpRequestGenerator;
import cn.yixblog.platform.http.HttpRequestResult;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.github.miemiedev.mybatis.paginator.domain.Order; import com.github.miemiedev.mybatis.paginator.domain.Order;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds; import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
@ -33,6 +33,7 @@ import org.springframework.stereotype.Service;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import javax.annotation.Resource;
import java.io.IOException; import java.io.IOException;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
@ -40,11 +41,6 @@ import java.security.Key;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import javax.annotation.Resource;
import cn.yixblog.platform.http.HttpRequestGenerator;
import cn.yixblog.platform.http.HttpRequestResult;
/** /**
* Created by yishuqian on 18/01/2017. * Created by yishuqian on 18/01/2017.
*/ */
@ -183,7 +179,6 @@ public class MailServiceImp implements MailService {
noticeBean.setPassword(mailPwd); noticeBean.setPassword(mailPwd);
String postUrl = mailHost + "/mail/single?" + generateMailSignParam(); String postUrl = mailHost + "/mail/single?" + generateMailSignParam();
HttpRequestResult result = null; HttpRequestResult result = null;
try {
logger.info("===sendEmail===noticeBean:" + JSON.toJSON(noticeBean)); logger.info("===sendEmail===noticeBean:" + JSON.toJSON(noticeBean));
result = new HttpRequestGenerator(postUrl, RequestMethod.POST).setJSONEntity(noticeBean).setTimeout(60_000).execute(); result = new HttpRequestGenerator(postUrl, RequestMethod.POST).setJSONEntity(noticeBean).setTimeout(60_000).execute();
if (result.isSuccess()) { if (result.isSuccess()) {
@ -193,9 +188,6 @@ public class MailServiceImp implements MailService {
} else { } else {
throw new ServerErrorException("Error Connection"); throw new ServerErrorException("Error Connection");
} }
} catch (URISyntaxException e) {
throw new ServerErrorException("Error Connection");
}
} }
@Override @Override
@ -219,7 +211,6 @@ public class MailServiceImp implements MailService {
noticeBean.setPassword(mailPwd); noticeBean.setPassword(mailPwd);
String postUrl = mailHost + "/mail/single?" + generateMailSignParam(); String postUrl = mailHost + "/mail/single?" + generateMailSignParam();
HttpRequestResult result = null; HttpRequestResult result = null;
try {
logger.info("===sendEmail===noticeBean:" + JSON.toJSON(noticeBean)); logger.info("===sendEmail===noticeBean:" + JSON.toJSON(noticeBean));
result = new HttpRequestGenerator(postUrl, RequestMethod.POST).setJSONEntity(noticeBean).setTimeout(60_000).execute(); result = new HttpRequestGenerator(postUrl, RequestMethod.POST).setJSONEntity(noticeBean).setTimeout(60_000).execute();
if (result.isSuccess()) { if (result.isSuccess()) {
@ -229,9 +220,6 @@ public class MailServiceImp implements MailService {
} else { } else {
throw new ServerErrorException("Error Connection"); throw new ServerErrorException("Error Connection");
} }
} catch (URISyntaxException e) {
throw new ServerErrorException("Error Connection");
}
} }
@Override @Override
@ -249,7 +237,7 @@ public class MailServiceImp implements MailService {
} else { } else {
throw new ServerErrorException("Mail Service failed; status code=" + result.getStatusCode()); throw new ServerErrorException("Mail Service failed; status code=" + result.getStatusCode());
} }
} catch (URISyntaxException | IOException e) { } catch (IOException e) {
throw new ServerErrorException("Mail Service failed", e); throw new ServerErrorException("Mail Service failed", e);
} }
@ -305,7 +293,6 @@ public class MailServiceImp implements MailService {
noticeBean.setAttachFiles(attachFiles); noticeBean.setAttachFiles(attachFiles);
String postUrl = mailHost + "/mail/single?" + generateMailSignParam(); String postUrl = mailHost + "/mail/single?" + generateMailSignParam();
HttpRequestResult result = null; HttpRequestResult result = null;
try {
logger.info("===sendEmail===noticeBean:" + JSON.toJSON(noticeBean)); logger.info("===sendEmail===noticeBean:" + JSON.toJSON(noticeBean));
result = new HttpRequestGenerator(postUrl, RequestMethod.POST).setJSONEntity(noticeBean).setTimeout(60_000).execute(); result = new HttpRequestGenerator(postUrl, RequestMethod.POST).setJSONEntity(noticeBean).setTimeout(60_000).execute();
if (result.isSuccess()) { if (result.isSuccess()) {
@ -315,9 +302,6 @@ public class MailServiceImp implements MailService {
} else { } else {
throw new ServerErrorException("Error Connection"); throw new ServerErrorException("Error Connection");
} }
} catch (URISyntaxException e) {
throw new ServerErrorException("Error Connection");
}
} }
@Override @Override
@ -350,7 +334,6 @@ public class MailServiceImp implements MailService {
} }
String postUrl = mailHost + "/mail/single?" + generateMailSignParam(); String postUrl = mailHost + "/mail/single?" + generateMailSignParam();
HttpRequestResult result = null; HttpRequestResult result = null;
try {
logger.info("===sendEmail===noticeBean:" + JSON.toJSON(noticeBean)); logger.info("===sendEmail===noticeBean:" + JSON.toJSON(noticeBean));
result = new HttpRequestGenerator(postUrl, RequestMethod.POST).setJSONEntity(noticeBean).setTimeout(60_000).execute(); result = new HttpRequestGenerator(postUrl, RequestMethod.POST).setJSONEntity(noticeBean).setTimeout(60_000).execute();
if (result.isSuccess()) { if (result.isSuccess()) {
@ -360,9 +343,6 @@ public class MailServiceImp implements MailService {
} else { } else {
throw new ServerErrorException("Error Connection"); throw new ServerErrorException("Error Connection");
} }
} catch (URISyntaxException e) {
throw new ServerErrorException("Error Connection");
}
} }
} }

@ -9,9 +9,9 @@ import au.com.royalpay.payment.tools.env.PlatformEnvironment;
import au.com.royalpay.payment.tools.exceptions.BadRequestException; import au.com.royalpay.payment.tools.exceptions.BadRequestException;
import au.com.royalpay.payment.tools.exceptions.ServerErrorException; import au.com.royalpay.payment.tools.exceptions.ServerErrorException;
import au.com.royalpay.payment.tools.fixing.FixedDocumentHelper; import au.com.royalpay.payment.tools.fixing.FixedDocumentHelper;
import cn.yixblog.platform.http.HttpRequestGenerator;
import cn.yixblog.platform.http.HttpRequestResult;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.time.DateFormatUtils; import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.http.NameValuePair; import org.apache.http.NameValuePair;
@ -25,18 +25,9 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.io.IOException;
import cn.yixblog.platform.http.HttpRequestGenerator; import java.util.*;
import cn.yixblog.platform.http.HttpRequestResult;
/** /**
* Created by wangning on 2017/12/7. * Created by wangning on 2017/12/7.
@ -266,7 +257,7 @@ public class OfeiClientImpl implements OfeiClient {
} else { } else {
throw new ChannelNetworkException(errMsg + "-->Network Error:" + res.getStatusCode()); throw new ChannelNetworkException(errMsg + "-->Network Error:" + res.getStatusCode());
} }
} catch (URISyntaxException | DocumentException | IOException e) { } catch (DocumentException | IOException e) {
throw new ChannelNetworkException(errMsg + "-->Network Error", e); throw new ChannelNetworkException(errMsg + "-->Network Error", e);
} }
} }
@ -282,7 +273,7 @@ public class OfeiClientImpl implements OfeiClient {
} else { } else {
throw new ChannelNetworkException(errMsg + "-->Network Error:" + res.getStatusCode()); throw new ChannelNetworkException(errMsg + "-->Network Error:" + res.getStatusCode());
} }
} catch (URISyntaxException | IOException e) { } catch (IOException e) {
throw new ChannelNetworkException(errMsg + "-->Network Error", e); throw new ChannelNetworkException(errMsg + "-->Network Error", e);
} }

@ -2,6 +2,7 @@ package au.com.royalpay.payment.manage.organizations.beans;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotEmpty;
/** /**
@ -73,7 +74,6 @@ public class OrgInfo {
if (StringUtils.isNotBlank(senior_parent_org_id)) { if (StringUtils.isNotBlank(senior_parent_org_id)) {
param.put("senior_parent_org_id", senior_parent_org_id); param.put("senior_parent_org_id", senior_parent_org_id);
} }
return param; return param;
} }
@ -359,4 +359,5 @@ public class OrgInfo {
public void setMin_cb_bankpay_rate(Double min_cb_bankpay_rate) { public void setMin_cb_bankpay_rate(Double min_cb_bankpay_rate) {
this.min_cb_bankpay_rate = min_cb_bankpay_rate; this.min_cb_bankpay_rate = min_cb_bankpay_rate;
} }
} }

@ -23,12 +23,22 @@ public interface OrgManager {
JSONObject saveNewOrg(OrgInfo org); JSONObject saveNewOrg(OrgInfo org);
void updateOrg(int orgId, OrgInfo org); void updateOrg(int orgId, OrgInfo org, JSONObject manager);
void setPartnerPublicKeyConfig(int orgId, JSONObject manager, String ipWhitelistConfig);
void refreshPlatformPublicKeyConfig(int orgId, JSONObject manager);
List<JSONObject> getReferrers(); List<JSONObject> getReferrers();
JSONObject getCityPartnerPrizeInfoList(int page, int limit,int orgId, JSONObject manager); JSONObject getCityPartnerPrizeInfoList(int page, int limit,int orgId, JSONObject manager);
String refreshMerchantCode(int orgId, JSONObject manager);
String initMerchantCode();
boolean getMerchantIsValid(String clientMoniker);
void switchPermission(int orgId, String permissionName, boolean enabled); void switchPermission(int orgId, String permissionName, boolean enabled);
List<JSONObject> listAllOrg(); List<JSONObject> listAllOrg();

@ -2,27 +2,32 @@ package au.com.royalpay.payment.manage.organizations.core.impls;
import au.com.royalpay.payment.manage.mappers.financial.FinancialPartnerCommissionMapper; import au.com.royalpay.payment.manage.mappers.financial.FinancialPartnerCommissionMapper;
import au.com.royalpay.payment.manage.mappers.system.OrgMapper; import au.com.royalpay.payment.manage.mappers.system.OrgMapper;
import au.com.royalpay.payment.manage.mappers.system.OrgSignInfoMapper;
import au.com.royalpay.payment.manage.organizations.beans.OrgInfo; import au.com.royalpay.payment.manage.organizations.beans.OrgInfo;
import au.com.royalpay.payment.manage.organizations.core.OrgManager; import au.com.royalpay.payment.manage.organizations.core.OrgManager;
import au.com.royalpay.payment.tools.codec.RSACrypt;
import au.com.royalpay.payment.tools.exceptions.ForbiddenException; import au.com.royalpay.payment.tools.exceptions.ForbiddenException;
import au.com.royalpay.payment.tools.utils.PageListUtils; import au.com.royalpay.payment.tools.utils.PageListUtils;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.github.miemiedev.mybatis.paginator.domain.Order; import com.github.miemiedev.mybatis.paginator.domain.Order;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds; import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.PageList; import com.github.miemiedev.mybatis.paginator.domain.PageList;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.security.KeyPair;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import javax.annotation.Resource;
/** /**
* Created by yixian on 2016-10-18. * Created by yixian on 2016-10-18.
*/ */
@ -32,6 +37,8 @@ public class OrgManagerImpl implements OrgManager {
private OrgMapper orgMapper; private OrgMapper orgMapper;
@Resource @Resource
private FinancialPartnerCommissionMapper financialPartnerCommissionMapper; private FinancialPartnerCommissionMapper financialPartnerCommissionMapper;
@Resource
private OrgSignInfoMapper orgSignInfoMapper;
@Override @Override
public List<JSONObject> listOrgs(boolean detail) { public List<JSONObject> listOrgs(boolean detail) {
@ -102,7 +109,13 @@ public class OrgManagerImpl implements OrgManager {
@Override @Override
public JSONObject getOrgDetail(int orgId,JSONObject manager) { public JSONObject getOrgDetail(int orgId,JSONObject manager) {
return orgMapper.findOne(orgId); JSONObject org = orgMapper.findOne(orgId);
JSONObject gatewayInfo = orgSignInfoMapper.findByOrgId(orgId);
if (gatewayInfo != null) {
gatewayInfo.remove("platform_private_key");
org.putAll(gatewayInfo);
}
return org;
} }
@Override @Override
@ -113,17 +126,58 @@ public class OrgManagerImpl implements OrgManager {
json.put("sort_no", orgMapper.listAllOrgs().size()); json.put("sort_no", orgMapper.listAllOrgs().size());
json.put("create_time",new Date()); json.put("create_time",new Date());
orgMapper.saveOrg(json); orgMapper.saveOrg(json);
initOrgGatewayInfo(json);
return json; return json;
} }
@Override @Override
public void updateOrg(int orgId, OrgInfo org) { public void updateOrg(int orgId, OrgInfo org, JSONObject manager) {
JSONObject json = org.toJSON(); JSONObject json = org.toJSON();
checkOrgRate(json); checkOrgRate(json);
json.put("org_id", orgId); json.put("org_id", orgId);
orgMapper.updateOrg(json); orgMapper.updateOrg(json);
} }
@Override
@Transactional
public void refreshPlatformPublicKeyConfig(int orgId, JSONObject manager) {
int managerOrgId = manager.getIntValue("org_id");
if (managerOrgId != 0 && managerOrgId != 1 && managerOrgId != orgId) {
throw new ForbiddenException("You have no permission to setting the org");
}
JSONObject org = orgMapper.findOne(orgId);
JSONObject gateway = orgSignInfoMapper.findByOrgId(orgId);
if (gateway == null) {
initOrgGatewayInfo(org);
}else {
JSONObject key = getRsaKey();
gateway.put("platform_public_key", key.getString("public_key"));
gateway.put("platform_private_key", key.getString("private_key"));
gateway.put("last_update_by", manager.getString("manager_id"));
gateway.put("last_update_date", new Date());
orgSignInfoMapper.update(gateway);
}
}
@Override
public void setPartnerPublicKeyConfig(int orgId, JSONObject manager, String publicKey) {
int managerOrgId = manager.getIntValue("org_id");
if (managerOrgId != 0 && managerOrgId != 1 && managerOrgId != orgId) {
throw new ForbiddenException("You have no permission to setting the org");
}
JSONObject org = orgMapper.findOne(orgId);
JSONObject gateway = orgSignInfoMapper.findByOrgId(orgId);
if (gateway == null) {
org.put("mch_public_key", publicKey);
initOrgGatewayInfo(org);
}else {
gateway.put("mch_public_key", publicKey);
gateway.put("last_update_by", manager.getString("manager_id"));
gateway.put("last_update_date", new Date());
orgSignInfoMapper.update(gateway);
}
}
@Override @Override
public List<JSONObject> getReferrers() { public List<JSONObject> getReferrers() {
return orgMapper.listOrgs(1,new PageBounds()); return orgMapper.listOrgs(1,new PageBounds());
@ -139,6 +193,45 @@ public class OrgManagerImpl implements OrgManager {
return null; return null;
} }
@Override
public String refreshMerchantCode(int orgId, JSONObject manager) {
String merchantCode = null;
int managerOrgId = manager.getIntValue("org_id");
JSONObject org = orgMapper.findOne(orgId);
if (managerOrgId != 0 && managerOrgId != 1 && managerOrgId != orgId && managerOrgId != org.getIntValue("parent_org_id")) {
throw new ForbiddenException("You have no permission to setting the org");
}
JSONObject gateway = orgSignInfoMapper.findByOrgId(orgId);
merchantCode = initMerchantCode();
if (gateway == null) {
org.put("gateway_short_id", merchantCode);
initOrgGatewayInfo(org);
}else {
gateway.put("gateway_short_id", merchantCode);
gateway.put("last_update_by", manager.getString("manager_id"));
gateway.put("last_update_date", new Date());
orgSignInfoMapper.update(gateway);
}
return merchantCode;
}
@Override
public String initMerchantCode() {
String code = RandomStringUtils.randomAlphanumeric(10).toUpperCase();
if (!getMerchantIsValid(code)) {
return initMerchantCode();
}
return code;
}
@Override
public boolean getMerchantIsValid(String clientMoniker) {
if (orgSignInfoMapper.getPartnercode(clientMoniker) > 0) {
return false;
}
return true;
}
@Override @Override
public void switchPermission(int orgId, String permissionName, boolean enabled) { public void switchPermission(int orgId, String permissionName, boolean enabled) {
JSONObject org = new JSONObject(); JSONObject org = new JSONObject();
@ -272,4 +365,27 @@ public class OrgManagerImpl implements OrgManager {
} }
} }
} }
private JSONObject getRsaKey() {
JSONObject key = new JSONObject();
KeyPair keyPairGen = RSACrypt.generateKeyPairs();
RSAPublicKey publicKey = (RSAPublicKey) keyPairGen.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPairGen.getPrivate();
key.put("public_key", Base64.encodeBase64String(publicKey.getEncoded()));
key.put("private_key", Base64.encodeBase64String(privateKey.getEncoded()));
return key;
}
private void initOrgGatewayInfo(JSONObject org) {
JSONObject key = getRsaKey();
String shortId = org.containsKey("gateway_short_id") ? org.getString("gateway_short_id") : initMerchantCode();
String mchPublicKey = org.containsKey("mch_public_key") ? org.getString("mch_public_key") : null;
org.put("gateway_short_id", shortId);
org.put("mch_public_key", mchPublicKey);
org.put("platform_public_key", key.getString("public_key"));
org.put("platform_private_key", key.getString("private_key"));
org.put("is_valid", 1);
org.put("creation_by", "init");
org.put("creation_date", new Date());
orgSignInfoMapper.insert(org);
}
} }

@ -7,16 +7,13 @@ import au.com.royalpay.payment.manage.permission.manager.RequireManager;
import au.com.royalpay.payment.tools.CommonConsts; import au.com.royalpay.payment.tools.CommonConsts;
import au.com.royalpay.payment.tools.http.HttpUtils; import au.com.royalpay.payment.tools.http.HttpUtils;
import au.com.royalpay.payment.tools.permission.enums.ManagerRole; import au.com.royalpay.payment.tools.permission.enums.ManagerRole;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import org.springframework.validation.Errors; import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.List;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.validation.Valid; import javax.validation.Valid;
import java.util.List;
/** /**
* Created by yixian on 2016-10-18. * Created by yixian on 2016-10-18.
@ -75,9 +72,19 @@ public class OrgManageController {
} }
@ManagerMapping(value = "/{orgId}", method = RequestMethod.PUT) @ManagerMapping(value = "/{orgId}", method = RequestMethod.PUT)
public void updateOrg(@PathVariable int orgId, @RequestBody @Valid OrgInfo org, Errors errors) { public void updateOrg(@PathVariable int orgId, @ModelAttribute(CommonConsts.MANAGER_STATUS) JSONObject manager, @RequestBody @Valid OrgInfo org, Errors errors) {
HttpUtils.handleValidErrors(errors); HttpUtils.handleValidErrors(errors);
orgManager.updateOrg(orgId, org); orgManager.updateOrg(orgId, org, manager);
}
@ManagerMapping(value = "/{orgId}/partner_public_key", method = RequestMethod.PUT)
public void setPartnerPublicKeyConfig(@PathVariable int orgId, @ModelAttribute(CommonConsts.MANAGER_STATUS) JSONObject manager, @RequestBody JSONObject config) {
orgManager.setPartnerPublicKeyConfig(orgId, manager, config.getString("partner_public_key"));
}
@ManagerMapping(value = "/{orgId}/refresh_platform_public_key", method = RequestMethod.PUT)
public void refreshPlatformPublicKeyConfig(@PathVariable int orgId, @ModelAttribute(CommonConsts.MANAGER_STATUS) JSONObject manager) {
orgManager.refreshPlatformPublicKeyConfig(orgId, manager);
} }
@ManagerMapping(value = "/{orgId}/enable_change_rate",method = RequestMethod.PUT,role = {ManagerRole.ADMIN}) @ManagerMapping(value = "/{orgId}/enable_change_rate",method = RequestMethod.PUT,role = {ManagerRole.ADMIN})
@ -97,4 +104,11 @@ public class OrgManageController {
@RequestParam(defaultValue = "20") int limit, @ModelAttribute(CommonConsts.MANAGER_STATUS) JSONObject manager) { @RequestParam(defaultValue = "20") int limit, @ModelAttribute(CommonConsts.MANAGER_STATUS) JSONObject manager) {
return orgManager.getCityPartnerPrizeInfoList(page, limit,orgId,manager); return orgManager.getCityPartnerPrizeInfoList(page, limit,orgId,manager);
} }
@RequestMapping(value = "/{orgId}/init/merchant_code", method = RequestMethod.GET, produces = "application/json")
public JSONObject initMerchantCode(@PathVariable int orgId, @ModelAttribute(CommonConsts.MANAGER_STATUS) JSONObject manager) {
JSONObject result = new JSONObject();
result.put("partner_code", orgManager.refreshMerchantCode(orgId, manager));
return result;
}
} }

@ -12,9 +12,7 @@ public class ReadWriteSplitRoutingDataSource extends AbstractRoutingDataSource {
@Override @Override
public Object determineCurrentLookupKey() { public Object determineCurrentLookupKey() {
DbContextHolder.DbType dataSource = DbContextHolder.getDbType(); return DbContextHolder.getDbType();
logger.info("------------------当前数据源:{}---------------------",dataSource);
return dataSource;
} }
} }

@ -11,7 +11,6 @@ import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import java.io.IOException; import java.io.IOException;
import java.net.URISyntaxException;
/** /**
@ -29,7 +28,6 @@ public class PosterServiceImpl implements PosterService {
public void updatePoster(String imgUrl) { public void updatePoster(String imgUrl) {
String url = cmsHost + "/api/statistics/count"; String url = cmsHost + "/api/statistics/count";
HttpRequestGenerator htg = new HttpRequestGenerator(url, RequestMethod.PUT); HttpRequestGenerator htg = new HttpRequestGenerator(url, RequestMethod.PUT);
try {
HttpRequestResult result = htg.addQueryString("imgUrl", imgUrl).execute(); HttpRequestResult result = htg.addQueryString("imgUrl", imgUrl).execute();
if (result.isSuccess()) { if (result.isSuccess()) {
int statusCode = result.getStatusCode(); int statusCode = result.getStatusCode();
@ -37,9 +35,6 @@ public class PosterServiceImpl implements PosterService {
logger.info("CMS request succeeded"); logger.info("CMS request succeeded");
} }
} }
} catch (URISyntaxException e) {
e.printStackTrace();
}
} }
@Override @Override
@ -57,8 +52,6 @@ public class PosterServiceImpl implements PosterService {
// final String s = result.getResponseContentString(); // final String s = result.getResponseContentString();
return obj; return obj;
} }
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }

@ -23,11 +23,9 @@ import au.com.royalpay.payment.tools.exceptions.ForbiddenException;
import au.com.royalpay.payment.tools.permission.enums.PartnerRole; import au.com.royalpay.payment.tools.permission.enums.PartnerRole;
import au.com.royalpay.payment.tools.utils.CurrencyAmountUtils; import au.com.royalpay.payment.tools.utils.CurrencyAmountUtils;
import au.com.royalpay.payment.tools.utils.PageListUtils; import au.com.royalpay.payment.tools.utils.PageListUtils;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds; import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.PageList; import com.github.miemiedev.mybatis.paginator.domain.PageList;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisher;
@ -35,12 +33,11 @@ import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import javax.annotation.Resource;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import javax.annotation.Resource;
/** /**
* Created by yixian on 2016-07-04. * Created by yixian on 2016-07-04.
*/ */
@ -222,7 +219,7 @@ public class RefundServiceImpl implements RefundService, ApplicationEventPublish
int accountClientId = partnerAccount.getIntValue("client_id"); int accountClientId = partnerAccount.getIntValue("client_id");
Assert.isTrue(accountClientId == client.getIntValue("client_id") || accountClientId == client.getIntValue("parent_client_id") Assert.isTrue(accountClientId == client.getIntValue("client_id") || accountClientId == client.getIntValue("parent_client_id")
||clientManager.listLevel3Client(accountClientId).contains(client.getIntValue("parent_client_id")), || clientManager.listLevel3Client(accountClientId).contains(client.getIntValue("parent_client_id")),
"This order is not belong to current merchant"); "This order is not belong to current merchant");
operator.put("operator_id", partnerAccount.getString("account_id")); operator.put("operator_id", partnerAccount.getString("account_id"));
operator.put("operator", partnerAccount.getString("display_name")); operator.put("operator", partnerAccount.getString("display_name"));
@ -233,7 +230,7 @@ public class RefundServiceImpl implements RefundService, ApplicationEventPublish
boolean requireAudit = type == OperatorType.PARTNER && PartnerRole.getRole(partnerAccount.getIntValue("role")) == PartnerRole.CASHIER boolean requireAudit = type == OperatorType.PARTNER && PartnerRole.getRole(partnerAccount.getIntValue("role")) == PartnerRole.CASHIER
&& clientConfig.getBooleanValue("enable_refund_auth"); && clientConfig.getBooleanValue("enable_refund_auth");
logger.debug("applyer type=" + type + "; require audit=" + requireAudit); logger.debug("applyer type=" + type + "; require audit=" + requireAudit);
return paymentApi.refundOrder(orderId, null, amount, remark, operator, type, requireAudit); return paymentApi.refundOrder(null, orderId, null, amount, remark, operator, type, requireAudit);
} }
// 订单使用积分商城优惠券,仅支持全额退款 // 订单使用积分商城优惠券,仅支持全额退款

@ -2,15 +2,15 @@
spring.datasource.type = com.zaxxer.hikari.HikariDataSource spring.datasource.type = com.zaxxer.hikari.HikariDataSource
#数据源master #数据源master
spring.datasource.master.schema-name=royalpay_production spring.datasource.master.schema-name=royalpay_dev
spring.datasource.master.host=192.168.1.52:3306 spring.datasource.master.host=127.0.0.1:3306
spring.datasource.master.jdbc-url=jdbc:mysql://${spring.datasource.master.host}/${spring.datasource.master.schema-name}?useUnicode=true&characterEncoding=utf8&useSSL=false spring.datasource.master.jdbc-url=jdbc:mysql://${spring.datasource.master.host}/${spring.datasource.master.schema-name}?useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.master.username=taylor spring.datasource.master.username=root
spring.datasource.master.password=taylor spring.datasource.master.password=root
#数据源salve #数据源salve
spring.datasource.slave.schema-name=royalpay_production spring.datasource.slave.schema-name=royalpay_dev
spring.datasource.slave.host=192.168.1.52:3306 spring.datasource.slave.host=127.0.0.1:3306
spring.datasource.slave.jdbc-url=jdbc:mysql://${spring.datasource.slave.host}/${spring.datasource.slave.schema-name}?useUnicode=true&characterEncoding=utf8&useSSL=false spring.datasource.slave.jdbc-url=jdbc:mysql://${spring.datasource.slave.host}/${spring.datasource.slave.schema-name}?useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.slave.username=taylor spring.datasource.slave.username=root
spring.datasource.slave.password=taylor spring.datasource.slave.password=root

@ -2,27 +2,33 @@
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="au.com.royalpay.payment.manage.mappers.log.ClearingDetailMapper"> <mapper namespace="au.com.royalpay.payment.manage.mappers.log.ClearingDetailMapper">
<update id="updateAllBanks"> <update id="updateAllBanks">
update log_clearing_detail set settle_bank=#{settle_bank} where clearing_id=#{clearing_id} update log_clearing_detail
set settle_bank=#{settle_bank}
where clearing_id = #{clearing_id}
</update> </update>
<select id="listReports" resultType="com.alibaba.fastjson.JSONObject"> <select id="listReports" resultType="com.alibaba.fastjson.JSONObject">
<![CDATA[ <![CDATA[
SELECT SELECT settle_date_from,
settle_date_from,
settle_date_to, settle_date_to,
clearing_amount, clearing_amount,
report_date report_date
FROM log_clearing_detail FROM log_clearing_detail
WHERE client_id = #{client_id} AND month(report_date) = month(#{month}) AND year(report_date) = year(#{month}) WHERE client_id = #{client_id}
AND month(report_date) = month(#{month})
AND year(report_date) = year(#{month})
]]> ]]>
</select> </select>
<select id="listReportsOfSettlement" resultType="com.alibaba.fastjson.JSONObject"> <select id="listReportsOfSettlement" resultType="com.alibaba.fastjson.JSONObject">
SELECT SELECT d.*,
d.*,DATE_FORMAT(d.report_date,'%y-%m-%d')clear_date,DATE_FORMAT(d.settle_date_from,'%m-%d')settle_from,DATE_FORMAT(d.settle_date_to,'%m-%d')settle_to, DATE_FORMAT(d.report_date, '%y-%m-%d') clear_date,
DATE_FORMAT(d.settle_date_from, '%m-%d') settle_from,
DATE_FORMAT(d.settle_date_to, '%m-%d') settle_to,
c.client_id, c.client_id,
c.client_moniker, c.client_moniker,
c.parent_client_id c.parent_client_id,
c.ext_params
FROM log_clearing_detail d FROM log_clearing_detail d
INNER JOIN sys_clients c ON c.client_id = d.client_id AND c.is_valid=1 INNER JOIN sys_clients c ON c.client_id = d.client_id AND c.is_valid = 1
WHERE d.clearing_id = #{clearing_id} WHERE d.clearing_id = #{clearing_id}
</select> </select>
@ -57,12 +63,15 @@
and c.org_id = #{org_id} and c.org_id = #{org_id}
</if> </if>
<if test="org_ids!=null">and c.org_id in <if test="org_ids!=null">and c.org_id in
<foreach collection="org_ids" item="org_id" open="(" close=")" separator=",">#{org_id}</foreach></if> <foreach collection="org_ids" item="org_id" open="(" close=")" separator=",">#{org_id}</foreach>
</if>
</where> </where>
</select> </select>
<select id="listClientSettlementLog" resultType="com.alibaba.fastjson.JSONObject"> <select id="listClientSettlementLog" resultType="com.alibaba.fastjson.JSONObject">
select *,DATE_FORMAT(report_date,'%y-%m-%d')clear_date,DATE_FORMAT(settle_date_from,'%m-%d')settle_from,DATE_FORMAT(settle_date_to,'%m-%d')settle_to FROM log_clearing_detail select
*,DATE_FORMAT(report_date,'%y-%m-%d')clear_date,DATE_FORMAT(settle_date_from,'%m-%d')settle_from,DATE_FORMAT(settle_date_to,'%m-%d')settle_to
FROM log_clearing_detail
<where> <where>
<if test="client_ids!=null"> <if test="client_ids!=null">
AND client_id IN AND client_id IN

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="au.com.royalpay.payment.manage.mappers.log.PreSettleTaskMapper">
<update id="resetClearStatus">
update log_presettle_task p
inner join log_clearing_detail cd on cd.clear_detail_id = p.clear_detail_id
set p.clear_detail_id=null,
p.finish_flag=0
where cd.clearing_id = #{clearing_id}
</update>
</mapper>

@ -4,7 +4,9 @@
<update id="removeSettleRemark"> <update id="removeSettleRemark">
UPDATE pmt_transactions AS t UPDATE pmt_transactions AS t
INNER JOIN log_clearing_detail d ON d.clear_detail_id = t.clearing_order INNER JOIN log_clearing_detail d ON d.clear_detail_id = t.clearing_order
SET clearing_status = 0, SET clearing_status = if(
(select count(task_id) from log_presettle_task p where p.clear_detail_id = d.clear_detail_id) >
0, 4, 0),
clearing_order = NULL, clearing_order = NULL,
clearing_time = NULL clearing_time = NULL
WHERE d.clearing_id = #{clearing_id} WHERE d.clearing_id = #{clearing_id}
@ -61,7 +63,8 @@
SELECT count(1) SELECT count(1)
FROM pmt_transactions t FROM pmt_transactions t
<if test="dev_id!=null or "> <if test="dev_id!=null or ">
INNER JOIN (select o.order_id from pmt_orders o<where> INNER JOIN (select o.order_id from pmt_orders o
<where>
<if test="dev_id!=null">and o.dev_id = #{dev_id}</if> <if test="dev_id!=null">and o.dev_id = #{dev_id}</if>
<if test=" <if test="
channel!=null">and channel!=null">and
@ -69,7 +72,8 @@
o.channel=#{chan} o.channel=#{chan}
</foreach> </foreach>
</if> </if>
</where>)oo ON oo.order_id=t.order_id </where>
)oo ON oo.order_id=t.order_id
</if> </if>
<where> <where>
@ -628,7 +632,7 @@
select sum(if(temp.transaction_type = 'Credit', temp.clearing_amount * d.proportion, select sum(if(temp.transaction_type = 'Credit', temp.clearing_amount * d.proportion,
-temp.clearing_amount * d.proportion)) -temp.clearing_amount * d.proportion))
total total
FROM (SELECT l.client_id,l.clearing_amount,l.refund_id,l.transaction_type,o.create_time FROM (SELECT l.client_id, l.clearing_amount, l.refund_id, l.transaction_type, o.create_time
FROM pmt_transactions l FROM pmt_transactions l
INNER JOIN pmt_orders o INNER JOIN pmt_orders o
ON o.order_id = l.order_id ON o.order_id = l.order_id
@ -1073,7 +1077,7 @@
and t.clearing_status = 1 and t.clearing_status = 1
and t.transaction_time between #{from} and #{to} and t.transaction_time between #{from} and #{to}
and t.channel != 'Settlement' and t.channel != 'Settlement'
group by cd.bsb_no,cd.account_no group by cd.bsb_no, cd.account_no
order by period_start order by period_start
</select> </select>
<select id="listCreditTransactionsForSecure" resultType="com.alibaba.fastjson.JSONObject"> <select id="listCreditTransactionsForSecure" resultType="com.alibaba.fastjson.JSONObject">
@ -1208,13 +1212,13 @@
</select> </select>
<select id="getLastDaytransAmount" resultType="com.alibaba.fastjson.JSONObject"> <select id="getLastDaytransAmount" resultType="com.alibaba.fastjson.JSONObject">
SELECT ifnull(SUM(IF(transaction_type='Credit',clearing_amount,-clearing_amount)),0) clearing_amount, SELECT ifnull(SUM(IF(transaction_type = 'Credit', clearing_amount, -clearing_amount)), 0) clearing_amount,
ifnull(SUM(IF(transaction_type='Credit',total_surcharge,-total_surcharge)),0) total_surcharge, ifnull(SUM(IF(transaction_type = 'Credit', total_surcharge, -total_surcharge)), 0) total_surcharge,
ifnull(SUM(IF(transaction_type='Credit',channel_surcharge,-channel_surcharge)),0) channel_surcharge, ifnull(SUM(IF(transaction_type = 'Credit', channel_surcharge, -channel_surcharge)), 0) channel_surcharge,
channel channel
FROM pmt_transactions FROM pmt_transactions
WHERE channel!='Settlement' WHERE channel != 'Settlement'
AND channel!='System' AND channel != 'System'
AND system_generate = 0 AND system_generate = 0
AND transaction_time >= #{datefrom} AND transaction_time >= #{datefrom}
AND transaction_time &lt; #{dateto} AND transaction_time &lt; #{dateto}
@ -1222,14 +1226,14 @@
</select> </select>
<select id="useAlipayOnlineClients" resultType="java.lang.Integer"> <select id="useAlipayOnlineClients" resultType="java.lang.Integer">
SELECT DISTINCT client_id FROM pmt_transactions SELECT DISTINCT client_id
WHERE order_channel='AlipayOnline' FROM pmt_transactions
and create_time>='2019-01-01 00:00:00' WHERE order_channel = 'AlipayOnline'
and create_time >= '2019-01-01 00:00:00'
</select> </select>
<select id="getSettleDataDailyReport" resultType="com.alibaba.fastjson.JSONObject"> <select id="getSettleDataDailyReport" resultType="com.alibaba.fastjson.JSONObject">
SELECT SELECT channel,
channel,
SUM(IF(transaction_type = 'Credit', settle_amount, -settle_amount)) AS settle_amount, SUM(IF(transaction_type = 'Credit', settle_amount, -settle_amount)) AS settle_amount,
SUM(IF(transaction_type = 'Credit', clearing_amount, 0)) AS credit_amount, SUM(IF(transaction_type = 'Credit', clearing_amount, 0)) AS credit_amount,
SUM(IF(transaction_type = 'Credit', 0, -clearing_amount)) AS debit_amount, SUM(IF(transaction_type = 'Credit', 0, -clearing_amount)) AS debit_amount,

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="au.com.royalpay.payment.manage.mappers.system.OrgSignInfoMapper">
<select id="getPartnercode" resultType="int">
SELECT count(1)
FROM org_sign_info
where gateway_short_id = #{codes};
</select>
</mapper>

@ -1,6 +1,6 @@
msg.test=测试 msg.test=测试
error.payment.valid.param_missing=请填写{0} error.payment.valid.param_missing= {0} 请填写
error.payment.valid.invalid_time=时间格式不正确 error.payment.valid.invalid_time=时间格式不正确
error.payment.valid.invalid_channel=不合法的支付通道 error.payment.valid.invalid_channel=不合法的支付通道
error.payment.valid.invalid_fee=不正确的金额 error.payment.valid.invalid_fee=不正确的金额

@ -542,8 +542,68 @@ define(['angular', 'uiRouter', 'uiBootstrap'], function (angular) {
$scope.listManagers(); $scope.listManagers();
}) })
} }
$scope.gateway_sign = {};
$scope.gateway_sign.platform_public_key = $scope.org.platform_public_key;
$scope.gateway_sign.org_id = $scope.org.org_id;
$scope.gateway_sign.mch_public_key = $scope.org.mch_public_key;
$scope.refreshPlatformPubliKey = function () {
$uibModal.open({
templateUrl: '/static/payment/partner/templates/partner_refresh_platform_public_key_dialog.html',
controller: 'clientRefreshPlatformPublicKeyDialogCtrl',
backdrop: false,
size: 'lg',
resolve: {
gateway_sign: function () {
return $scope.gateway_sign;
}
}
}).result.then(function () {
commonDialog.alert({
title: 'Success!',
content: 'RoyalPay Public Key Refresh Successfully',
type: 'success'
})
$state.reload();
})
};
$scope.resetPartnerPubliKey = function () {
$uibModal.open({
templateUrl: '/static/payment/partner/templates/partner_reset_public_key_dialog.html',
controller: 'clientResetPartnerPublicKeyDialogCtrl',
backdrop: false,
size: 'lg',
resolve: {
gateway_sign: function () {
return $scope.gateway_sign;
}
}
}).result.then(function () {
commonDialog.alert({
title: 'Success!',
content: 'Partner Public Key Upload Successfully',
type: 'success'
})
$state.reload();
})
};
$scope.refreshMerchantCode = function () {
commonDialog.confirm({
title: 'Confirm',
content: 'This operation will refresh the gateway short id, Are you sure?'
}).then(function () {
$http.get('/sys/orgs/' + $scope.org.org_id + '/init/merchant_code').then(function (response) {
commonDialog.alert({title: 'Success', content: "Gateway Short Id Refresh Successfully", type: 'success'})
$scope.org.gateway_short_id = response.data.partner_code;
}, function (resp) {
commonDialog.alert({title: 'Error', content: resp.data.message, type: 'error'})
});
})
};
}]); }]);
app.controller('orgDetailParentCtrl', ['$scope', '$http', '$state', 'Upload', '$uibModal','commonDialog', 'org','stateMap', function ($scope, $http, $state, Upload,$uibModal,commonDialog, org,stateMap) { app.controller('orgDetailParentCtrl', ['$scope', '$http', '$state', 'Upload', '$uibModal','commonDialog', 'org','stateMap', function ($scope, $http, $state, Upload,$uibModal,commonDialog, org,stateMap) {
$scope.merchantCodeChecked = true;
$scope.merchantIsValid = true;
$scope.types = angular.copy(types); $scope.types = angular.copy(types);
$scope.states = stateMap.configs(); $scope.states = stateMap.configs();
$scope.commission_types = angular.copy(commission_types); $scope.commission_types = angular.copy(commission_types);
@ -589,62 +649,96 @@ define(['angular', 'uiRouter', 'uiBootstrap'], function (angular) {
commonDialog.alert({title: 'Error', content: resp.data.message, type: 'error'}) commonDialog.alert({title: 'Error', content: resp.data.message, type: 'error'})
}) })
}; };
/* $scope.gateway_sign = {};
$scope.toggleRateEditable = function () { $scope.gateway_sign.platform_public_key = $scope.org.platform_public_key;
if($scope.org.rate_editable==org.data.rate_editable){ $scope.gateway_sign.org_id = $scope.org.org_id;
return; $scope.gateway_sign.mch_public_key = $scope.org.mch_public_key;
}
$http.put('/sys/orgs/'+$scope.org.org_id+'/enable_change_rate',{enabled:$scope.org.rate_editable}).then(function () {
},function (resp) { $scope.refreshPlatformPubliKey = function () {
commonDialog.alert({title: 'Error', content: resp.data.message, type: 'error'}); $uibModal.open({
templateUrl: '/static/payment/partner/templates/partner_refresh_platform_public_key_dialog.html',
controller: 'clientRefreshPlatformPublicKeyDialogCtrl',
backdrop: false,
size: 'lg',
resolve: {
gateway_sign: function () {
return $scope.gateway_sign;
}
}
}).result.then(function () {
commonDialog.alert({
title: 'Success!',
content: 'RoyalPay Public Key Refresh Successfully',
type: 'success'
}) })
}; $state.reload();
$scope.search = {role:'1111111'};
$scope.listManagers = function () {
$http.get('/sys/manager_accounts',{params:{org_id:$scope.org.org_id}}).then(function (resp) {
$scope.managers = resp.data;
}) })
}; };
$scope.resetPartnerPubliKey = function () {
$scope.listManagers();
$scope.modifyManager = function (manager) {
$uibModal.open({ $uibModal.open({
templateUrl: '/static/config/managers/templates/modify.html', templateUrl: '/static/payment/partner/templates/partner_reset_public_key_dialog.html',
controller: 'modifyManagerCtrl', controller: 'clientResetPartnerPublicKeyDialogCtrl',
backdrop: false,
size: 'lg',
resolve: { resolve: {
manager: function () { gateway_sign: function () {
return angular.copy(manager); return $scope.gateway_sign;
} }
} }
}).result.then(function () { }).result.then(function () {
$scope.listManagers(); commonDialog.alert({
title: 'Success!',
content: 'Org Public Key Upload Successfully',
type: 'success'
})
$state.reload();
}) })
}; };
$scope.disableManager = function (manager) { $scope.refreshMerchantCode = function () {
commonDialog.confirm({ commonDialog.confirm({
title: 'Confirm!', title: 'Confirm',
content: 'You are setting manager ' + manager.display_name + ' disabled.Are you sure?' content: 'This operation will refresh the gateway short id, Are you sure?'
}).then(function () { }).then(function () {
$http.delete('/sys/manager_accounts/' + manager.manager_id).then(function () { $http.get('/sys/orgs/' + $scope.org.org_id + '/init/merchant_code').then(function (response) {
$scope.listManagers(); commonDialog.alert({title: 'Success', content: "Gateway Short Id Refresh Successfully", type: 'success'})
$scope.org.gateway_short_id = response.data.partner_code;
}, function (resp) { }, function (resp) {
commonDialog.alert({title: 'Error', content: resp.data.message, type: 'error'}) commonDialog.alert({title: 'Error', content: resp.data.message, type: 'error'})
}) });
}) })
}; };
$scope.newManager = function () { }]);
$uibModal.open({ app.controller('clientResetPartnerPublicKeyDialogCtrl', ['$scope', '$http', 'gateway_sign', function ($scope, $http, gateway_sign) {
templateUrl: '/static/config/managers/templates/new_manager.html', $scope.gateway_sign = angular.copy(gateway_sign);
controller: 'newManagerCtrl', $scope.uploadPublicKey = function (mch_public_key) {
resolve: { $scope.errmsg = null;
org: angular.copy($scope.org) $http.put('/sys/orgs/' + $scope.gateway_sign.org_id + '/partner_public_key', {partner_public_key: mch_public_key}).then(function () {
$scope.$close();
}, function (resp) {
$scope.errmsg = resp.data.message;
})
} }
}).result.then(function () { }]);
$scope.listManagers(); app.controller('clientRefreshPlatformPublicKeyDialogCtrl', ['$scope', '$http', 'gateway_sign', 'commonDialog', function ($scope, $http, gateway_sign, commonDialog) {
$scope.gateway_sign = angular.copy(gateway_sign);
$scope.copyPublicKey = function () {
var e = document.getElementById("c-cpKey");
e.select();
var successful = document.execCommand("Copy");
if (successful) {
commonDialog.alert({title: 'Success', content: '已复制到剪切板!', type: 'success'});
} else {
commonDialog.alert({title: 'Error', content: '您的浏览器不支持!请手动复制', type: 'error'});
}
};
$scope.refreshPublicKey = function () {
$scope.errmsg = null;
$http.put('/sys/orgs/' + $scope.gateway_sign.org_id + '/refresh_platform_public_key').then(function () {
$scope.$close();
}, function (resp) {
$scope.errmsg = resp.data.message;
}) })
}*/ }
}]); }]);
app.controller('newOrgCtrl', ['$scope', '$http', '$state', 'Upload', 'commonDialog','stateMap', function ($scope, $http, $state, Upload, commonDialog,stateMap) { app.controller('newOrgCtrl', ['$scope', '$http', '$state', 'Upload', 'commonDialog','stateMap', function ($scope, $http, $state, Upload, commonDialog,stateMap) {
$scope.types = angular.copy(types); $scope.types = angular.copy(types);
@ -711,7 +805,6 @@ define(['angular', 'uiRouter', 'uiBootstrap'], function (angular) {
}) })
}; };
}]); }]);
app.controller('modifyManagerCtrl', ['$scope', '$http', 'manager', function ($scope, $http, manager) { app.controller('modifyManagerCtrl', ['$scope', '$http', 'manager', function ($scope, $http, manager) {
$scope.manager = manager; $scope.manager = manager;
$scope.isOrgModify = true; $scope.isOrgModify = true;

@ -440,6 +440,36 @@
</div> </div>
</div> </div>
</uib-tab> </uib-tab>
<uib-tab heading="Gateway API" ng-if="org.type == 0 && org.org_id != 1">
<form class="form-horizontal margin-top" name="org_gateway_form">
<div class="form-group">
<label class="control-label col-sm-2">Gateway Short Id</label>
<div class="col-sm-8">
<p class="form-control-static">
{{org.gateway_short_id||'初始化'}}
<a role="button" ng-click="refreshMerchantCode()"><i class="fa fa-refresh"></i></a>
</p>
</div>
</div>
<div class="form-group"
ng-class="{'has-error':org_form.gateway_short_id.$invalid && org_form.gateway_short_id.$dirty}">
<label class="col-sm-2 control-label">RoyalPay Public Key</label>
<div class="col-sm-10" style="margin-top: 8px;">
<a role="button" ng-click="refreshPlatformPubliKey()">
View
</a>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Org Public Key</label>
<div class="col-sm-10" style="margin-top: 8px;">
<a role="button" ng-click="resetPartnerPubliKey()">
Upload
</a>
</div>
</div>
</form>
</uib-tab>
<uib-tab heading="Permission" ng-if="org.type == 0"> <uib-tab heading="Permission" ng-if="org.type == 0">
<form class="form-horizontal margin-top" name="org_permission_form"> <form class="form-horizontal margin-top" name="org_permission_form">
<div class="form-group"> <div class="form-group">

@ -432,6 +432,36 @@
<!--<button class="btn btn-success col-sm-offset-2" ng-click="update()"><i class="fa fa-save"></i> Update</button>--> <!--<button class="btn btn-success col-sm-offset-2" ng-click="update()"><i class="fa fa-save"></i> Update</button>-->
</form> </form>
</uib-tab> </uib-tab>
<uib-tab heading="Gateway API" ng-if="org.type == 0 && org.org_id != 1">
<form class="form-horizontal margin-top" name="org_gateway_form">
<div class="form-group">
<label class="control-label col-sm-2">Gateway Short Id</label>
<div class="col-sm-8">
<p class="form-control-static">
{{org.gateway_short_id||'初始化'}}
<a role="button" ng-click="refreshMerchantCode()"><i class="fa fa-refresh"></i></a>
</p>
</div>
</div>
<div class="form-group"
ng-class="{'has-error':org_form.gateway_short_id.$invalid && org_form.gateway_short_id.$dirty}">
<label class="col-sm-2 control-label">RoyalPay Public Key</label>
<div class="col-sm-10" style="margin-top: 8px;">
<a role="button" ng-click="refreshPlatformPubliKey()">
View
</a>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Org Public Key</label>
<div class="col-sm-10" style="margin-top: 8px;">
<a role="button" ng-click="resetPartnerPubliKey()">
Upload
</a>
</div>
</div>
</form>
</uib-tab>
</uib-tabset> </uib-tabset>
</div> </div>
</div> </div>

@ -43,7 +43,7 @@
</style> </style>
<section class="content-header"> <section class="content-header">
<h1> <h1>
<span ng-bind="partner.company_name"></span> <span ng-bind="partner.company_name"></span><span ng-if="partner.source==5" style="color:red;font-size:14px">(Gateway API)</span>
<i ng-if="partner.parent_client_id" class="fa fa-sitemap" title="Sub Partner"></i> <i ng-if="partner.parent_client_id" class="fa fa-sitemap" title="Sub Partner"></i>
<a class="text-primary" ng-if="'00011'|withRole" title="Mock Login" <a class="text-primary" ng-if="'00011'|withRole" title="Mock Login"
ng-href="/global/userstatus/current_manager/clients/{{partner.client_moniker}}/auth" target="_blank"><i ng-href="/global/userstatus/current_manager/clients/{{partner.client_moniker}}/auth" target="_blank"><i

@ -1,628 +0,0 @@
package au.com.royalpay.payment.manage.apps.core.impls;
import au.com.royalpay.payment.manage.analysis.core.WeekReporter;
import au.com.royalpay.payment.manage.citypartner.core.CityPartnerPrizeService;
import au.com.royalpay.payment.manage.mappers.payment.OrderMapper;
import au.com.royalpay.payment.manage.mappers.system.ClientConfigMapper;
import au.com.royalpay.payment.manage.mappers.system.ClientMapper;
import au.com.royalpay.payment.manage.mappers.system.OrgMapper;
import au.com.royalpay.payment.manage.merchants.core.ClientManager;
import au.com.royalpay.payment.manage.notice.core.MailService;
import au.com.royalpay.payment.tools.mail.MailGunClient;
import au.com.royalpay.payment.tools.mail.SendMail;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.bind.annotation.RequestMethod;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import cn.yixblog.platform.http.HttpRequestGenerator;
import cn.yixblog.platform.http.HttpRequestResult;
/**
* Created by wangning on 05/01/2018.
*/
// @SpringBootTest
// @ActiveProfiles({ "local", "alipay", "wechat", "jd", "bestpay" })
// @RunWith(SpringRunner.class)
public class CustomerImpressionImplTest {
@Resource
private OrderMapper orderMapper;
@Resource
private StringRedisTemplate stringRedisTemplate;
@Resource
private ClientMapper clientMapper;
@Resource
private OrgMapper orgMapper;
@Resource
private MailGunClient mailGunClient;
@Resource
private ClientConfigMapper clientConfigMapper;
@Resource
private ClientManager clientManager;
@Resource
private MailService mailService;
@Resource
private WeekReporter weekReporter;
@Resource
private CityPartnerPrizeService cityPartnerPrizeService;
@Test
public void redisQueue() {
BoundListOperations<String, String> ops = stringRedisTemplate.boundListOps("customer_impression");
JSONObject order = orderMapper.find("00009201711300930013961422");
for (int i = 0; i < 10000; i++) {
ops.rightPush(order.toJSONString());
}
}
@Test
public void excel1() {
try {
XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File("/Users/wangning/Desktop/asd.xlsx")));
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.rowIterator();
Row row = null;
Cell cell = null;
Map<String, Map<String, String>> result = new HashMap<>();
while (rowIterator.hasNext()) {
row = rowIterator.next();
cell = row.getCell(0);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
String amount = cell.getStringCellValue().trim();
cell = row.getCell(1);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
String dateStr = cell.getStringCellValue();
cell = row.getCell(2);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
String clientId = cell.getStringCellValue();
if (result.containsKey(clientId)) {
result.get(clientId).put(dateStr, amount);
} else {
Map<String, String> ele = new HashMap<>();
ele.put(dateStr, amount);
result.put(clientId, ele);
}
}
Set<String> clients = new HashSet<>();
result.entrySet().parallelStream().forEach(p -> {
p.getValue().entrySet().parallelStream().forEach(o -> {
BigDecimal insAvg = BigDecimal.valueOf(Double.valueOf(o.getValue()));
BigDecimal pastTotal = BigDecimal.ZERO;
for (int i = 1; i < 4; i++) {
if (i == 1) {
pastTotal = BigDecimal.ZERO;
}
try {
Date tmp = DateUtils.addMonths(DateUtils.parseDate(o.getKey(), "YYYYMM"), (-i + 1));
String pastKey = String.valueOf(tmp.getYear() + 1900) + String.valueOf(tmp.getMonth());
if (p.getValue().containsKey(String.valueOf(pastKey))) {
BigDecimal pastAvgtmp = BigDecimal.valueOf(Double.parseDouble(p.getValue().get(String.valueOf(pastKey))));
pastTotal = pastTotal.add(pastAvgtmp);
} else {
i = 10;
}
if (i == 3) {
try {
BigDecimal pastAvg = pastTotal.divide(BigDecimal.valueOf(3L), 5, BigDecimal.ROUND_HALF_DOWN);
if (pastAvg.compareTo(BigDecimal.ZERO) > 0) {
if (insAvg.divide(pastAvg, 5, BigDecimal.ROUND_HALF_DOWN).intValue() > 3) {
clients.add(p.getKey());
}
}
} catch (Exception ignore) {
}
}
} catch (ParseException e) {
}
}
});
});
clients.forEach(p -> {
System.out.println(p);
});
System.out.println(clients.size());
System.out.println(clients.size());
System.out.println(clients.size());
System.out.println(clients.size());
System.out.println(clients.size());
System.out.println(clients.size());
System.out.println(clients.size());
OutputStream out = new FileOutputStream("/Users/wangning/Desktop/春节活动报名结果通知(包含BD名称).xlsx");
workbook.write(out);
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void excel2() {
try {
XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File("/Users/wangning/Desktop/qwe.xlsx")));
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.rowIterator();
Row row = null;
Cell cell = null;
Map<String, LinkedHashMap<String, String>> result = new HashMap<>();
while (rowIterator.hasNext()) {
row = rowIterator.next();
cell = row.getCell(3);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
String orders = cell.getStringCellValue().trim();
cell = row.getCell(1);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
String dateStr = cell.getStringCellValue();
cell = row.getCell(2);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
String clientId = cell.getStringCellValue();
if (result.containsKey(clientId)) {
result.get(clientId).put(dateStr, orders);
} else {
LinkedHashMap<String, String> ele = new LinkedHashMap<>();
ele.put(dateStr, orders);
result.put(clientId, ele);
}
}
Set<String> clients = new HashSet<>();
for (Map.Entry<String, LinkedHashMap<String, String>> p : result.entrySet()) {
int count = 1;
for (Map.Entry<String, String> o : p.getValue().entrySet()) {
count += 1;
for (int i = 1; i < 4; i++) {
if (p.getValue().size() < 4 && count == p.getValue().size()) {
try {
if (DateUtils.addMonths(DateUtils.parseDate(o.getKey(), "YYYYMM"), 3).compareTo(new Date()) < 0) {
clients.add(p.getKey());
}
} catch (ParseException e) {
}
}
Date tmp = null;
try {
tmp = DateUtils.addMonths(DateUtils.parseDate(o.getKey(), "YYYYMM"), i);
String pastKey = String.valueOf(tmp.getYear() + 1900) + String.valueOf(tmp.getMonth());
if (p.getValue().containsKey(String.valueOf(pastKey))) {
i = 10;
} else {
if (i == 3 && (Integer.valueOf(o.getValue()) > 99)) {
clients.add(p.getKey());
}
}
} catch (ParseException e) {
e.printStackTrace();
}
}
}
}
System.out.println(clients.size());
System.out.println(clients.size());
System.out.println(clients.size());
System.out.println(clients.size());
System.out.println(clients.size());
System.out.println(clients.size());
System.out.println(clients.size());
// OutputStream out = new FileOutputStream("/Users/wangning/Desktop/春节活动报名结果通知(包含BD名称).xlsx");
// workbook.write(out);
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void excel3() {
List<JSONObject> clients = clientMapper.listValidClient();
Map<String,JSONObject> clientMap = new HashMap<>();
clients.parallelStream().forEach(p->{
clientMap.put(p.getString("client_id"),p);
});
try {
XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File("/Users/wangning/Desktop/e4.xlsx")));
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.rowIterator();
Row row = null;
Cell cell = null;
Map<String, LinkedHashMap<String, String>> result = new HashMap<>();
while (rowIterator.hasNext()) {
row = rowIterator.next();
cell = row.getCell(0);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
String orderCounts = cell.getStringCellValue().trim();
cell = row.getCell(1);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
String clientId = cell.getStringCellValue().trim();
cell = row.getCell(2);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
String dateStr = cell.getStringCellValue().trim();
if (result.containsKey(clientId)) {
result.get(clientId).put(dateStr, orderCounts);
} else {
LinkedHashMap<String, String> ele = new LinkedHashMap<>();
ele.put(dateStr, orderCounts);
result.put(clientId, ele);
}
}
Set<String> resultClients = new HashSet<>();
Date now = new Date();
for (Map.Entry<String, LinkedHashMap<String, String>> p : result.entrySet()) {
JSONObject tmpClient = clientMap.get(p.getKey());
if(tmpClient==null){
continue;
}
if(DateUtils.addMonths(tmpClient.getDate("create_time"), 7).compareTo(now)>-1){
continue;
}
for (Map.Entry<String, String> o : p.getValue().entrySet()) {
LinkedHashMap<String,String> resultEle = p.getValue();
int compareCount = 0;
for (int i = 1; i < 7; i++) {
compareCount+=1;
if(DateUtils.addMonths(DateUtils.parseDate(o.getKey(), "YYYY-MM"), 7).compareTo(now)>-1){
i=10;
continue;
}
Date compareDate = DateUtils.addMonths(DateUtils.parseDate(o.getKey(), "YYYY-MM"), i);
String compareKey = DateFormatUtils.format(compareDate,"YYYY-MM");
if(resultEle.containsKey(compareKey)){
i=10;
}
if(compareCount==6){
resultClients.add(p.getKey());
}
}
}
}
System.out.println("0---"+resultClients.size());
resultClients.forEach(p->{
System.out.println(p);
});
// OutputStream out = new FileOutputStream("/Users/wangning/Desktop/春节活动报名结果通知(包含BD名称).xlsx");
// workbook.write(out);
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void sendSimpleMessage() throws Exception {
String url = "https://api.mailgun.net/v3/dev.showcodes.com/messages?from=postmaster@mail.royalpay.com.au&to=164851225@qq.com,1029811920@qq.com&subject=啊是记录&text=暗杀苏&v:my-custom-data={\"key\":\"value\"}";
String asd = "王宁测试标题";
HttpRequestGenerator generator = new HttpRequestGenerator(url, RequestMethod.POST).addHeader("Authorization", getHeader());
HttpRequestResult res = null;
try {
res = generator.execute();
} catch (URISyntaxException e) {
e.printStackTrace();
}
System.out.println(res.getException());
System.out.println();
System.out.println();
try {
System.out.println(res.getResponseContentJSONObj().toJSONString());
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void sendSimeMessage() throws Exception {
String url = "https://api.mailgun.net/v3/dev.showcodes.com/events";
HttpRequestGenerator generator = new HttpRequestGenerator(url, RequestMethod.POST).addHeader("Authorization", getHeader());
generator.addQueryString("ascending", "yes");
generator.addQueryString("v:my-custom-data", "123456789");
generator.addQueryString("limit", "12");
System.out.println(String.valueOf(DateUtils.addDays(new Date(), 1)));
HttpRequestResult res = null;
try {
res = generator.execute();
} catch (URISyntaxException e) {
e.printStackTrace();
}
System.out.println(res.getException());
System.out.println();
System.out.println();
try {
System.out.println(res.getResponseContentJSONObj().toJSONString());
} catch (IOException e) {
e.printStackTrace();
}
}
private String getHeader() {
String auth = "api:key-96fa3b5866ace125b8ec5a9d27e19353";
byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("UTF-8")));
String authHeader = "Basic " + new String(encodedAuth);
return authHeader;
}
@Test
public void sendSimpleMessages() throws Exception {
SendMail sendMail = new SendMail();
sendMail.setFrom("info@mail.royalpay.com.au");
sendMail.setContent("<html><p>Hi</p ></html>");
List<String> list = new ArrayList<>();
list.add("testTag");
// sendMail.setTags(list);
Set<String> mailCCs = new HashSet<>();
mailCCs.add("asd1159111@163.com");
sendMail.setMailCcs(mailCCs);
Set<String> mailtos = new HashSet<>();
mailtos.add("eason.qian@royalpay.com.au");
sendMail.setMailTos(mailtos);
sendMail.setTitle("Final Test");
JSONObject result = mailGunClient.sendMail(sendMail);
System.out.println(result.toJSONString());
System.out.println(result.toJSONString());
System.out.println(result.toJSONString());
}
@Test
public void asd() {
JSONObject client = clientMapper.findClient(9);
JSONObject var = new JSONObject();
var.put("client_moniker", client.getString("client_moniker"));
var.put("short_name", client.getString("short_name"));
JSONObject result = mailGunClient.addListMember(client.getString("contact_email"), "merchants@mail.royalpay.com.au", client.getString("contact_person"),
"", var);
}
@Test
public void fd() {
List<String> asd12eq = new ArrayList<>();
asd12eq.add("9");
JSONObject asd = clientManager.getByEmail("164851225@qq.com", 1, 1, asd12eq);
JSONArray qwe = asd.getJSONArray("data");
System.out.println(asd.getJSONArray("data"));
System.out.println(qwe);
System.out.println(asd);
System.out.println(asd);
System.out.println(asd);
}
@Test
public void addMailUnsub() {
try {
XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File("/Users/wangning/Desktop/asd.xlsx")));
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.rowIterator();
Row row = null;
Cell cell = null;
while (rowIterator.hasNext()) {
row = rowIterator.next();
cell = row.getCell(1);
if (cell == null) {
continue;
}
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
CellStyle cellStyle = cell.getCellStyle();
if (cellStyle.getFillForegroundColor() == 0) {
continue;
}
String clientMonikers = cell.getStringCellValue().trim();
if (clientMonikers.contains("/")) {
String[] clientMonikerArr = clientMonikers.split("/");
for (String s : clientMonikerArr) {
String tmp = s.trim().toUpperCase();
if (tmp.length() > 4 || tmp.length() == 0) {
continue;
}
mailService.addUnsub(s.trim().toUpperCase());
}
} else {
String tmp = clientMonikers.trim().toUpperCase();
if (tmp.length() > 4 || tmp.length() == 0) {
continue;
}
mailService.addUnsub(clientMonikers.trim().toUpperCase());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void zxc() {
weekReporter.generateReport("2018-06-04", false);
}
@Test
public void royalpayIndustryTransform() {
String json = "[\n" + " {\n" + " \"children\": [\n" + " {\n" + " \"children\": [],\n" + " \"label\": \"机票\",\n"
+ " \"mccCode\": \"10001\"\n" + " },\n" + " {\n" + " \"children\": [],\n" + " \"label\": \"旅游行业\",\n"
+ " \"mccCode\": \"10002\"\n" + " },\n" + " {\n" + " \"children\": [],\n" + " \"label\": \"私人定制旅游\",\n"
+ " \"mccCode\": \"10003\"\n" + " },\n" + " {\n" + " \"children\": [],\n" + " \"label\": \"租车\",\n"
+ " \"mccCode\": \"10004\"\n" + " },\n" + " {\n" + " \"children\": [],\n" + " \"label\": \"巴士\",\n"
+ " \"mccCode\": \"10005\"\n" + " }\n" + " ],\n" + " \"label\": \"旅游出行\",\n" + " \"mccCode\": \"1\"\n" + " },\n" + " {\n"
+ " \"children\": [\n" + " {\n" + " \"children\": [],\n" + " \"label\": \"饭店\",\n" + " \"mccCode\": \"20001\"\n"
+ " },\n" + " {\n" + " \"children\": [],\n" + " \"label\": \"奶茶店\",\n" + " \"mccCode\": \"20002\"\n"
+ " },\n" + " {\n" + " \"children\": [],\n" + " \"label\": \"烧烤\",\n" + " \"mccCode\": \"20003\"\n"
+ " },\n" + " {\n" + " \"children\": [],\n" + " \"label\": \"火锅\",\n" + " \"mccCode\": \"20004\"\n"
+ " },\n" + " {\n" + " \"children\": [],\n" + " \"label\": \"Coffee\",\n" + " \"mccCode\": \"20005\"\n"
+ " },\n" + " {\n" + " \"children\": [],\n" + " \"label\": \"酒吧\",\n" + " \"mccCode\": \"20006\"\n" + " }\n"
+ " ],\n" + " \"label\": \"餐饮\",\n" + " \"mccCode\": \"2\"\n" + " },\n" + " {\n" + " \"children\": [\n" + " {\n"
+ " \"children\": [],\n" + " \"label\": \"培训类\",\n" + " \"mccCode\": \"30001\"\n" + " },\n" + " {\n"
+ " \"children\": [],\n" + " \"label\": \"移民留学\",\n" + " \"mccCode\": \"30002\"\n" + " },\n" + " {\n"
+ " \"children\": [],\n" + " \"label\": \"私人幼儿园\",\n" + " \"mccCode\": \"30003\"\n" + " }\n" + " ],\n"
+ " \"label\": \"教育\",\n" + " \"mccCode\": \"3\"\n" + " },\n" + " {\n" + " \"children\": [\n" + " {\n"
+ " \"children\": [],\n" + " \"label\": \"换汇\",\n" + " \"mccCode\": \"40001\"\n" + " },\n" + " {\n"
+ " \"children\": [],\n" + " \"label\": \"房产\",\n" + " \"mccCode\": \"40002\"\n" + " }\n" + " ],\n"
+ " \"label\": \"商务咨询\",\n" + " \"mccCode\": \"4\"\n" + " },\n" + " {\n" + " \"children\": [\n" + " {\n"
+ " \"children\": [],\n" + " \"label\": \"公众号服务商\",\n" + " \"mccCode\": \"50001\"\n" + " },\n" + " {\n"
+ " \"children\": [],\n" + " \"label\": \"各种媒体类宣传\",\n" + " \"mccCode\": \"50002\"\n" + " }\n" + " ],\n"
+ " \"label\": \"传媒\",\n" + " \"mccCode\": \"5\",\n"
+ " \"value\": \"{\\\"category\\\":\\\"SERVICE\\\",\\\"code\\\":\\\"7542\\\",\\\"description\\\":\\\"Car Washes\\\",\\\"parentCode\\\":\\\"S10\\\"}\"\n"
+ " },\n" + " {\n" + " \"children\": [\n" + " {\n" + " \"children\": [],\n" + " \"label\": \"美容院\",\n"
+ " \"mccCode\": \"60001\"\n" + " },\n" + " {\n" + " \"children\": [],\n" + " \"label\": \"医疗美容\",\n"
+ " \"mccCode\": \"60002\"\n" + " }\n" + " ],\n" + " \"label\": \"医美\",\n" + " \"mccCode\": \"6\"\n" + " },\n" + " {\n"
+ " \"children\": [\n" + " {\n" + " \"label\": \"超市\",\n" + " \"mccCode\": \"70001\"\n" + " },\n" + " {\n"
+ " \"children\": [],\n" + " \"label\": \"服装店\",\n" + " \"mccCode\": \"70002\"\n" + " },\n" + " {\n"
+ " \"children\": [],\n" + " \"label\": \"鞋店\",\n" + " \"mccCode\": \"70003\"\n" + " },\n" + " {\n"
+ " \"children\": [],\n" + " \"label\": \"珠宝店\",\n" + " \"mccCode\": \"70004\"\n" + " },{\n"
+ " \"children\": [],\n" + " \"label\": \"箱包\",\n" + " \"mccCode\": \"70005\"\n" + " }\n" + " ],\n"
+ " \"label\": \"零售\",\n" + " \"mccCode\": \"7\"\n" + " },\n" + " {\n" + " \"children\": [\n" + " {\n"
+ " \"children\": [],\n" + " \"label\": \"桌游吧\",\n" + " \"mccCode\": \"80001\"\n" + " },\n" + " {\n"
+ " \"children\": [],\n" + " \"label\": \"演唱会\",\n" + " \"mccCode\": \"80002\"\n" + " },\n" + " {\n"
+ " \"children\": [],\n" + " \"label\": \"马术训练\",\n" + " \"mccCode\": \"80003\"\n" + " },\n" + " {\n"
+ " \"children\": [],\n" + " \"label\": \"瑜伽\",\n" + " \"mccCode\": \"80004\"\n" + " },\n" + " {\n"
+ " \"children\": [],\n" + " \"label\": \"健身\",\n" + " \"mccCode\": \"80005\"\n" + " },\n" + " {\n"
+ " \"children\": [],\n" + " \"label\": \"社团\",\n" + " \"mccCode\": \"80006\"\n" + " },\n" + " {\n"
+ " \"children\": [],\n" + " \"label\": \"网吧\",\n" + " \"mccCode\": \"80007\"\n" + " },\n" + " {\n"
+ " \"children\": [],\n" + " \"label\": \"KTV\",\n" + " \"mccCode\": \"80008\"\n" + " },\n" + " {\n"
+ " \"children\": [],\n" + " \"label\": \"电影\",\n" + " \"mccCode\": \"80009\"\n" + " }\n" + " ],\n"
+ " \"label\": \"休闲娱乐\",\n" + " \"mccCode\": \"8\"\n" + " },\n" + " {\n" + " \"children\": [\n" + " {\n"
+ " \"children\": [],\n" + " \"label\": \"摄影\",\n" + " \"mccCode\": \"90001\"\n" + " },\n" + " {\n"
+ " \"children\": [],\n" + " \"label\": \"massage\",\n" + " \"mccCode\": \"90002\"\n" + " },\n" + " {\n"
+ " \"children\": [],\n" + " \"label\": \"通讯运营商\",\n" + " \"mccCode\": \"90003\"\n" + " },\n" + " {\n"
+ " \"children\": [],\n" + " \"label\": \"车行\",\n" + " \"mccCode\": \"90004\"\n" + " },\n" + " {\n"
+ " \"children:\":[],\n" + " \"label\":\"软件服务\",\n" + " \"mccCode\":\"90005\"\n" + " }\n" + " ],\n"
+ " \"label\": \"其他服务类\",\n" + " \"mccCode\": \"9\"\n" + " },\n" + " {\n" + " \"children\": [\n" + " {\n"
+ " \"children\": [],\n" + " \"label\": \"Hotel\",\n" + " \"mccCode\": \"100001\"\n" + " },\n" + " {\n"
+ " \"children\": [],\n" + " \"label\": \"Motel\",\n" + " \"mccCode\": \"100002\"\n" + " }\n" + " ],\n"
+ " \"label\": \"酒店\",\n" + " \"mccCode\": \"10\"\n" + " },\n" + " {\n" + " \"children\": [\n" + " {\n"
+ " \"children\": [],\n" + " \"label\": \"代购\",\n" + " \"mccCode\": \"110001\"\n" + " },\n" + " {\n"
+ " \"children\": [],\n" + " \"label\": \"物流(大宗出口贸易)\",\n" + " \"mccCode\": \"110002\"\n" + " },\n" + " {\n"
+ " \"children\": [],\n" + " \"label\": \"红酒出口\",\n" + " \"mccCode\": \"110003\"\n" + " },\n" + " {\n"
+ " \"children\": [],\n" + " \"label\": \"综合电商\",\n" + " \"mccCode\": \"110004\"\n" + " }\n" + " ],\n"
+ " \"label\": \"出口贸易\",\n" + " \"mccCode\": \"11\"\n" + " },\n" + " {\n" + " \"children\": [\n" + " {\n"
+ " \"children\": [],\n" + " \"label\": \"建材\",\n" + " \"mccCode\": \"120001\"\n" + " },\n" + " {\n"
+ " \"children\": [],\n" + " \"label\": \"家居\",\n" + " \"mccCode\": \"120002\"\n" + " }\n" + " ],\n"
+ " \"label\": \"家居建材\",\n" + " \"mccCode\": \"12\"\n" + " }\n" + "]";
JSONArray jsonArray = JSONObject.parseArray(json);
try {
XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File("/Users/wangning/Desktop/asd.xlsx")));
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.rowIterator();
Row row = null;
Cell cell = null;
while (rowIterator.hasNext()) {
row = rowIterator.next();
cell = row.getCell(2);
if (cell == null) {
continue;
}
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
String industryChinese = recursionIndustry(jsonArray, cell.getStringCellValue());
cell.setCellValue(industryChinese);
}
OutputStream out = new FileOutputStream("/Users/wangning/Desktop/qwe.xlsx");
workbook.write(out);
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public String recursionIndustry(JSONArray jsonArray, String mccCode) {
String result = "";
for (Object o : jsonArray) {
if (StringUtils.isNotEmpty(result)) {
break;
}
JSONObject tmp = (JSONObject) o;
if (tmp.getString("mccCode").equals(mccCode)) {
result = tmp.getString("label");
} else {
if (tmp.getJSONArray("children") != null) {
result = recursionIndustry(tmp.getJSONArray("children"), mccCode);
} else {
result = "";
}
}
}
return result;
}
@Test
public void zxcs(){
cityPartnerPrizeService.generateSenior("2018-02");
}
}

@ -1,25 +1,39 @@
package au.com.royalpay.payment.manage.citypartner.core.impls; package au.com.royalpay.payment.manage.citypartner.core.impls;
import au.com.royalpay.payment.manage.citypartner.core.CityPartnerPrizeService; import au.com.royalpay.payment.manage.citypartner.core.CityPartnerPrizeService;
import au.com.royalpay.payment.tools.exceptions.ServerErrorException;
import cn.yixblog.platform.http.HttpRequestGenerator;
import cn.yixblog.platform.http.HttpRequestResult;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles; import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.*;
import static au.com.royalpay.payment.tools.codec.RSACrypt.loadPrivateKey;
/** /**
* Created by wangning on 09/01/2018. * Created by wangning on 09/01/2018.
*/ */
@SpringBootTest @SpringBootTest
@ActiveProfiles({"local","alipay","wechat","jd","bestpay"})
@RunWith(SpringRunner.class)
public class CityPartnerPrizeServiceImplTest { public class CityPartnerPrizeServiceImplTest {
static String PRIKEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCdIiy3fFUrZx4X0aIU37PGzViqG03yRDprSk2tqhORnAiZL3sLNFsjmy2FR4+84bksp2VxIc+rMot+4iFIAmpK50t6qj2Fz7sOO5DMSN0pRN9flIqQ1RFKYnIQN+BymfJ9bXbMN2aN+sbfZzZRTAZPtJuES9JIrmUDi4NwNeqBSjhflUqlyYx3ejMx2CrxHAS+35W5fAK88e//9SQiMdKHzNPFl4vXtCMqTY7Mk7febLfsG0aaRVMM/QOeT57sszB3Wib3wUFi9xGsqdqLi0skAWc4QmOGOoue7uvieghFWZXETfFN/K3wSz5TzVS55ma2u3KOkn8/M4E7J96RHzAPAgMBAAECggEAet+ueA0RzM7mCVo0lH4Z5uvM2bhgS4Ju7Fc+Rv8oLkUFtEQcw7Y9TqqZ/g7np5wbYX/FI6J88jKkQqQxwk2hMNGNhG57jZfTfl217QlNaGgjBGrzsC3tR22UJHqNWRBpPwvKSgdIet4PhcMABrKcfNeOhPWFirBU7WC7d5OxvUdA3oCnZXZ7nGxgyX06actjb3GhIUybi4DJosCY3NkBsUXWLh45Kmm8IfJv29cd+VrIBn5i1+mMd6hECmiN03ToH9dc3o1aS4YGJirvkf1q1oiJJMT7exacuZiTrRfUh+NIemm8oaBYJj9PMcy5PEtS/ZyJe7jzDEnbV71i5dnkAQKBgQDhXej3o3KyvP9h/nwH/gifK/Urai0u/SB6CScb8c0xzHoQhomjNaaHHKX82j8zDYMvg7yNWHEo5WdCEcenvjO4OWkbhL9brBJnpN5QyfPtjijUh/8PFNKu/NP0PISkFjuAOp+LVgMRgrfQL/wu1/zp6jgsAXckauUIBNITZPTWrwKBgQCyffLy1Cc1tSovzXchty7TLU49IzNZQ3keMEy8MWw6YFS5PGUSEixtjvsAuzoYMg6w7F/LxK8jMfOcDPza1AJUQIByXPoZs4jm31j6EPjPYP+ocQ04Ji+OOcbR5TOlFamNMnjQNlTqpEmNYpQcKp8AOyGm0dSMHe7YUKqzaymUoQKBgQDNQ4aL/s/aIjAM5ge8E9FwgE4GY+eRc7Wf0TRQzHSTVeUbph44jAYH67z3RyTm7/i7TyZuKs6ua/sXfzA1BRUARzIHgWn1Kg19Xvmp5bcJeECSCufxqYqXHOpD+tboyOMa0Mo903JqAYA/22S6mbjeqJjO4+rLPZ0rJ5DbX0ltOwKBgA+3rYwaiHVfRZ69/g6W/eWUqL4TenMS0PiKkkdEJt6hGvTQz6methDTtWCkHAKDbe3ActMTt8RmoqgMMLvoTWgz4duwOknHGHgUFNa4ZeCFDx47Dknyet+QUOSsxTZ1SN/pIOBc2G9tFhkAJECytBumGVmCQrAv9pdPyyhPeHLhAoGATvtEmi3oYPQtoy8qDEhI8wCXrrKIZh2a7ahRjt8B056HZ26EjalKg2Yz+5WTRbS6Bgr8ZN+12wRl7CbjWyr+loOEsMTjAuJoxGDo9bm936IqvmwVlEdLkOoMoFnJY6OFiVqWmLIXHr56+z2ShryZVPc59gdLxNRA+ZJMF5kY27s=";
private final String IMG_AGGREGATE_FILE = "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=95272786,3986826432&fm=26&gp=0.jpg";
@Resource @Resource
private CityPartnerPrizeService cityPartnerPrizeService; private CityPartnerPrizeService cityPartnerPrizeService;
@Test @Test
public void generateAgent() throws Exception { public void generateAgent() throws Exception {
} }
@ -29,4 +43,166 @@ public class CityPartnerPrizeServiceImplTest {
cityPartnerPrizeService.generate("2017-06"); cityPartnerPrizeService.generate("2017-06");
} }
@Test
public void applicationMerchant() throws Exception {
JSONObject companyInfo = new JSONObject() {{
put("company_name", "gateway partner test1");
put("short_name", "gateway partner test1");
put("store_name", "gateway partner test1");
put("business_name", "gateway partner test1");
put("business_structure", "Company");
put("acn", "123456789");
put("company_phone", "123456789");
put("logo_url", "http://n.sinaimg.cn/sinacn15/435/w640h595/20181010/403e-hkrzvkw4936423.jpg");
}};
JSONObject contactInfo = new JSONObject() {{
put("contact_person", "person1");
put("contact_phone", "1231231");
put("contact_email", "1qq@qq.com");
put("contact_job", "Direct");
put("address", "测试住址1");
put("suburb", "测试区1");
put("postcode", "测试code1");
put("state", "测试state1");
put("country", "AU");
put("registered_address", "测试住址2");
put("registered_suburb", "测试区2");
put("registered_postcode", "测试code2");
put("registered_state", "测试state2");
put("timezone", "Australia/West");
}};
JSONObject ClientLegalConfig = new JSONObject() {{
put("legal_representative_person", "person2");
put("legal_representative_phone", "1231231");
put("legal_representative_email", "1qq@qq.com");
put("legal_representative_job", "Direct");
}};
JSONObject clientPayConfig = new JSONObject() {{
put("client_pay_type", "2");
put("client_pay_desc", "201");
put("royalpay_industry", "10001");
put("wechat_industry", "339");
put("alipay_industry", "4511");
put("company_photo", "https://c-ssl.duitang.com/uploads/item/201812/10/20181210170153_xPUVk.jpeg");
put("store_photo", "https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=3199241964,979639112&fm=26&gp=0.jpg");
put("company_website", "https://11.com");
}};
JSONObject settleConfig = new JSONObject() {{
put("swift_code", "2");
put("bsb_no", "201");
put("bank", "10001");
put("city", "339");
put("address", "4511");
put("system", "sytem");
put("postcode", "postcode");
put("state", "state");
put("branch", "branch");
put("account_no", "21213131");
put("account_name", "dasdasdasd");
put("clean_days", "2");
put("wechat_rate", "1.2");
put("alipay_rate", "1.2");
put("alipay_online_rate", "1.2");
put("transaction_fee", "0");
put("active_time", "2020-02-04 00:00:00");
put("expire_time", "2021-02-06 00:00:00");
}};
JSONObject complianceInfo = new JSONObject() {{
put("id_type", "pastport");
put("id_title", "Direct");
put("id_title_description", "test");
put("bank_statement", "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=820350352,1683018569&fm=26&gp=0.jpg");
put("certificate_of_registration", "http://i2.w.yun.hjfile.cn/doc/201404/00662ef619754b749200eecdf3671c3a.jpg");
put("id_file", "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=2284543896,2456565772&fm=26&gp=0.jpg");
put("utility_bill", "http://i0.sinaimg.cn/ent/v/2009-08-22/U2389P28T3D2664490F346DT20090822015510.JPG");
}};
JSONObject params = new JSONObject() {{
put("apply_id", "orgapply1");
put("notify_url", "http://127.0.0.1:9002/sys/partners/7CMV/qrcode");
put("company_info", companyInfo);
put("contact_info", contactInfo);
put("legal_info", ClientLegalConfig);
put("pay_info", clientPayConfig);
put("settle_info", settleConfig);
put("compliance_file_info", complianceInfo);
}};
String originUrl = "http://127.0.0.1:5000/api/v1.0/gateway/partners/AXLCEXDDMB/merchant/application";
// String originUrl = "http://127.0.0.1:5000/api/v1.0/gateway/partners/2121/merchant/application";
String url = addSignUrl(originUrl, params, PRIKEY);
HttpRequestGenerator gen = new HttpRequestGenerator(url, RequestMethod.POST);
gen.setJSONEntity(params);
HttpRequestResult result = gen.execute();
if (result.isSuccess()) {
System.out.println(result.getResponseContentJSONObj().toJSONString());
}else {
System.out.println(result.getResponseContentString());
}
}
@Test
public void queryMerchantStatus() throws Exception{
String partnerCode = "PBAR";
String originUrl = "http://127.0.0.1:5000/api/v1.0/gateway/partners/AXLCEXDDMB/merchant/" + partnerCode + "/status";
String url = addSignUrl(originUrl, null, PRIKEY);
HttpRequestGenerator gen = new HttpRequestGenerator(url, RequestMethod.GET);
HttpRequestResult result = gen.execute();
if (result.isSuccess()) {
System.out.println(result.getResponseContentJSONObj().toJSONString());
}else {
System.out.println(result.getResponseContentString());
}
}
@Test
public void updateFile() throws Exception{
String originUrl = "http://127.0.0.1:5000/api/v1.0/gateway/partners/AXLCEXDDMB/attachment/files";
String url = addSignUrl(originUrl, null, PRIKEY);
File file = new File("/Users/luoyang/Downloads/121.jpg");
InputStream stream = new FileInputStream(file);
HttpRequestGenerator gen = new HttpRequestGenerator(url, RequestMethod.POST);
gen.setTimeout(10000);
gen.initFileEntity().attachFile("file", "121.jpg", stream);
HttpRequestResult result = gen.execute();
if (result.isSuccess()) {
System.out.println(result.getResponseContentJSONObj().toJSONString());
}else {
System.out.println(result.getResponseContentString());
}
}
private String sign(byte[] source, String privateKey) {
try {
PrivateKey priKey = loadPrivateKey(new ByteArrayInputStream(privateKey.getBytes(StandardCharsets.UTF_8)));
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(priKey);
signature.update(source);
byte[] signed = signature.sign();
return Base64.encodeBase64URLSafeString(signed);
} catch (NoSuchAlgorithmException | SignatureException | InvalidKeyException e) {
//shall never happen
throw new ServerErrorException(e);
}
}
private String addSignUrl(String originUrl, JSONObject params, String priKey) {
if (params == null) {
params = new JSONObject();
}
String nonceStr = RandomStringUtils.random(15, true, true);
params.put("url", originUrl);
params.put("sign_type", "RSA2");
params.put("nonce_str", nonceStr);
String signStr = sign(JSONObject.toJSONBytes(params, SerializerFeature.MapSortField), priKey);
originUrl += ("?nonce_str=" + nonceStr);
originUrl += "&sign_type=RSA2";
originUrl += "&sign=" + signStr;
return originUrl;
}
} }

@ -6,6 +6,7 @@ import au.com.royalpay.payment.tools.codec.AESCrypt;
import au.com.royalpay.payment.tools.encryptalgorithm.SignUtils; import au.com.royalpay.payment.tools.encryptalgorithm.SignUtils;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.github.stuxuhai.jpinyin.PinyinException; import com.github.stuxuhai.jpinyin.PinyinException;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.net.util.Base64; import org.apache.commons.net.util.Base64;
import org.junit.Test; import org.junit.Test;
@ -62,4 +63,14 @@ public class JPinYinTest {
System.err.println(SignUtils.decData(aesData, rsa1_pri)); System.err.println(SignUtils.decData(aesData, rsa1_pri));
} }
@Test
public void testhash(){
String hash = DigestUtils.sha256Hex("customer&xxnpdBRwd4sIaCCI&1575949279241&/api/sso/manager_sign_in").toLowerCase();
String hash2 = DigestUtils.sha256Hex("customer&xxnpdBRwd4sIaCCI&1575950092568&/api/sso/manager_sign_in&119.28.3.196").toLowerCase();
System.err.println(hash);
System.err.println(hash2);
}
} }

Loading…
Cancel
Save