diff --git a/pom.xml b/pom.xml index 68ddf33ba..cbacd19fb 100644 --- a/pom.xml +++ b/pom.xml @@ -5,11 +5,11 @@ au.com.royalpay.payment payment-parent - 1.1.7 + 1.1.12 4.0.0 manage - 1.3.24 + 1.3.25 UTF-8 1.4.0 diff --git a/src/document/cn/apidoc.json b/src/document/cn/apidoc.json index 3bfca5fe1..567b6e3d3 100644 --- a/src/document/cn/apidoc.json +++ b/src/document/cn/apidoc.json @@ -39,7 +39,11 @@ "ListOrder", "ListTransaction", "SettleLog", - "PayNotice" + "PayNotice", + "update_file", + "application_merchant", + "query_merchant", + "merchant_notice" ], "template":{ "forceLanguage":"zh_cn" diff --git a/src/document/cn/apis.js b/src/document/cn/apis.js index bed7a627a..6d2d28a08 100644 --- a/src/document/cn/apis.js +++ b/src/document/cn/apis.js @@ -17,9 +17,30 @@ /** * @apiDefine JSON JSON字段 */ +/** + * @apiDefine BINARY 文件数据流 + */ /** * @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 错误码 */ @@ -36,6 +57,13 @@ * @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 获取当前汇率 * @apiName GetExchange diff --git a/src/document/en/apidoc.json b/src/document/en/apidoc.json index b8c3e6bc4..374c76566 100644 --- a/src/document/en/apidoc.json +++ b/src/document/en/apidoc.json @@ -39,7 +39,11 @@ "ListOrder", "ListTransaction", "SettleLog", - "PayNotice" + "PayNotice", + "update_file", + "application_merchant", + "query_merchant", + "merchant_notice" ], "template":{ "forceLanguage":"en" diff --git a/src/document/en/apis.js b/src/document/en/apis.js index 3c3fe44d7..ed523570b 100644 --- a/src/document/en/apis.js +++ b/src/document/en/apis.js @@ -14,9 +14,30 @@ /** * @apiDefine QueryParam Query Params */ +/** + * @apiDefine BINARY File data stream + */ /** * @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 */ @@ -34,7 +55,13 @@ * @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) 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 * */ /** diff --git a/src/main/java/au/com/royalpay/payment/manage/appclient/core/impls/RetailRSvcServiceImpl.java b/src/main/java/au/com/royalpay/payment/manage/appclient/core/impls/RetailRSvcServiceImpl.java index f3b570abb..bc23206c4 100644 --- a/src/main/java/au/com/royalpay/payment/manage/appclient/core/impls/RetailRSvcServiceImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/appclient/core/impls/RetailRSvcServiceImpl.java @@ -106,10 +106,8 @@ public class RetailRSvcServiceImpl implements RetailRSvcService { serviceApply.put("is_valid", 1); serviceApply.put("create_time", new Date()); clientServicesApplyMapper.save(serviceApply); - result.put("result_code", "SUCCESS"); result.put("result_status", "PROCESSING"); } catch (Exception e) { - result.put("result_code", "SUCCESS"); result.put("result_status", "SYSTEMERROR"); result.put("result_msg", e.getMessage()); } diff --git a/src/main/java/au/com/royalpay/payment/manage/application/core/impls/SimpleClientApplyServiceImpl.java b/src/main/java/au/com/royalpay/payment/manage/application/core/impls/SimpleClientApplyServiceImpl.java index 3cc6c9bd0..5696a9815 100644 --- a/src/main/java/au/com/royalpay/payment/manage/application/core/impls/SimpleClientApplyServiceImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/application/core/impls/SimpleClientApplyServiceImpl.java @@ -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.locale.LocaleSupport; import au.com.royalpay.payment.tools.utils.PasswordUtils; - import au.com.royalpay.payment.tools.utils.PdfUtils; 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.JSONObject; - import com.alibaba.fastjson.parser.Feature; import org.apache.commons.codec.binary.Base64; 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.multipart.MultipartFile; 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.io.*; -import java.math.BigDecimal; import java.net.URISyntaxException; import java.net.URLDecoder; import java.util.*; @@ -57,15 +61,6 @@ import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; 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 public class SimpleClientApplyServiceImpl implements SimpleClientApplyService { @@ -828,7 +823,7 @@ public class SimpleClientApplyServiceImpl implements SimpleClientApplyService { throw new NotFoundException("BSB Number Not Found"); } } - } catch (URISyntaxException | IOException e) { + } catch (IOException e) { throw new ServerErrorException(); } return banInfo; diff --git a/src/main/java/au/com/royalpay/payment/manage/apps/events/listeners/AfterPaymentFinishListener.java b/src/main/java/au/com/royalpay/payment/manage/apps/events/listeners/AfterPaymentFinishListener.java index b52e8387b..512641468 100644 --- a/src/main/java/au/com/royalpay/payment/manage/apps/events/listeners/AfterPaymentFinishListener.java +++ b/src/main/java/au/com/royalpay/payment/manage/apps/events/listeners/AfterPaymentFinishListener.java @@ -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.manage.customers.core.CustomerPaymentInfoService; import au.com.royalpay.payment.manage.mappers.system.SysCustomerPaymentInfoMapper; - import au.com.royalpay.payment.manage.merchants.core.ClientManager; import com.alibaba.fastjson.JSONObject; - import org.apache.commons.lang3.StringUtils; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Service; diff --git a/src/main/java/au/com/royalpay/payment/manage/datav/core/Impl/DatavServiceImpl.java b/src/main/java/au/com/royalpay/payment/manage/datav/core/Impl/DatavServiceImpl.java index ae4015685..e3404217e 100644 --- a/src/main/java/au/com/royalpay/payment/manage/datav/core/Impl/DatavServiceImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/datav/core/Impl/DatavServiceImpl.java @@ -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.mappers.payment.OrderMapper; 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.HttpRequestResult; import com.alibaba.fastjson.JSONObject; -import org.apache.commons.lang3.time.DateUtils; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.RequestMethod; import javax.annotation.Resource; import java.io.IOException; -import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -104,7 +101,7 @@ public class DatavServiceImpl implements DatavService { obj.put("moniker_longitude", customer.getString("longitude")); obj.put("moniker_latitude", customer.getString("latitude")); } - } catch (IOException | URISyntaxException e) { + } catch (IOException e) { e.printStackTrace(); } } diff --git a/src/main/java/au/com/royalpay/payment/manage/dev/web/TestController.java b/src/main/java/au/com/royalpay/payment/manage/dev/web/TestController.java index d5bd11c71..2abc1e604 100644 --- a/src/main/java/au/com/royalpay/payment/manage/dev/web/TestController.java +++ b/src/main/java/au/com/royalpay/payment/manage/dev/web/TestController.java @@ -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.OrderNotExistsException; 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.PlatformClearService; 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.merchants.core.ClientManager; 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.tradelog.core.TradeLogService; 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.SysConfigManager; 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.merchants.core.MerchantInfoProvider; 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.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; -import au.com.royalpay.payment.tools.exceptions.NotFoundException; import javax.annotation.Resource; import javax.servlet.ServletOutputStream; diff --git a/src/main/java/au/com/royalpay/payment/manage/gateway/advice/Gtw2Ctrl.java b/src/main/java/au/com/royalpay/payment/manage/gateway/advice/Gtw2Ctrl.java new file mode 100644 index 000000000..042e1871f --- /dev/null +++ b/src/main/java/au/com/royalpay/payment/manage/gateway/advice/Gtw2Ctrl.java @@ -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 { +} diff --git a/src/main/java/au/com/royalpay/payment/manage/gateway/advice/Gtw2SignAspect.java b/src/main/java/au/com/royalpay/payment/manage/gateway/advice/Gtw2SignAspect.java new file mode 100644 index 000000000..be5a5ece8 --- /dev/null +++ b/src/main/java/au/com/royalpay/payment/manage/gateway/advice/Gtw2SignAspect.java @@ -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 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 pathVariables = (Map) 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); + } + } +} diff --git a/src/main/java/au/com/royalpay/payment/manage/gateway/beans/ClientCompanyConfig.java b/src/main/java/au/com/royalpay/payment/manage/gateway/beans/ClientCompanyConfig.java new file mode 100644 index 000000000..5c737c49a --- /dev/null +++ b/src/main/java/au/com/royalpay/payment/manage/gateway/beans/ClientCompanyConfig.java @@ -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); + } +} diff --git a/src/main/java/au/com/royalpay/payment/manage/gateway/beans/ClientComplianceFileConfig.java b/src/main/java/au/com/royalpay/payment/manage/gateway/beans/ClientComplianceFileConfig.java new file mode 100644 index 000000000..fc1fd9c6f --- /dev/null +++ b/src/main/java/au/com/royalpay/payment/manage/gateway/beans/ClientComplianceFileConfig.java @@ -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"); + } + } + } +} diff --git a/src/main/java/au/com/royalpay/payment/manage/gateway/beans/ClientContactConfig.java b/src/main/java/au/com/royalpay/payment/manage/gateway/beans/ClientContactConfig.java new file mode 100644 index 000000000..1fcc450e9 --- /dev/null +++ b/src/main/java/au/com/royalpay/payment/manage/gateway/beans/ClientContactConfig.java @@ -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; + } +} diff --git a/src/main/java/au/com/royalpay/payment/manage/gateway/beans/ClientLegalConfig.java b/src/main/java/au/com/royalpay/payment/manage/gateway/beans/ClientLegalConfig.java new file mode 100644 index 000000000..ede6d5920 --- /dev/null +++ b/src/main/java/au/com/royalpay/payment/manage/gateway/beans/ClientLegalConfig.java @@ -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; + } + +} diff --git a/src/main/java/au/com/royalpay/payment/manage/gateway/beans/ClientPayConfig.java b/src/main/java/au/com/royalpay/payment/manage/gateway/beans/ClientPayConfig.java new file mode 100644 index 000000000..5ce71d06a --- /dev/null +++ b/src/main/java/au/com/royalpay/payment/manage/gateway/beans/ClientPayConfig.java @@ -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; + } +} diff --git a/src/main/java/au/com/royalpay/payment/manage/gateway/beans/ClientRegisterInfo.java b/src/main/java/au/com/royalpay/payment/manage/gateway/beans/ClientRegisterInfo.java new file mode 100644 index 000000000..09900b8b5 --- /dev/null +++ b/src/main/java/au/com/royalpay/payment/manage/gateway/beans/ClientRegisterInfo.java @@ -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); + } +} diff --git a/src/main/java/au/com/royalpay/payment/manage/gateway/beans/ClientSettleConfig.java b/src/main/java/au/com/royalpay/payment/manage/gateway/beans/ClientSettleConfig.java new file mode 100644 index 000000000..86caa0b20 --- /dev/null +++ b/src/main/java/au/com/royalpay/payment/manage/gateway/beans/ClientSettleConfig.java @@ -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; + } +} diff --git a/src/main/java/au/com/royalpay/payment/manage/gateway/core/GatewayMerchantApply.java b/src/main/java/au/com/royalpay/payment/manage/gateway/core/GatewayMerchantApply.java new file mode 100644 index 000000000..4d13cc221 --- /dev/null +++ b/src/main/java/au/com/royalpay/payment/manage/gateway/core/GatewayMerchantApply.java @@ -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); +} diff --git a/src/main/java/au/com/royalpay/payment/manage/gateway/core/impls/GatewayMerchantApplyImpl.java b/src/main/java/au/com/royalpay/payment/manage/gateway/core/impls/GatewayMerchantApplyImpl.java new file mode 100644 index 000000000..709eeae58 --- /dev/null +++ b/src/main/java/au/com/royalpay/payment/manage/gateway/core/impls/GatewayMerchantApplyImpl.java @@ -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); + } + } + +} diff --git a/src/main/java/au/com/royalpay/payment/manage/gateway/web/GtwPayController.java b/src/main/java/au/com/royalpay/payment/manage/gateway/web/GtwPayController.java new file mode 100644 index 000000000..bb2a47cc6 --- /dev/null +++ b/src/main/java/au/com/royalpay/payment/manage/gateway/web/GtwPayController.java @@ -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; + } + +} diff --git a/src/main/java/au/com/royalpay/payment/manage/logview/core/impl/OperationLogServiceImpl.java b/src/main/java/au/com/royalpay/payment/manage/logview/core/impl/OperationLogServiceImpl.java index 0528e18c8..0e29be584 100644 --- a/src/main/java/au/com/royalpay/payment/manage/logview/core/impl/OperationLogServiceImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/logview/core/impl/OperationLogServiceImpl.java @@ -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.merchants.beans.mongo.ClientConfigLog; import au.com.royalpay.payment.manage.merchants.core.ClientManager; - import com.alibaba.fastjson.JSONObject; import com.github.miemiedev.mybatis.paginator.domain.PageBounds; import com.github.miemiedev.mybatis.paginator.domain.Paginator; - import org.apache.commons.lang3.StringUtils; import org.springframework.data.domain.PageRequest; 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.stereotype.Service; -import java.util.List; - import javax.annotation.Resource; +import java.util.List; /** * @author kira @@ -35,16 +32,16 @@ public class OperationLogServiceImpl implements OperationLogService { public JSONObject query(JSONObject params, PageBounds pageBounds) { if (StringUtils.isNotEmpty(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")); } } 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) { 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"))); List clientConfigLogList = mongoTemplate.find(query, ClientConfigLog.class); return buildPageListResult(clientConfigLogList, diff --git a/src/main/java/au/com/royalpay/payment/manage/management/clearing/core/impl/CleanServiceImpl.java b/src/main/java/au/com/royalpay/payment/manage/management/clearing/core/impl/CleanServiceImpl.java index 7e65da9dd..7f1cb41ec 100644 --- a/src/main/java/au/com/royalpay/payment/manage/management/clearing/core/impl/CleanServiceImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/management/clearing/core/impl/CleanServiceImpl.java @@ -36,6 +36,7 @@ import au.com.royalpay.payment.tools.utils.PageListUtils; import au.com.royalpay.payment.tools.utils.TimeZoneUtils; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.JSONObject; import com.github.miemiedev.mybatis.paginator.domain.Order; import com.github.miemiedev.mybatis.paginator.domain.PageBounds; @@ -102,6 +103,8 @@ public class CleanServiceImpl implements CleanService, ManagerTodoNoticeProvider @Resource private TaskManualSettleMapper taskManualSettleMapper; @Resource + private PreSettleTaskMapper preSettleTaskMapper; + @Resource private ValidationLogMapper validationLogMapper; @Resource 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"; zos.putNextEntry(new ZipEntry(filename)); List details = clearingDetailMapper.listReportsOfSettlement(log.getIntValue("clearing_id")); + details = mergeBatchSettleClients(details); byte[] csv = generateSettleCSVFile(dt, details); IOUtils.write(csv, zos); } @@ -367,6 +371,7 @@ public class CleanServiceImpl implements CleanService, ManagerTodoNoticeProvider logger.info("using newest version test"); for (JSONObject log : logs) { List details = clearingDetailMapper.listReportsOfSettlement(log.getIntValue("clearing_id")); + details = mergeBatchSettleClients(details); exportAllBankXlsFiles(zos, details, log.getDate("operate_time")); } zos.flush(); @@ -398,7 +403,9 @@ public class CleanServiceImpl implements CleanService, ManagerTodoNoticeProvider String filename = "Merchant_Settlement_Info_" + DateFormatUtils.format(dt, "yyyyMMdd") + "_" + fileIndex + ".xlsx"; JSONObject file = new JSONObject(); file.put("name", filename); - file.put("byteArr", generateSettleXlsxFile(dt, clearingDetailMapper.listReportsOfSettlement(log.getIntValue("clearing_id")), bank)); + List details = clearingDetailMapper.listReportsOfSettlement(log.getIntValue("clearing_id")); + details = mergeBatchSettleClients(details); + file.put("byteArr", generateSettleXlsxFile(dt, details, bank)); result.add(file); fileIndex++; } @@ -407,7 +414,9 @@ public class CleanServiceImpl implements CleanService, ManagerTodoNoticeProvider String filename = "Merchant_Settlement_Info_" + DateFormatUtils.format(dt, "yyyyMMdd") + ".xlsx"; JSONObject file = new JSONObject(); file.put("name", filename); - file.put("byteArr", generateSettleXlsxFile(dt, clearingDetailMapper.listReportsOfSettlement(log.getIntValue("clearing_id")), bank)); + List details = clearingDetailMapper.listReportsOfSettlement(log.getIntValue("clearing_id")); + details = mergeBatchSettleClients(details); + file.put("byteArr", generateSettleXlsxFile(dt, details, bank)); result.add(file); } } @@ -415,6 +424,67 @@ public class CleanServiceImpl implements CleanService, ManagerTodoNoticeProvider return result; } + private List mergeBatchSettleClients(List details) { + Map> sameBankDetails = details.stream() + .filter(this::detailEnabledMergeSettle) + .collect(Collectors.groupingBy(this::detailGroupingId)); + List mergedSettleDetails = sameBankDetails.values().stream() + .map(this::mergeDetailGroup).collect(Collectors.toList()); + List 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 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 public List getAba(Date dt, String bank) { List logs = clearingLogMapper.findByDate(dt); @@ -425,6 +495,7 @@ public class CleanServiceImpl implements CleanService, ManagerTodoNoticeProvider List files = new ArrayList<>(); for (JSONObject log : logs) { List details = clearingDetailMapper.listReportsOfSettlement(log.getIntValue("clearing_id")); + details = mergeBatchSettleClients(details); files.addAll(generateSettleAbaFiles(dt, details, log.getDate("operate_time"))); } 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(1, Cell.CELL_TYPE_STRING).setCellValue(settle.getString("account_no")); 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(); wb.write(bos); @@ -464,6 +535,7 @@ public class CleanServiceImpl implements CleanService, ManagerTodoNoticeProvider for (JSONObject log : logs) { List details = clearingDetailMapper.listReportsOfSettlement(log.getIntValue("clearing_id")); + details = mergeBatchSettleClients(details); files.addAll(generateSettleAbaFiles(dt, details, log.getDate("operate_time"))); } OutputStream ous = resp.getOutputStream(); @@ -500,6 +572,7 @@ public class CleanServiceImpl implements CleanService, ManagerTodoNoticeProvider throw new NotFoundException("Clearing batch " + batchId + " not found"); } List details = clearingDetailMapper.listReportsOfSettlement(clearingId); + details = mergeBatchSettleClients(details); Date settleDate = clearing.getDate("settle_date"); Date opTime = clearing.getDate("operate_time"); 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"))); 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"); if (timezone_client != null) { @@ -838,7 +911,7 @@ public class CleanServiceImpl implements CleanService, ManagerTodoNoticeProvider int rowNum = 0; Row row = sheet.createRow(rowNum); 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)"}; for (int i = 0; i < title.length; 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()); cell = row.createCell(6, Cell.CELL_TYPE_STRING); 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")); cell = row.createCell(8, Cell.CELL_TYPE_STRING); cell.setCellValue(settle.getBigDecimal("display_amount") == null ? "" - : "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()); - cell.setCellStyle(!"Credit".equals(settle.getString("transaction_type"))?analysisStyle2:null); + : "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()); + cell.setCellStyle(!"Credit".equals(settle.getString("transaction_type")) ? analysisStyle2 : null); cell = row.createCell(9, Cell.CELL_TYPE_STRING); cell.setCellValue(settle.getBigDecimal("transaction_amount") == null ? "" - : "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()); - cell.setCellStyle(!"Credit".equals(settle.getString("transaction_type"))?analysisStyle2:null); + : "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()); + cell.setCellStyle(!"Credit".equals(settle.getString("transaction_type")) ? analysisStyle2 : null); cell = row.createCell(10, Cell.CELL_TYPE_STRING); cell.setCellValue(settle.getBigDecimal("clearing_amount") == null ? "" - : "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()); - cell.setCellStyle(!"Credit".equals(settle.getString("transaction_type"))?analysisStyle2:null); + : "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()); + cell.setCellStyle(!"Credit".equals(settle.getString("transaction_type")) ? analysisStyle2 : null); row.createCell(11, Cell.CELL_TYPE_STRING).setCellValue(channels.getString(settle.getString("channel")) == null ? "" : channels.getJSONObject(settle.getString("channel")).getBigDecimal("rate").toPlainString() + "%"); //手续费 + gst @@ -1212,6 +1285,7 @@ public class CleanServiceImpl implements CleanService, ManagerTodoNoticeProvider String defaultBank = config.getRemainsTo(); clearingDetailMapper.updateAllBanks(defaultBank, clearingId); List details = clearingDetailMapper.listReportsOfSettlement(clearingId); + details = mergeBatchSettleClients(details); details.sort((log1, log2) -> { if (StringUtils.equals(defaultBank, log1.getString("account_bank")) == StringUtils.equals(defaultBank, log2.getString("account_bank"))) { @@ -1283,6 +1357,7 @@ public class CleanServiceImpl implements CleanService, ManagerTodoNoticeProvider } transactionMapper.deleteSettlementTransaction(clearingId); transactionMapper.removeSettleRemark(clearingId); + preSettleTaskMapper.resetClearStatus(clearingId); clearingDetailAnalysisMapper.clearAnalysis(clearingId); taskManualSettleMapper.rollbackExecutedTask(clearingId); clearingDetailMapper.deleteSettleLogs(clearingId); diff --git a/src/main/java/au/com/royalpay/payment/manage/mappers/log/GatewayClientApplyNotifyLogMapper.java b/src/main/java/au/com/royalpay/payment/manage/mappers/log/GatewayClientApplyNotifyLogMapper.java new file mode 100644 index 000000000..0085819fb --- /dev/null +++ b/src/main/java/au/com/royalpay/payment/manage/mappers/log/GatewayClientApplyNotifyLogMapper.java @@ -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 listErrorLogsIn24Hour(); + + @AutoSql(type = SqlType.SELECT) + JSONObject findHistoryByClientId(@Param("client_id") int clientId); +} diff --git a/src/main/java/au/com/royalpay/payment/manage/mappers/log/PreSettleTaskMapper.java b/src/main/java/au/com/royalpay/payment/manage/mappers/log/PreSettleTaskMapper.java new file mode 100644 index 000000000..228190034 --- /dev/null +++ b/src/main/java/au/com/royalpay/payment/manage/mappers/log/PreSettleTaskMapper.java @@ -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); +} diff --git a/src/main/java/au/com/royalpay/payment/manage/mappers/system/ClientMapper.java b/src/main/java/au/com/royalpay/payment/manage/mappers/system/ClientMapper.java index 82f4aa242..4b164c94a 100644 --- a/src/main/java/au/com/royalpay/payment/manage/mappers/system/ClientMapper.java +++ b/src/main/java/au/com/royalpay/payment/manage/mappers/system/ClientMapper.java @@ -78,6 +78,10 @@ public interface ClientMapper { @AdvanceSelect(addonWhereClause = "is_valid=1") List listChildClients(@Param("parent_client_id") int parentClientId); + @AutoSql(type = SqlType.SELECT) + @AdvanceSelect(addonWhereClause = "is_valid=1") + List listChildClients(@Param("parent_client_id") int parentClientId, PageBounds pagination); + @AutoSql(type = SqlType.UPDATE) void updateCleanDays(@Param("client_id") int clientId, @Param("clean_days") int cleanDays); diff --git a/src/main/java/au/com/royalpay/payment/manage/mappers/system/ManagerMapper.java b/src/main/java/au/com/royalpay/payment/manage/mappers/system/ManagerMapper.java index 7617a0226..693904996 100644 --- a/src/main/java/au/com/royalpay/payment/manage/mappers/system/ManagerMapper.java +++ b/src/main/java/au/com/royalpay/payment/manage/mappers/system/ManagerMapper.java @@ -72,4 +72,6 @@ public interface ManagerMapper { List listDevAndBdOpenId(); List findBdById(@Param("org_id")String org_id); + + } diff --git a/src/main/java/au/com/royalpay/payment/manage/mappers/system/OrgSignInfoMapper.java b/src/main/java/au/com/royalpay/payment/manage/mappers/system/OrgSignInfoMapper.java new file mode 100644 index 000000000..a3c13b628 --- /dev/null +++ b/src/main/java/au/com/royalpay/payment/manage/mappers/system/OrgSignInfoMapper.java @@ -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); + +} diff --git a/src/main/java/au/com/royalpay/payment/manage/merchantid/core/impl/MerchantIdManageServiceImpl.java b/src/main/java/au/com/royalpay/payment/manage/merchantid/core/impl/MerchantIdManageServiceImpl.java index 0832bd737..c30c83d22 100644 --- a/src/main/java/au/com/royalpay/payment/manage/merchantid/core/impl/MerchantIdManageServiceImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/merchantid/core/impl/MerchantIdManageServiceImpl.java @@ -25,13 +25,14 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; 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.IOException; -import java.net.URISyntaxException; -import java.util.*; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; import java.util.stream.Collectors; /** @@ -166,11 +167,7 @@ public class MerchantIdManageServiceImpl implements MerchantIdManageService { 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)); HttpRequestResult result = null; - try { - result = new HttpRequestGenerator(createUrl, RequestMethod.PUT).setJSONEntity(param).execute(); - } catch (URISyntaxException e) { - e.printStackTrace(); - } + result = new HttpRequestGenerator(createUrl, RequestMethod.PUT).setJSONEntity(param).execute(); if (result.isSuccess()) { try { return result.getResponseContentJSONObj(); diff --git a/src/main/java/au/com/royalpay/payment/manage/merchants/core/impls/ClientManagerImpl.java b/src/main/java/au/com/royalpay/payment/manage/merchants/core/impls/ClientManagerImpl.java index 5298c79c0..013295833 100644 --- a/src/main/java/au/com/royalpay/payment/manage/merchants/core/impls/ClientManagerImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/merchants/core/impls/ClientManagerImpl.java @@ -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.dev.bean.TestMerchantAccountInfo; 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.management.sysconfig.core.impls.PermissionPartnerManagerImpl; import au.com.royalpay.payment.manage.mappers.financial.FinancialBDConfigMapper; @@ -126,7 +127,6 @@ import java.awt.image.BufferedImage; import java.io.*; import java.math.BigDecimal; import java.math.RoundingMode; -import java.net.URISyntaxException; import java.net.URL; import java.net.URLDecoder; import java.security.InvalidParameterException; @@ -305,6 +305,8 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid private ClientComplianceCompanyMapper clientComplianceCompanyMapper; @Resource private IndustryLookupMapper industryLookupMapper; + @Resource + private GatewayMerchantApply gatewayMerchantApply; @Resource @@ -830,7 +832,6 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid @Transactional public void updateClientRegisterInfo(JSONObject manager, String clientMoniker, ClientRegisterInfo info) { JSONObject client = getClientInfoByMoniker(clientMoniker); - Assert.notNull(client); checkOrgPermission(manager, client); JSONObject updateInfo = info.updateObject(); @@ -892,7 +893,6 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid @Transactional public void updateClientRegisterInfoV2(JSONObject manager, String clientMoniker, JSONObject info) { JSONObject client = getClientInfoByMoniker(clientMoniker); - Assert.notNull(client); checkOrgPermission(manager, client); int clientId = client.getIntValue("client_id"); @@ -1125,7 +1125,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid if (pass == 1) { createKycAuthStatus(manager,client); clientModifySupport.processClientConfigModify(new SwitchPermissionModify(manager, clientMoniker, "skip_clearing", false)); - if (client.getIntValue("source") == 4) { + if (client.getIntValue("source") == 4 || client.getIntValue("source") == 5) { List accounts = clientAccountMapper.listAdminAccounts(client.getIntValue("client_id")); JSONObject account = accounts.get(0); sendInitEmail(client, account.getString("username"), "*****"); @@ -1133,6 +1133,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid saveClientAuditProcess(client.getIntValue("client_id"), open_status, 5, "合规通过", manager); clientModifySupport.processClientConfigModify(new SwitchPermissionModify(manager, clientMoniker, "skip_clearing", false)); clientModifySupport.processClientConfigModify(new SwitchPermissionModify(manager, clientMoniker, "common_sub_merchant_id", false)); + gatewayMerchantApply.notifyOrgMerchantStatus(client); } else if (checkGreenChannel && client.getIntValue("open_status") == 5) { // 绿色通道通过后不发邮件 logger.info("PASS 绿色通道:" + clientMoniker); @@ -1656,7 +1657,6 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid private JSONObject checkAndFindAccount(JSONObject manager, String clientMoniker, String accountId) { JSONObject account = clientAccountMapper.findById(accountId); - Assert.notNull(account); if (clientMoniker != null) { JSONObject client = getClientInfoByMoniker(clientMoniker); Assert.notNull(client); @@ -2072,15 +2072,17 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid throw new InvalidShortIdException(); } checkOrgPermission(manager, client); - JSONObject listSubClients = new JSONObject(); List listChildClients = clientMapper.listChildClients(client.getIntValue("client_id")); - for (JSONObject partner : listChildClients) { - List clients = clientMapper.listChildClients(partner.getIntValue("client_id")); - if (clients.size() > 0) { - partner.put("level3Clients", clients); - clients.forEach(e -> { - e.put("parent_client_moniker", partner.getString("client_moniker")); - }); + JSONObject mchConfig = merchantInfoProvider.getMchExtParams(client.getIntValue("client_id")); + if (!mchConfig.getBooleanValue("disable_level3_mch")) { + for (JSONObject partner : listChildClients) { + List clients = clientMapper.listChildClients(partner.getIntValue("client_id")); + if (clients.size() > 0) { + partner.put("level3Clients", clients); + clients.forEach(e -> { + e.put("parent_client_moniker", partner.getString("client_moniker")); + }); + } } } return listChildClients; @@ -2546,7 +2548,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid ous.flush(); IOUtils.closeQuietly(ous); } - } catch (URISyntaxException | IOException e) { + } catch (IOException e) { throw new ServerErrorException("Error", e); } } @@ -2565,7 +2567,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid ous.flush(); IOUtils.closeQuietly(ous); } - } catch (URISyntaxException | IOException e) { + } catch (IOException e) { throw new ServerErrorException("Error", e); } } @@ -2602,7 +2604,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid 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()) { res = result.getResponseContentJSONObj(); } - } catch (URISyntaxException | IOException e) { + } catch (IOException e) { logger.error(e.getMessage(), e); } return res; @@ -3400,14 +3402,12 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid @Override public void disableClient(String clientMoniker, JSONObject manager) { JSONObject client = clientDetail(manager, clientMoniker); - Assert.notEmpty(client); clientModifySupport.processClientModify(new DisableModify(manager, clientMoniker, false)); } @Override public void revertClient(String clientMoniker, JSONObject manager) { JSONObject client = clientDetail(manager, clientMoniker); - Assert.notEmpty(client); 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) { logger.error("RefusePartnerError=======:" + clientMoniker + "," + e.getMessage()); } @@ -4716,7 +4719,6 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid @Override public void updateAppClient(JSONObject account, int client_id, AppClientBean appClientBean) { JSONObject client = getClientInfo(client_id); - Assert.notNull(client); JSONObject updateObj = appClientBean.updateObject(); if (updateObj.size() > 0) { updateObj.put("client_id", client_id); @@ -5838,7 +5840,6 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid @Override public void sendVerifyEmail(JSONObject client, String accountId) { JSONObject clientAccount = clientAccountMapper.findById(accountId); - Assert.notNull(clientAccount); simpleClientApplyService.sendVerifyEmail(client.getString("contact_email"), client.getIntValue("client_id"), clientAccount.getString("username")); } diff --git a/src/main/java/au/com/royalpay/payment/manage/merchants/web/PartnerViewController.java b/src/main/java/au/com/royalpay/payment/manage/merchants/web/PartnerViewController.java index 95fec7103..5a95da2f5 100644 --- a/src/main/java/au/com/royalpay/payment/manage/merchants/web/PartnerViewController.java +++ b/src/main/java/au/com/royalpay/payment/manage/merchants/web/PartnerViewController.java @@ -411,7 +411,6 @@ public class PartnerViewController { clientManager.refreshPlatformPublicKeyConfig(account); } - @PartnerMapping(value = "/payment_page_version", method = RequestMethod.PUT) @ResponseBody public void changePaymentPage(@RequestBody JSONObject pass, @ModelAttribute(CommonConsts.PARTNER_STATUS) JSONObject account) { diff --git a/src/main/java/au/com/royalpay/payment/manage/notice/core/impls/MailServiceImp.java b/src/main/java/au/com/royalpay/payment/manage/notice/core/impls/MailServiceImp.java index fc3b70d66..2f273da61 100644 --- a/src/main/java/au/com/royalpay/payment/manage/notice/core/impls/MailServiceImp.java +++ b/src/main/java/au/com/royalpay/payment/manage/notice/core/impls/MailServiceImp.java @@ -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.utils.PageListUtils; 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.JSONArray; import com.alibaba.fastjson.JSONObject; import com.github.miemiedev.mybatis.paginator.domain.Order; import com.github.miemiedev.mybatis.paginator.domain.PageBounds; - import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; @@ -33,6 +33,7 @@ import org.springframework.stereotype.Service; import org.springframework.util.Assert; import org.springframework.web.bind.annotation.RequestMethod; +import javax.annotation.Resource; import java.io.IOException; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; @@ -40,11 +41,6 @@ import java.security.Key; import java.util.ArrayList; 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. */ @@ -183,17 +179,13 @@ public class MailServiceImp implements MailService { noticeBean.setPassword(mailPwd); String postUrl = mailHost + "/mail/single?" + generateMailSignParam(); HttpRequestResult result = null; - try { - logger.info("===sendEmail===noticeBean:" + JSON.toJSON(noticeBean)); - result = new HttpRequestGenerator(postUrl, RequestMethod.POST).setJSONEntity(noticeBean).setTimeout(60_000).execute(); - if (result.isSuccess()) { - String mail_id = result.getResponseContentJSONObj().getString("mail_id"); - return mail_id; - //System.out.println("send Mail=============="+mail_id); - } else { - throw new ServerErrorException("Error Connection"); - } - } catch (URISyntaxException e) { + logger.info("===sendEmail===noticeBean:" + JSON.toJSON(noticeBean)); + result = new HttpRequestGenerator(postUrl, RequestMethod.POST).setJSONEntity(noticeBean).setTimeout(60_000).execute(); + if (result.isSuccess()) { + String mail_id = result.getResponseContentJSONObj().getString("mail_id"); + return mail_id; + //System.out.println("send Mail=============="+mail_id); + } else { throw new ServerErrorException("Error Connection"); } } @@ -219,17 +211,13 @@ public class MailServiceImp implements MailService { noticeBean.setPassword(mailPwd); String postUrl = mailHost + "/mail/single?" + generateMailSignParam(); HttpRequestResult result = null; - try { - logger.info("===sendEmail===noticeBean:" + JSON.toJSON(noticeBean)); - result = new HttpRequestGenerator(postUrl, RequestMethod.POST).setJSONEntity(noticeBean).setTimeout(60_000).execute(); - if (result.isSuccess()) { - String mail_id = result.getResponseContentJSONObj().getString("mail_id"); - return mail_id; - //System.out.println("send Mail=============="+mail_id); - } else { - throw new ServerErrorException("Error Connection"); - } - } catch (URISyntaxException e) { + logger.info("===sendEmail===noticeBean:" + JSON.toJSON(noticeBean)); + result = new HttpRequestGenerator(postUrl, RequestMethod.POST).setJSONEntity(noticeBean).setTimeout(60_000).execute(); + if (result.isSuccess()) { + String mail_id = result.getResponseContentJSONObj().getString("mail_id"); + return mail_id; + //System.out.println("send Mail=============="+mail_id); + } else { throw new ServerErrorException("Error Connection"); } } @@ -249,7 +237,7 @@ public class MailServiceImp implements MailService { } else { throw new ServerErrorException("Mail Service failed; status code=" + result.getStatusCode()); } - } catch (URISyntaxException | IOException e) { + } catch (IOException e) { throw new ServerErrorException("Mail Service failed", e); } @@ -305,17 +293,13 @@ public class MailServiceImp implements MailService { noticeBean.setAttachFiles(attachFiles); String postUrl = mailHost + "/mail/single?" + generateMailSignParam(); HttpRequestResult result = null; - try { - logger.info("===sendEmail===noticeBean:" + JSON.toJSON(noticeBean)); - result = new HttpRequestGenerator(postUrl, RequestMethod.POST).setJSONEntity(noticeBean).setTimeout(60_000).execute(); - if (result.isSuccess()) { - String mail_id = result.getResponseContentJSONObj().getString("mail_id"); - return mail_id; - //System.out.println("send Mail=============="+mail_id); - } else { - throw new ServerErrorException("Error Connection"); - } - } catch (URISyntaxException e) { + logger.info("===sendEmail===noticeBean:" + JSON.toJSON(noticeBean)); + result = new HttpRequestGenerator(postUrl, RequestMethod.POST).setJSONEntity(noticeBean).setTimeout(60_000).execute(); + if (result.isSuccess()) { + String mail_id = result.getResponseContentJSONObj().getString("mail_id"); + return mail_id; + //System.out.println("send Mail=============="+mail_id); + } else { throw new ServerErrorException("Error Connection"); } } @@ -350,17 +334,13 @@ public class MailServiceImp implements MailService { } String postUrl = mailHost + "/mail/single?" + generateMailSignParam(); HttpRequestResult result = null; - try { - logger.info("===sendEmail===noticeBean:" + JSON.toJSON(noticeBean)); - result = new HttpRequestGenerator(postUrl, RequestMethod.POST).setJSONEntity(noticeBean).setTimeout(60_000).execute(); - if (result.isSuccess()) { - String mail_id = result.getResponseContentJSONObj().getString("mail_id"); - return mail_id; - //System.out.println("send Mail=============="+mail_id); - } else { - throw new ServerErrorException("Error Connection"); - } - } catch (URISyntaxException e) { + logger.info("===sendEmail===noticeBean:" + JSON.toJSON(noticeBean)); + result = new HttpRequestGenerator(postUrl, RequestMethod.POST).setJSONEntity(noticeBean).setTimeout(60_000).execute(); + if (result.isSuccess()) { + String mail_id = result.getResponseContentJSONObj().getString("mail_id"); + return mail_id; + //System.out.println("send Mail=============="+mail_id); + } else { throw new ServerErrorException("Error Connection"); } } diff --git a/src/main/java/au/com/royalpay/payment/manage/ofei/core/impl/OfeiClientImpl.java b/src/main/java/au/com/royalpay/payment/manage/ofei/core/impl/OfeiClientImpl.java index 645afdd93..d8b9f391d 100644 --- a/src/main/java/au/com/royalpay/payment/manage/ofei/core/impl/OfeiClientImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/ofei/core/impl/OfeiClientImpl.java @@ -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.ServerErrorException; 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 org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.time.DateFormatUtils; import org.apache.http.NameValuePair; @@ -25,18 +25,9 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; 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 cn.yixblog.platform.http.HttpRequestGenerator; -import cn.yixblog.platform.http.HttpRequestResult; +import java.io.IOException; +import java.util.*; /** * Created by wangning on 2017/12/7. @@ -266,7 +257,7 @@ public class OfeiClientImpl implements OfeiClient { } else { throw new ChannelNetworkException(errMsg + "-->Network Error:" + res.getStatusCode()); } - } catch (URISyntaxException | DocumentException | IOException e) { + } catch (DocumentException | IOException e) { throw new ChannelNetworkException(errMsg + "-->Network Error", e); } } @@ -282,7 +273,7 @@ public class OfeiClientImpl implements OfeiClient { } else { throw new ChannelNetworkException(errMsg + "-->Network Error:" + res.getStatusCode()); } - } catch (URISyntaxException | IOException e) { + } catch (IOException e) { throw new ChannelNetworkException(errMsg + "-->Network Error", e); } diff --git a/src/main/java/au/com/royalpay/payment/manage/organizations/beans/OrgInfo.java b/src/main/java/au/com/royalpay/payment/manage/organizations/beans/OrgInfo.java index 2a20c1502..2fce91187 100644 --- a/src/main/java/au/com/royalpay/payment/manage/organizations/beans/OrgInfo.java +++ b/src/main/java/au/com/royalpay/payment/manage/organizations/beans/OrgInfo.java @@ -2,6 +2,7 @@ package au.com.royalpay.payment.manage.organizations.beans; import com.alibaba.fastjson.JSONObject; import org.apache.commons.lang3.StringUtils; + import javax.validation.constraints.NotEmpty; /** @@ -73,7 +74,6 @@ public class OrgInfo { if (StringUtils.isNotBlank(senior_parent_org_id)) { param.put("senior_parent_org_id", senior_parent_org_id); } - return param; } @@ -359,4 +359,5 @@ public class OrgInfo { public void setMin_cb_bankpay_rate(Double min_cb_bankpay_rate) { this.min_cb_bankpay_rate = min_cb_bankpay_rate; } + } diff --git a/src/main/java/au/com/royalpay/payment/manage/organizations/core/OrgManager.java b/src/main/java/au/com/royalpay/payment/manage/organizations/core/OrgManager.java index 9dc05f5d9..805173cb2 100644 --- a/src/main/java/au/com/royalpay/payment/manage/organizations/core/OrgManager.java +++ b/src/main/java/au/com/royalpay/payment/manage/organizations/core/OrgManager.java @@ -23,12 +23,22 @@ public interface OrgManager { 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 getReferrers(); 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); List listAllOrg(); diff --git a/src/main/java/au/com/royalpay/payment/manage/organizations/core/impls/OrgManagerImpl.java b/src/main/java/au/com/royalpay/payment/manage/organizations/core/impls/OrgManagerImpl.java index 8e38c3705..6cd187b79 100644 --- a/src/main/java/au/com/royalpay/payment/manage/organizations/core/impls/OrgManagerImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/organizations/core/impls/OrgManagerImpl.java @@ -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.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.core.OrgManager; +import au.com.royalpay.payment.tools.codec.RSACrypt; import au.com.royalpay.payment.tools.exceptions.ForbiddenException; import au.com.royalpay.payment.tools.utils.PageListUtils; - import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.github.miemiedev.mybatis.paginator.domain.Order; import com.github.miemiedev.mybatis.paginator.domain.PageBounds; 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.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.Date; import java.util.List; import java.util.stream.Collectors; -import javax.annotation.Resource; - /** * Created by yixian on 2016-10-18. */ @@ -32,6 +37,8 @@ public class OrgManagerImpl implements OrgManager { private OrgMapper orgMapper; @Resource private FinancialPartnerCommissionMapper financialPartnerCommissionMapper; + @Resource + private OrgSignInfoMapper orgSignInfoMapper; @Override public List listOrgs(boolean detail) { @@ -102,7 +109,13 @@ public class OrgManagerImpl implements OrgManager { @Override 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 @@ -113,17 +126,58 @@ public class OrgManagerImpl implements OrgManager { json.put("sort_no", orgMapper.listAllOrgs().size()); json.put("create_time",new Date()); orgMapper.saveOrg(json); + initOrgGatewayInfo(json); return json; } @Override - public void updateOrg(int orgId, OrgInfo org) { + public void updateOrg(int orgId, OrgInfo org, JSONObject manager) { JSONObject json = org.toJSON(); checkOrgRate(json); json.put("org_id", orgId); 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 public List getReferrers() { return orgMapper.listOrgs(1,new PageBounds()); @@ -139,6 +193,45 @@ public class OrgManagerImpl implements OrgManager { 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 public void switchPermission(int orgId, String permissionName, boolean enabled) { 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); + } } diff --git a/src/main/java/au/com/royalpay/payment/manage/organizations/web/OrgManageController.java b/src/main/java/au/com/royalpay/payment/manage/organizations/web/OrgManageController.java index 0476cbc99..9dd4aff73 100644 --- a/src/main/java/au/com/royalpay/payment/manage/organizations/web/OrgManageController.java +++ b/src/main/java/au/com/royalpay/payment/manage/organizations/web/OrgManageController.java @@ -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.http.HttpUtils; import au.com.royalpay.payment.tools.permission.enums.ManagerRole; - import com.alibaba.fastjson.JSONObject; - import org.springframework.validation.Errors; import org.springframework.web.bind.annotation.*; -import java.util.List; - import javax.annotation.Resource; import javax.validation.Valid; +import java.util.List; /** * Created by yixian on 2016-10-18. @@ -75,9 +72,19 @@ public class OrgManageController { } @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); - 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}) @@ -97,4 +104,11 @@ public class OrgManageController { @RequestParam(defaultValue = "20") int limit, @ModelAttribute(CommonConsts.MANAGER_STATUS) JSONObject 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; + } } diff --git a/src/main/java/au/com/royalpay/payment/manage/pos/datasource/ReadWriteSplitRoutingDataSource.java b/src/main/java/au/com/royalpay/payment/manage/pos/datasource/ReadWriteSplitRoutingDataSource.java index 1f3bc62a1..180e7c967 100644 --- a/src/main/java/au/com/royalpay/payment/manage/pos/datasource/ReadWriteSplitRoutingDataSource.java +++ b/src/main/java/au/com/royalpay/payment/manage/pos/datasource/ReadWriteSplitRoutingDataSource.java @@ -12,9 +12,7 @@ public class ReadWriteSplitRoutingDataSource extends AbstractRoutingDataSource { @Override public Object determineCurrentLookupKey() { - DbContextHolder.DbType dataSource = DbContextHolder.getDbType(); - logger.info("------------------当前数据源:{}---------------------",dataSource); - return dataSource; + return DbContextHolder.getDbType(); } } diff --git a/src/main/java/au/com/royalpay/payment/manage/posters/core/impls/PosterServiceImpl.java b/src/main/java/au/com/royalpay/payment/manage/posters/core/impls/PosterServiceImpl.java index a4a25e5a0..8ff68653e 100644 --- a/src/main/java/au/com/royalpay/payment/manage/posters/core/impls/PosterServiceImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/posters/core/impls/PosterServiceImpl.java @@ -11,7 +11,6 @@ import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.RequestMethod; import java.io.IOException; -import java.net.URISyntaxException; /** @@ -29,16 +28,12 @@ public class PosterServiceImpl implements PosterService { public void updatePoster(String imgUrl) { String url = cmsHost + "/api/statistics/count"; HttpRequestGenerator htg = new HttpRequestGenerator(url, RequestMethod.PUT); - try { - HttpRequestResult result = htg.addQueryString("imgUrl", imgUrl).execute(); - if (result.isSuccess()) { - int statusCode = result.getStatusCode(); - if (statusCode == 200) { - logger.info("CMS request succeeded"); - } + HttpRequestResult result = htg.addQueryString("imgUrl", imgUrl).execute(); + if (result.isSuccess()) { + int statusCode = result.getStatusCode(); + if (statusCode == 200) { + logger.info("CMS request succeeded"); } - } catch (URISyntaxException e) { - e.printStackTrace(); } } @@ -57,8 +52,6 @@ public class PosterServiceImpl implements PosterService { // final String s = result.getResponseContentString(); return obj; } - } catch (URISyntaxException e) { - e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } diff --git a/src/main/java/au/com/royalpay/payment/manage/tradelog/refund/impls/RefundServiceImpl.java b/src/main/java/au/com/royalpay/payment/manage/tradelog/refund/impls/RefundServiceImpl.java index 076947193..8512b1582 100644 --- a/src/main/java/au/com/royalpay/payment/manage/tradelog/refund/impls/RefundServiceImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/tradelog/refund/impls/RefundServiceImpl.java @@ -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.utils.CurrencyAmountUtils; import au.com.royalpay.payment.tools.utils.PageListUtils; - import com.alibaba.fastjson.JSONObject; import com.github.miemiedev.mybatis.paginator.domain.PageBounds; import com.github.miemiedev.mybatis.paginator.domain.PageList; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationEventPublisher; @@ -35,12 +33,11 @@ import org.springframework.context.ApplicationEventPublisherAware; import org.springframework.stereotype.Service; import org.springframework.util.Assert; +import javax.annotation.Resource; import java.math.BigDecimal; import java.util.Date; import java.util.List; -import javax.annotation.Resource; - /** * Created by yixian on 2016-07-04. */ @@ -213,7 +210,7 @@ public class RefundServiceImpl implements RefundService, ApplicationEventPublish } private JSONObject executeRefund(String orderId, BigDecimal amount, String remark, JSONObject partnerAccount, JSONObject manager, JSONObject order, - JSONObject client) { + JSONObject client) { checkOrderUseCustomerCoupon(order, amount); JSONObject clientConfig = clientConfigService.find(client.getIntValue("client_id")); OperatorType type = partnerAccount != null ? OperatorType.PARTNER : OperatorType.MANAGER; @@ -222,7 +219,7 @@ public class RefundServiceImpl implements RefundService, ApplicationEventPublish int accountClientId = partnerAccount.getIntValue("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"); operator.put("operator_id", partnerAccount.getString("account_id")); 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 && clientConfig.getBooleanValue("enable_refund_auth"); 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); } // 订单使用积分商城优惠券,仅支持全额退款 diff --git a/src/main/resources/application-dev.properties b/src/main/resources/application-dev.properties index aee3d5b60..9ace52739 100644 --- a/src/main/resources/application-dev.properties +++ b/src/main/resources/application-dev.properties @@ -2,15 +2,15 @@ spring.datasource.type = com.zaxxer.hikari.HikariDataSource #数据源master -spring.datasource.master.schema-name=royalpay_production -spring.datasource.master.host=192.168.1.52:3306 +spring.datasource.master.schema-name=royalpay_dev +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.username=taylor -spring.datasource.master.password=taylor +spring.datasource.master.username=root +spring.datasource.master.password=root #数据源salve -spring.datasource.slave.schema-name=royalpay_production -spring.datasource.slave.host=192.168.1.52:3306 +spring.datasource.slave.schema-name=royalpay_dev +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.username=taylor -spring.datasource.slave.password=taylor \ No newline at end of file +spring.datasource.slave.username=root +spring.datasource.slave.password=root diff --git a/src/main/resources/au/com/royalpay/payment/manage/mappers/log/ClearingDetailMapper.xml b/src/main/resources/au/com/royalpay/payment/manage/mappers/log/ClearingDetailMapper.xml index 473d41a81..cd6d3e435 100644 --- a/src/main/resources/au/com/royalpay/payment/manage/mappers/log/ClearingDetailMapper.xml +++ b/src/main/resources/au/com/royalpay/payment/manage/mappers/log/ClearingDetailMapper.xml @@ -2,28 +2,34 @@ - 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} @@ -628,7 +632,7 @@ select sum(if(temp.transaction_type = 'Credit', temp.clearing_amount * d.proportion, -temp.clearing_amount * d.proportion)) 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 INNER JOIN pmt_orders o ON o.order_id = l.order_id @@ -744,13 +748,13 @@ if(t.transaction_type = 'Credit', t.clearing_amount, -t.clearing_amount) clearing_amount, if(t.transaction_type = 'Credit', t.total_surcharge, -t.total_surcharge) total_surcharge, if(t.transaction_type = 'Credit', t.channel_surcharge, -t.channel_surcharge) channel_surcharge, - if(t.transaction_type = 'Credit', t.settle_amount, -t.settle_amount) settle_amount, + if(t.transaction_type = 'Credit', t.settle_amount, -t.settle_amount) settle_amount, t.order_id, t.org_rate, t.surcharge_cashback, o.customer_surcharge from pmt_transactions t - LEFT JOIN pmt_orders o on o.order_id = t.order_id + LEFT JOIN pmt_orders o on o.order_id = t.order_id INNER JOIN sys_org so ON t.org_id = so.org_id AND so.is_valid = 1 AND so.type = 0 AND so.citypartner = 1 AND so.commission = 1 @@ -763,7 +767,7 @@ @@ -1145,10 +1149,10 @@ t.channel = 'Settlement' ]]> - AND t.client_id IN - - #{clientId} - + AND t.client_id IN + + #{clientId} + and t.client_id=#{client_id} @@ -1208,42 +1212,42 @@ diff --git a/src/main/resources/au/com/royalpay/payment/manage/mappers/system/OrgSignInfoMapper.xml b/src/main/resources/au/com/royalpay/payment/manage/mappers/system/OrgSignInfoMapper.xml new file mode 100644 index 000000000..5ce3c51b9 --- /dev/null +++ b/src/main/resources/au/com/royalpay/payment/manage/mappers/system/OrgSignInfoMapper.xml @@ -0,0 +1,9 @@ + + + + + diff --git a/src/main/resources/i18n/msg_zh.properties b/src/main/resources/i18n/msg_zh.properties index 14d573c35..88fd110a1 100644 --- a/src/main/resources/i18n/msg_zh.properties +++ b/src/main/resources/i18n/msg_zh.properties @@ -1,6 +1,6 @@ msg.test=测试 -error.payment.valid.param_missing=请填写{0} +error.payment.valid.param_missing= {0} 请填写 error.payment.valid.invalid_time=时间格式不正确 error.payment.valid.invalid_channel=不合法的支付通道 error.payment.valid.invalid_fee=不正确的金额 diff --git a/src/main/ui/static/config/organizations/organizations.js b/src/main/ui/static/config/organizations/organizations.js index 5a09e8e70..b144fb176 100644 --- a/src/main/ui/static/config/organizations/organizations.js +++ b/src/main/ui/static/config/organizations/organizations.js @@ -542,8 +542,68 @@ define(['angular', 'uiRouter', 'uiBootstrap'], function (angular) { $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) { + $scope.merchantCodeChecked = true; + $scope.merchantIsValid = true; $scope.types = angular.copy(types); $scope.states = stateMap.configs(); $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'}) }) }; -/* - $scope.toggleRateEditable = function () { - if($scope.org.rate_editable==org.data.rate_editable){ - return; - } - $http.put('/sys/orgs/'+$scope.org.org_id+'/enable_change_rate',{enabled:$scope.org.rate_editable}).then(function () { + $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; - },function (resp) { - commonDialog.alert({title: 'Error', content: resp.data.message, type: 'error'}); - }) - }; - - $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.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.listManagers(); - $scope.modifyManager = function (manager) { + $scope.resetPartnerPubliKey = function () { $uibModal.open({ - templateUrl: '/static/config/managers/templates/modify.html', - controller: 'modifyManagerCtrl', + templateUrl: '/static/payment/partner/templates/partner_reset_public_key_dialog.html', + controller: 'clientResetPartnerPublicKeyDialogCtrl', + backdrop: false, + size: 'lg', resolve: { - manager: function () { - return angular.copy(manager); + gateway_sign: function () { + return $scope.gateway_sign; } } }).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({ - title: 'Confirm!', - content: 'You are setting manager ' + manager.display_name + ' disabled.Are you sure?' + title: 'Confirm', + content: 'This operation will refresh the gateway short id, Are you sure?' }).then(function () { - $http.delete('/sys/manager_accounts/' + manager.manager_id).then(function () { - $scope.listManagers(); + $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'}) - }) + }); }) }; - $scope.newManager = function () { - $uibModal.open({ - templateUrl: '/static/config/managers/templates/new_manager.html', - controller: 'newManagerCtrl', - resolve: { - org: angular.copy($scope.org) - } - }).result.then(function () { - $scope.listManagers(); + }]); + app.controller('clientResetPartnerPublicKeyDialogCtrl', ['$scope', '$http', 'gateway_sign', function ($scope, $http, gateway_sign) { + $scope.gateway_sign = angular.copy(gateway_sign); + $scope.uploadPublicKey = function (mch_public_key) { + $scope.errmsg = null; + $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; }) - }*/ + } + }]); + 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) { $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) { $scope.manager = manager; $scope.isOrgModify = true; @@ -815,4 +908,4 @@ define(['angular', 'uiRouter', 'uiBootstrap'], function (angular) { } }); return app; -}); \ No newline at end of file +}); diff --git a/src/main/ui/static/config/organizations/templates/org_detail.html b/src/main/ui/static/config/organizations/templates/org_detail.html index df2f98844..af53d7d00 100644 --- a/src/main/ui/static/config/organizations/templates/org_detail.html +++ b/src/main/ui/static/config/organizations/templates/org_detail.html @@ -440,6 +440,36 @@ + +
+
+ +
+

+ {{org.gateway_short_id||'初始化'}} + +

+
+
+
+ + +
+
+ + +
+
+
diff --git a/src/main/ui/static/config/organizations/templates/org_detail_parent.html b/src/main/ui/static/config/organizations/templates/org_detail_parent.html index 67d929ab0..138178412 100644 --- a/src/main/ui/static/config/organizations/templates/org_detail_parent.html +++ b/src/main/ui/static/config/organizations/templates/org_detail_parent.html @@ -432,6 +432,36 @@ + +
+
+ +
+

+ {{org.gateway_short_id||'初始化'}} + +

+
+
+
+ + +
+
+ + +
+
+
@@ -516,4 +546,4 @@ --> - \ No newline at end of file + diff --git a/src/main/ui/static/payment/partner/templates/partner_detail.html b/src/main/ui/static/payment/partner/templates/partner_detail.html index c24de99b6..54ff61fe9 100644 --- a/src/main/ui/static/payment/partner/templates/partner_detail.html +++ b/src/main/ui/static/payment/partner/templates/partner_detail.html @@ -43,7 +43,7 @@

- + (Gateway API) 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 rowIterator = sheet.rowIterator(); - Row row = null; - Cell cell = null; - Map> 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 ele = new HashMap<>(); - ele.put(dateStr, amount); - result.put(clientId, ele); - } - } - Set 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 rowIterator = sheet.rowIterator(); - Row row = null; - Cell cell = null; - Map> 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 ele = new LinkedHashMap<>(); - ele.put(dateStr, orders); - result.put(clientId, ele); - } - } - Set clients = new HashSet<>(); - - for (Map.Entry> p : result.entrySet()) { - int count = 1; - for (Map.Entry 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 clients = clientMapper.listValidClient(); - Map 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 rowIterator = sheet.rowIterator(); - Row row = null; - Cell cell = null; - Map> 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 ele = new LinkedHashMap<>(); - ele.put(dateStr, orderCounts); - result.put(clientId, ele); - } - } - Set resultClients = new HashSet<>(); - Date now = new Date(); - for (Map.Entry> 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 o : p.getValue().entrySet()) { - LinkedHashMap 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("

Hi

"); - List list = new ArrayList<>(); - list.add("testTag"); - // sendMail.setTags(list); - Set mailCCs = new HashSet<>(); - mailCCs.add("asd1159111@163.com"); - sendMail.setMailCcs(mailCCs); - Set 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 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 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 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"); - } - -} \ No newline at end of file diff --git a/src/test/java/au/com/royalpay/payment/manage/citypartner/core/impls/CityPartnerPrizeServiceImplTest.java b/src/test/java/au/com/royalpay/payment/manage/citypartner/core/impls/CityPartnerPrizeServiceImplTest.java index c8e8dc0a4..a1d71f8aa 100644 --- a/src/test/java/au/com/royalpay/payment/manage/citypartner/core/impls/CityPartnerPrizeServiceImplTest.java +++ b/src/test/java/au/com/royalpay/payment/manage/citypartner/core/impls/CityPartnerPrizeServiceImplTest.java @@ -1,25 +1,39 @@ package au.com.royalpay.payment.manage.citypartner.core.impls; 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.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.web.bind.annotation.RequestMethod; 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. */ @SpringBootTest -@ActiveProfiles({"local","alipay","wechat","jd","bestpay"}) -@RunWith(SpringRunner.class) 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 private CityPartnerPrizeService cityPartnerPrizeService; + @Test public void generateAgent() throws Exception { } @@ -29,4 +43,166 @@ public class CityPartnerPrizeServiceImplTest { cityPartnerPrizeService.generate("2017-06"); } -} \ No newline at end of file + @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; + } + + +} diff --git a/src/test/java/au/com/royalpay/payment/manage/valid/JPinYinTest.java b/src/test/java/au/com/royalpay/payment/manage/valid/JPinYinTest.java index cef5a20dd..bd427757c 100644 --- a/src/test/java/au/com/royalpay/payment/manage/valid/JPinYinTest.java +++ b/src/test/java/au/com/royalpay/payment/manage/valid/JPinYinTest.java @@ -6,6 +6,7 @@ import au.com.royalpay.payment.tools.codec.AESCrypt; import au.com.royalpay.payment.tools.encryptalgorithm.SignUtils; import com.alibaba.fastjson.JSONObject; import com.github.stuxuhai.jpinyin.PinyinException; +import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.net.util.Base64; import org.junit.Test; @@ -62,4 +63,14 @@ public class JPinYinTest { 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); + } }