提交 dfb120f5 authored 作者: 吴德鹏's avatar 吴德鹏

合并分支 'feature_1.0' 到 'master'

商品导入

查看合并请求 !1
package com.example.afrishop_v3.config;
import com.example.afrishop_v3.models.Token;
import com.example.afrishop_v3.repository.TokenRepository;
import com.example.afrishop_v3.util.PayPalUtil;
import com.paypal.base.codec.binary.Base64;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.OAuthTokenCredential;
import com.paypal.base.rest.PayPalRESTException;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.builder.ToStringExclude;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.concurrent.*;
@Configuration
public class PaypalConfig {
@Value("${paypal.client_app}")
private String clientId;
@Value("${paypal.client_secret}")
private String clientSecret;
@Value("${paypal.mode}")
private String mode;
@Bean
public Map<String, String> paypalSdkConfig() {
Map<String, String> sdkConfig = new HashMap<>();
sdkConfig.put("mode", mode);
return sdkConfig;
}
@Bean
public OAuthTokenCredential authTokenCredential() {
return new OAuthTokenCredential(clientId, clientSecret, paypalSdkConfig());
}
@Bean
public APIContext apiContext() throws PayPalRESTException {
APIContext apiContext = new APIContext(authTokenCredential().getAccessToken());
apiContext.setConfigurationMap(paypalSdkConfig());
return apiContext;
}
}
//package com.example.afrishop_v3.config;
//
//import com.example.afrishop_v3.models.Token;
//import com.example.afrishop_v3.repository.TokenRepository;
//import com.example.afrishop_v3.util.PayPalUtil;
//import com.paypal.base.codec.binary.Base64;
//import com.paypal.base.rest.APIContext;
//import com.paypal.base.rest.OAuthTokenCredential;
//import com.paypal.base.rest.PayPalRESTException;
//
//import net.sf.json.JSONObject;
//import org.apache.commons.lang3.builder.ToStringExclude;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.context.annotation.*;
//
//
//import java.io.IOException;
//import java.io.UnsupportedEncodingException;
//import java.util.*;
//import java.util.concurrent.*;
//
//
//@Configuration
//public class PaypalConfig {
//
// @Value("${paypal.client_app}")
// private String clientId;
//
// @Value("${paypal.client_secret}")
// private String clientSecret;
//
// @Value("${paypal.mode}")
// private String mode;
//
//
// @Bean
// public Map<String, String> paypalSdkConfig() {
// Map<String, String> sdkConfig = new HashMap<>();
// sdkConfig.put("mode", mode);
// return sdkConfig;
// }
//
//
// @Bean
// public OAuthTokenCredential authTokenCredential() {
// return new OAuthTokenCredential(clientId, clientSecret, paypalSdkConfig());
// }
//
// @Bean
// public APIContext apiContext() throws PayPalRESTException {
// APIContext apiContext = new APIContext(authTokenCredential().getAccessToken());
// apiContext.setConfigurationMap(paypalSdkConfig());
// return apiContext;
// }
//
//
//}
package com.example.afrishop_v3.controllers;
import com.example.afrishop_v3.base.Result;
import com.example.afrishop_v3.config.PaypalPaymentIntent;
import com.example.afrishop_v3.config.PaypalPaymentMethod;
import com.example.afrishop_v3.enums.DeliveryStatusEnum;
import com.example.afrishop_v3.enums.OrderStatusEnum;
import com.example.afrishop_v3.enums.ResultCodeEnum;
import com.example.afrishop_v3.models.*;
import com.example.afrishop_v3.repository.*;
import com.example.afrishop_v3.util.DateUtil;
import com.example.afrishop_v3.util.IdUtil;
import com.example.afrishop_v3.util.PayPalUtil;
import com.paypal.api.payments.*;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.OAuthTokenCredential;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @Auther: wudepeng
* @Date: 2020/11/27
* @Description:paypal支付
*/
@RestController
@RequestMapping(value = "/paypal")
@Transactional
public class PaypalContoller extends Controller {
private static Logger logger = LoggerFactory.getLogger(PaypalContoller.class);
@Value("${paypal.success_url}")
private String PAYPAL_SUCCESS_URL;
@Value("${paypal.cancel_url}")
private String PAYPAL_CANCEL_URL;
@Value("${paypal.success_page}")
private String PAYPAL_SUCCESS_PAGE;
@Value("${paypal.failed_page}")
private String PAYPAL_FAILED_PAGE;
@Value("${paypal.mode}")
private String mode;
private final APIContext oldApiContext;
private final TbCfOrderRepository orderRepository;
private final TbCfFinanceRepository financeRepository;
private final NetworkRepository networkRepository;
private final BonusRepository bonusRepository;
private final PostRepository postRepository;
private final UserRepository userRepository;
private final TokenRepository tokenRepository;
public PaypalContoller(APIContext oldApiContext, TbCfOrderRepository orderRepository, TbCfFinanceRepository financeRepository, NetworkRepository networkRepository, BonusRepository bonusRepository, PostRepository postRepository, UserRepository userRepository, TokenRepository tokenRepository) {
this.oldApiContext = oldApiContext;
this.orderRepository = orderRepository;
this.financeRepository = financeRepository;
this.networkRepository = networkRepository;
this.bonusRepository = bonusRepository;
this.postRepository = postRepository;
this.userRepository = userRepository;
this.tokenRepository = tokenRepository;
}
/**
* 发起paypal支付
*
* @param orderId 订单号
* @return Result
*/
@PostMapping("/payment/{orderId}")
public Result payment(@PathVariable("orderId") String orderId) throws IOException {
Result result = new Result();
//==========================支付信息校验==========================
//获取paypal的最新token
APIContext apiContext = getToken();
logger.info("APIContext info token:" + apiContext.getAccessToken());
//订单号
if (StringUtils.isBlank(orderId)) {
logger.error("paypal支付,订单Id不能为空");
return payErrorInfo(result);
}
//订单信息
Optional<TbCfOrder> byId = orderRepository.findById(orderId);
if (byId.isPresent()) {
TbCfOrder order = byId.get();
//订单不存在
if (order == null) {
logger.error("订单不存在");
return payErrorInfo(result);
}
//价格不存在或错误
if (order.getRealityPay() == null || order.getRealityPay().compareTo(BigDecimal.ZERO) <= 0) {
logger.error("paypal支付,订单[" + order.getOrderNo() + "]价格错误");
return payErrorInfo(result);
}
//订单已支付
if (OrderStatusEnum.PAID.getValue().equals(order.getPayStatus().toString())) {
logger.error("paypal支付,订单[" + order.getOrderNo() + "]已支付");
return payErrorInfo(result);
}
//==========================paypal支付业务开始==========================
logger.info("paypal支付开始,时间:" + getTime());
String orderInfo = order.getDeliveryName() + "'s payment information";
logger.info(orderInfo);
try {
Amount amount = new Amount();
amount.setCurrency("USD");
amount.setTotal(String.format("%.2f", order.getRealityPay()));
Transaction transaction = new Transaction();
transaction.setDescription(orderInfo);
transaction.setAmount(amount);
List<Transaction> transactions = new ArrayList<>();
transactions.add(transaction);
Payer payer = new Payer();
payer.setPaymentMethod(PaypalPaymentMethod.paypal.toString());
Payment payment = new Payment();
payment.setIntent(PaypalPaymentIntent.sale.toString());
payment.setPayer(payer);
payment.setTransactions(transactions);
RedirectUrls redirectUrls = new RedirectUrls();
redirectUrls.setCancelUrl(PAYPAL_CANCEL_URL);
redirectUrls.setReturnUrl(PAYPAL_SUCCESS_URL + "/" + orderId);
payment.setRedirectUrls(redirectUrls);
Payment pay = payment.create(apiContext);
logger.info("paypal支付完成,时间:" + getTime());
for (Links links : pay.getLinks()) {
if (links.getRel().equals("approval_url")) {
return result.setData(links.getHref());
}
}
} catch (Exception e) {
logger.info("paypal支付发生异常,时间:" + getTime() + e.getMessage());
return payErrorInfo(result);
}
}
return payErrorInfo(result);
}
public APIContext getToken() throws IOException {
//获取paypal的最新token
Optional<Token> tokenOptional = tokenRepository.findFirstToken();
String token = PayPalUtil.getToken(tokenOptional.get().getToken(), mode);
// String token = PayPalUtil.getToken(oldApiContext.getAccessToken(), mode);
APIContext apiContext = new APIContext(token);
Map<String, String> sdkConfig = new HashMap<>();
sdkConfig.put("mode", mode);
apiContext.setConfigurationMap(sdkConfig);
return apiContext;
}
/**
* 用户取消支付
*/
@GetMapping("/cancel")
public void paymentCancle(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.sendRedirect(PAYPAL_FAILED_PAGE);
}
/**
* 支付成功的回调方法
* <p>
* https://app.afrieshop.com/afrishop/paypal/success?
* paymentId=PAYID-L6XFFIA6TM43947C4571820W&
* token=EC-82206922L7926962C&
* PayerID=WBS8FAZYEQQXS
*/
@GetMapping("/success/{orderId}")
public void paymentSuccess(@PathVariable("orderId") String orderId, HttpServletRequest request, HttpServletResponse response) throws Exception {
logger.info("paypal支付校验开始,时间:" + getTime());
//获取paypal的最新token
APIContext apiContext = getToken();
boolean verify = false;
String payerId = request.getParameter("PayerID");
//订单id
String paymentId = request.getParameter("paymentId");
String token = request.getParameter("token");
System.out.println("payerId" + payerId);
System.out.println("paymentId" + paymentId);
System.out.println("token" + token);
Payment payment = new Payment();
payment.setId(paymentId);
PaymentExecution paymentExecute = new PaymentExecution();
paymentExecute.setPayerId(payerId);
Payment paypal = payment.execute(apiContext, paymentExecute);
logger.info("支付信息:" + paypal);
logger.info("orderId:" + orderId);
Optional<TbCfOrder> byId = orderRepository.findById(orderId);
String payUrl = PAYPAL_SUCCESS_URL + "?paymentId=" + payerId + "&token=" + token + "&PayerID=" + payerId;
if (byId.isPresent()) {
TbCfOrder order = byId.get();
//paypal支付成功
if (paypal.getState().equals("approved")) {
logger.info("paypal支付,订单[" + order.getOrderNo() + "]支付成功");
//1)、修改订单状态
TbCfOrder tbCfOrder = changeOrderState(payerId, order);
//2)、生成支付流水
createFinance(paymentId, payUrl, order);
//数据库校验支付状态##PayStatus 20
if (OrderStatusEnum.PAID.getValue().equals(tbCfOrder.getPayStatus()))
verify = true;
//生成佣金
Optional<TbCfOrder> optional = orderRepository.findById(orderId);
if (optional.isPresent()) {
TbCfOrder order1 = optional.get();
Bonus bonus = new Bonus();
TbCfUserInfo userInfo = new TbCfUserInfo();
userInfo.setUserId(order1.getUserId());
// bonus.setUserId(tbCfOrder.getUserId());
bonus.setOrderId(orderId);
bonus.setAmount(order1.getItemsPrice());
System.out.println("佣金-----》》》订单号:" + orderId + "=user=" + order1.getUserId() + "=price=" + order1.getItemsPrice());
saveNetworkMarketing(bonus, order1.getUserId());
}
}
}
if (verify) {
response.sendRedirect(PAYPAL_SUCCESS_PAGE);
} else {
response.sendRedirect(PAYPAL_FAILED_PAGE);
}
}
/**
* 支付失败提示
*
* @param result
*/
public Result payErrorInfo(Result result) {
result.setCode(ResultCodeEnum.ORDER_PAY_ERROR.getCode());
result.setMessage(ResultCodeEnum.ORDER_PAY_ERROR.getDesc());
return result;
}
/**
* 修改订单状态
*/
private TbCfOrder changeOrderState(String transToken, TbCfOrder order) {
//更改订单状态
order.setUpdateTime(DateUtil.getNow());
order.setDealTime(DateUtil.getNow());
order.setPayId(transToken);
order.setOrderStatus(OrderStatusEnum.PAID.getValue());
order.setPayStatus(OrderStatusEnum.PAID.getValue());
order.setDeliveryFlag(DeliveryStatusEnum.PROCESSING.getValue());
return orderRepository.save(order);
}
private TbCfFinance createFinance(String paymentId, String url, TbCfOrder tbCfOrderVo) {
TbCfFinance tbCfFinance = new TbCfFinance();
tbCfFinance.setOrderId(tbCfOrderVo.getOrderId());
tbCfFinance.setFinaceId(IdUtil.createIdbyUUID());
tbCfFinance.setPayAccount(tbCfOrderVo.getRealityPay());
tbCfFinance.setPayId(paymentId);
tbCfFinance.setPayTime(new Date());
tbCfFinance.setReceiptUrl(url);
tbCfFinance.setPayWayCode("paypal");
tbCfFinance.setUserId(tbCfOrderVo.getUserId());
financeRepository.save(tbCfFinance);
return tbCfFinance;
}
public String getTime() {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String now = format.format(new Date());
return now;
}
public void saveNetworkMarketing(Bonus bonus, String userId) {
String orderId = bonus.getOrderId();
if (orderId == null)
logger.info("佣金:orderId为空");
Optional<TbCfOrder> orderOptional = orderRepository.findById(orderId);
if (!orderOptional.isPresent())
logger.info("佣金:订单不存在");
TbCfOrder order = orderOptional.get();
if (!OrderStatusEnum.PAID.getValue().equals(order.getPayStatus())) {
logger.info("佣金:订单未支付");
}
boolean condition = orderId != null && orderOptional.isPresent() && OrderStatusEnum.PAID.getValue().equals(order.getPayStatus()) && !StringUtils.isBlank(userId);
// if (bonusRepository.existsByOrderId(orderId)) {
// return new Result(ResultCodeEnum.VALIDATE_ERROR.getCode(), "Transaction already done !!!");
//package com.example.afrishop_v3.controllers;
//
//
//import com.example.afrishop_v3.base.Result;
//import com.example.afrishop_v3.config.PaypalPaymentIntent;
//import com.example.afrishop_v3.config.PaypalPaymentMethod;
//import com.example.afrishop_v3.enums.DeliveryStatusEnum;
//import com.example.afrishop_v3.enums.OrderStatusEnum;
//import com.example.afrishop_v3.enums.ResultCodeEnum;
//import com.example.afrishop_v3.models.*;
//import com.example.afrishop_v3.repository.*;
//import com.example.afrishop_v3.util.DateUtil;
//import com.example.afrishop_v3.util.IdUtil;
//import com.example.afrishop_v3.util.PayPalUtil;
//import com.paypal.api.payments.*;
//import com.paypal.base.rest.APIContext;
//import com.paypal.base.rest.OAuthTokenCredential;
//import org.apache.commons.lang3.StringUtils;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.transaction.annotation.Transactional;
//import org.springframework.web.bind.annotation.*;
//
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.io.IOException;
//import java.math.BigDecimal;
//import java.math.RoundingMode;
//import java.text.SimpleDateFormat;
//import java.util.*;
//
///**
// * @Auther: wudepeng
// * @Date: 2020/11/27
// * @Description:paypal支付
// */
//@RestController
//@RequestMapping(value = "/paypal")
//@Transactional
//public class PaypalContoller extends Controller {
//
// private static Logger logger = LoggerFactory.getLogger(PaypalContoller.class);
//
// @Value("${paypal.success_url}")
// private String PAYPAL_SUCCESS_URL;
//
// @Value("${paypal.cancel_url}")
// private String PAYPAL_CANCEL_URL;
//
// @Value("${paypal.success_page}")
// private String PAYPAL_SUCCESS_PAGE;
//
// @Value("${paypal.failed_page}")
// private String PAYPAL_FAILED_PAGE;
//
// @Value("${paypal.mode}")
// private String mode;
//
// private final APIContext oldApiContext;
// private final TbCfOrderRepository orderRepository;
// private final TbCfFinanceRepository financeRepository;
// private final NetworkRepository networkRepository;
// private final BonusRepository bonusRepository;
// private final PostRepository postRepository;
// private final UserRepository userRepository;
// private final TokenRepository tokenRepository;
//
//
// public PaypalContoller(APIContext oldApiContext, TbCfOrderRepository orderRepository, TbCfFinanceRepository financeRepository, NetworkRepository networkRepository, BonusRepository bonusRepository, PostRepository postRepository, UserRepository userRepository, TokenRepository tokenRepository) {
// this.oldApiContext = oldApiContext;
// this.orderRepository = orderRepository;
// this.financeRepository = financeRepository;
// this.networkRepository = networkRepository;
// this.bonusRepository = bonusRepository;
// this.postRepository = postRepository;
// this.userRepository = userRepository;
// this.tokenRepository = tokenRepository;
// }
//
//
// /**
// * 发起paypal支付
// *
// * @param orderId 订单号
// * @return Result
// */
// @PostMapping("/payment/{orderId}")
// public Result payment(@PathVariable("orderId") String orderId) throws IOException {
//
// Result result = new Result();
// //==========================支付信息校验==========================
// //获取paypal的最新token
// APIContext apiContext = getToken();
//
// logger.info("APIContext info token:" + apiContext.getAccessToken());
//
// //订单号
// if (StringUtils.isBlank(orderId)) {
// logger.error("paypal支付,订单Id不能为空");
// return payErrorInfo(result);
// }
BigDecimal amount = bonus.getAmount();
if (condition) {
Optional<TbCfUserInfo> optionalUser = userRepository.findById(userId);
if (optionalUser.isPresent()) {
TbCfUserInfo user = optionalUser.get();
Post post = bonus.getPost();
Optional<Post> postOptional = post == null ? Optional.empty() : postRepository.findById(post.getId());
String productSharer = bonus.getProductSharer();
Optional<TbCfUserInfo> sharer = Optional.empty();
if (productSharer != null) {
sharer = userRepository.findByCode(productSharer);
}
synchronized (this) {
boolean exists = bonusRepository.existsByOrderId(orderId);
if (!exists && user.invited()) {
BigDecimal v = amount.multiply(BigDecimal.valueOf(10)).divide(BigDecimal.valueOf(100), RoundingMode.CEILING);
bonus.setAmount(v);
bonus.setUserInfo(user);
bonus.setPercentage(10);
bonus = bonusRepository.save(bonus);
if (user.hasFcm()) {
sendNotification(user.getFcm(), "Bonus alert !!", user.display() + ", You received bonus of $" + formatter.format(v) + " in your account");
}
}
TbCfUserInfo bonusInc = runBonusInc(user, amount, 5, false, orderId);
runBonusInc(sharer.orElseGet(() -> postOptional.isPresent() ? postOptional.get().getRealUser() : bonusInc), amount, 5, postOptional.isPresent() || sharer.isPresent(), orderId);
//runBonusInc(bonusInc, amount, 0);
}
}
}
}
private TbCfUserInfo runBonusInc(TbCfUserInfo user, BigDecimal amount, int percent, boolean direct, String orderId) {
if (user == null) return null;
Optional<Network> userCode = networkRepository.findFirstByNetworkInfoCode(user.getCode());
if (userCode.isPresent() || direct) {
TbCfUserInfo userInfo = direct ? user : userCode.get().getUserInfo();
Bonus bonus = new Bonus();
bonus.setUserInfo(userInfo);
BigDecimal v = amount.multiply(BigDecimal.valueOf(percent));
v = v.divide(BigDecimal.valueOf(100), RoundingMode.CEILING);
bonus.setAmount(v);
bonus.setPercentage(percent);
bonus.setOrderId(orderId);
if (userInfo != null && userInfo.invited() && !"000000".equals(userInfo.getCode())) {
bonusRepository.save(bonus);
// bonus = repository.save(bonus);
if (userInfo.hasFcm()) {
sendNotification(userInfo.getFcm(), "Bonus alert !!", userInfo.display() + ", You received bonus of $" + formatter.format(v) + " in your account");
}
}
return userInfo;
}
return null;
}
}
//
// //订单信息
// Optional<TbCfOrder> byId = orderRepository.findById(orderId);
// if (byId.isPresent()) {
// TbCfOrder order = byId.get();
//
// //订单不存在
// if (order == null) {
// logger.error("订单不存在");
// return payErrorInfo(result);
// }
//
// //价格不存在或错误
// if (order.getRealityPay() == null || order.getRealityPay().compareTo(BigDecimal.ZERO) <= 0) {
// logger.error("paypal支付,订单[" + order.getOrderNo() + "]价格错误");
// return payErrorInfo(result);
// }
//
// //订单已支付
// if (OrderStatusEnum.PAID.getValue().equals(order.getPayStatus().toString())) {
// logger.error("paypal支付,订单[" + order.getOrderNo() + "]已支付");
// return payErrorInfo(result);
// }
//
// //==========================paypal支付业务开始==========================
//
// logger.info("paypal支付开始,时间:" + getTime());
// String orderInfo = order.getDeliveryName() + "'s payment information";
// logger.info(orderInfo);
// try {
//
// Amount amount = new Amount();
// amount.setCurrency("USD");
// amount.setTotal(String.format("%.2f", order.getRealityPay()));
//
// Transaction transaction = new Transaction();
// transaction.setDescription(orderInfo);
// transaction.setAmount(amount);
//
// List<Transaction> transactions = new ArrayList<>();
// transactions.add(transaction);
//
// Payer payer = new Payer();
// payer.setPaymentMethod(PaypalPaymentMethod.paypal.toString());
// Payment payment = new Payment();
// payment.setIntent(PaypalPaymentIntent.sale.toString());
// payment.setPayer(payer);
// payment.setTransactions(transactions);
// RedirectUrls redirectUrls = new RedirectUrls();
// redirectUrls.setCancelUrl(PAYPAL_CANCEL_URL);
// redirectUrls.setReturnUrl(PAYPAL_SUCCESS_URL + "/" + orderId);
// payment.setRedirectUrls(redirectUrls);
// Payment pay = payment.create(apiContext);
//
// logger.info("paypal支付完成,时间:" + getTime());
// for (Links links : pay.getLinks()) {
// if (links.getRel().equals("approval_url")) {
// return result.setData(links.getHref());
// }
// }
// } catch (Exception e) {
// logger.info("paypal支付发生异常,时间:" + getTime() + e.getMessage());
// return payErrorInfo(result);
// }
// }
//
// return payErrorInfo(result);
// }
//
//
// public APIContext getToken() throws IOException {
// //获取paypal的最新token
// Optional<Token> tokenOptional = tokenRepository.findFirstToken();
// String token = PayPalUtil.getToken(tokenOptional.get().getToken(), mode);
//// String token = PayPalUtil.getToken(oldApiContext.getAccessToken(), mode);
// APIContext apiContext = new APIContext(token);
// Map<String, String> sdkConfig = new HashMap<>();
// sdkConfig.put("mode", mode);
// apiContext.setConfigurationMap(sdkConfig);
// return apiContext;
// }
//
// /**
// * 用户取消支付
// */
// @GetMapping("/cancel")
// public void paymentCancle(HttpServletRequest request, HttpServletResponse response) throws IOException {
// response.sendRedirect(PAYPAL_FAILED_PAGE);
// }
//
//
// /**
// * 支付成功的回调方法
// * <p>
// * https://app.afrieshop.com/afrishop/paypal/success?
// * paymentId=PAYID-L6XFFIA6TM43947C4571820W&
// * token=EC-82206922L7926962C&
// * PayerID=WBS8FAZYEQQXS
// */
// @GetMapping("/success/{orderId}")
// public void paymentSuccess(@PathVariable("orderId") String orderId, HttpServletRequest request, HttpServletResponse response) throws Exception {
// logger.info("paypal支付校验开始,时间:" + getTime());
// //获取paypal的最新token
// APIContext apiContext = getToken();
//
// boolean verify = false;
// String payerId = request.getParameter("PayerID");
// //订单id
// String paymentId = request.getParameter("paymentId");
// String token = request.getParameter("token");
// System.out.println("payerId" + payerId);
// System.out.println("paymentId" + paymentId);
// System.out.println("token" + token);
// Payment payment = new Payment();
// payment.setId(paymentId);
// PaymentExecution paymentExecute = new PaymentExecution();
// paymentExecute.setPayerId(payerId);
// Payment paypal = payment.execute(apiContext, paymentExecute);
//
// logger.info("支付信息:" + paypal);
// logger.info("orderId:" + orderId);
//
// Optional<TbCfOrder> byId = orderRepository.findById(orderId);
// String payUrl = PAYPAL_SUCCESS_URL + "?paymentId=" + payerId + "&token=" + token + "&PayerID=" + payerId;
// if (byId.isPresent()) {
// TbCfOrder order = byId.get();
// //paypal支付成功
// if (paypal.getState().equals("approved")) {
// logger.info("paypal支付,订单[" + order.getOrderNo() + "]支付成功");
//
// //1)、修改订单状态
// TbCfOrder tbCfOrder = changeOrderState(payerId, order);
//
// //2)、生成支付流水
// createFinance(paymentId, payUrl, order);
//
// //数据库校验支付状态##PayStatus 20
// if (OrderStatusEnum.PAID.getValue().equals(tbCfOrder.getPayStatus()))
// verify = true;
// //生成佣金
// Optional<TbCfOrder> optional = orderRepository.findById(orderId);
// if (optional.isPresent()) {
// TbCfOrder order1 = optional.get();
// Bonus bonus = new Bonus();
// TbCfUserInfo userInfo = new TbCfUserInfo();
// userInfo.setUserId(order1.getUserId());
//// bonus.setUserId(tbCfOrder.getUserId());
// bonus.setOrderId(orderId);
// bonus.setAmount(order1.getItemsPrice());
//
// System.out.println("佣金-----》》》订单号:" + orderId + "=user=" + order1.getUserId() + "=price=" + order1.getItemsPrice());
// saveNetworkMarketing(bonus, order1.getUserId());
// }
//
// }
// }
// if (verify) {
// response.sendRedirect(PAYPAL_SUCCESS_PAGE);
// } else {
// response.sendRedirect(PAYPAL_FAILED_PAGE);
// }
//
// }
//
// /**
// * 支付失败提示
// *
// * @param result
// */
// public Result payErrorInfo(Result result) {
// result.setCode(ResultCodeEnum.ORDER_PAY_ERROR.getCode());
// result.setMessage(ResultCodeEnum.ORDER_PAY_ERROR.getDesc());
// return result;
// }
//
//
// /**
// * 修改订单状态
// */
// private TbCfOrder changeOrderState(String transToken, TbCfOrder order) {
// //更改订单状态
// order.setUpdateTime(DateUtil.getNow());
// order.setDealTime(DateUtil.getNow());
// order.setPayId(transToken);
// order.setOrderStatus(OrderStatusEnum.PAID.getValue());
// order.setPayStatus(OrderStatusEnum.PAID.getValue());
// order.setDeliveryFlag(DeliveryStatusEnum.PROCESSING.getValue());
// return orderRepository.save(order);
// }
//
// private TbCfFinance createFinance(String paymentId, String url, TbCfOrder tbCfOrderVo) {
// TbCfFinance tbCfFinance = new TbCfFinance();
// tbCfFinance.setOrderId(tbCfOrderVo.getOrderId());
// tbCfFinance.setFinaceId(IdUtil.createIdbyUUID());
// tbCfFinance.setPayAccount(tbCfOrderVo.getRealityPay());
// tbCfFinance.setPayId(paymentId);
// tbCfFinance.setPayTime(new Date());
// tbCfFinance.setReceiptUrl(url);
// tbCfFinance.setPayWayCode("paypal");
// tbCfFinance.setUserId(tbCfOrderVo.getUserId());
// financeRepository.save(tbCfFinance);
// return tbCfFinance;
// }
//
//
// public String getTime() {
// SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
// String now = format.format(new Date());
// return now;
// }
//
// public void saveNetworkMarketing(Bonus bonus, String userId) {
//
// String orderId = bonus.getOrderId();
//
// if (orderId == null)
// logger.info("佣金:orderId为空");
//
// Optional<TbCfOrder> orderOptional = orderRepository.findById(orderId);
//
// if (!orderOptional.isPresent())
// logger.info("佣金:订单不存在");
//
// TbCfOrder order = orderOptional.get();
//
// if (!OrderStatusEnum.PAID.getValue().equals(order.getPayStatus())) {
// logger.info("佣金:订单未支付");
// }
//
// boolean condition = orderId != null && orderOptional.isPresent() && OrderStatusEnum.PAID.getValue().equals(order.getPayStatus()) && !StringUtils.isBlank(userId);
//
//// if (bonusRepository.existsByOrderId(orderId)) {
//// return new Result(ResultCodeEnum.VALIDATE_ERROR.getCode(), "Transaction already done !!!");
//// }
//
//
// BigDecimal amount = bonus.getAmount();
//
// if (condition) {
//
//
// Optional<TbCfUserInfo> optionalUser = userRepository.findById(userId);
//
// if (optionalUser.isPresent()) {
//
// TbCfUserInfo user = optionalUser.get();
//
// Post post = bonus.getPost();
//
// Optional<Post> postOptional = post == null ? Optional.empty() : postRepository.findById(post.getId());
//
// String productSharer = bonus.getProductSharer();
//
// Optional<TbCfUserInfo> sharer = Optional.empty();
//
// if (productSharer != null) {
// sharer = userRepository.findByCode(productSharer);
// }
// synchronized (this) {
// boolean exists = bonusRepository.existsByOrderId(orderId);
// if (!exists && user.invited()) {
// BigDecimal v = amount.multiply(BigDecimal.valueOf(10)).divide(BigDecimal.valueOf(100), RoundingMode.CEILING);
// bonus.setAmount(v);
// bonus.setUserInfo(user);
// bonus.setPercentage(10);
// bonus = bonusRepository.save(bonus);
// if (user.hasFcm()) {
// sendNotification(user.getFcm(), "Bonus alert !!", user.display() + ", You received bonus of $" + formatter.format(v) + " in your account");
// }
// }
//
// TbCfUserInfo bonusInc = runBonusInc(user, amount, 5, false, orderId);
// runBonusInc(sharer.orElseGet(() -> postOptional.isPresent() ? postOptional.get().getRealUser() : bonusInc), amount, 5, postOptional.isPresent() || sharer.isPresent(), orderId);
// //runBonusInc(bonusInc, amount, 0);
// }
// }
//
// }
//
//
// }
//
// private TbCfUserInfo runBonusInc(TbCfUserInfo user, BigDecimal amount, int percent, boolean direct, String orderId) {
// if (user == null) return null;
// Optional<Network> userCode = networkRepository.findFirstByNetworkInfoCode(user.getCode());
// if (userCode.isPresent() || direct) {
// TbCfUserInfo userInfo = direct ? user : userCode.get().getUserInfo();
// Bonus bonus = new Bonus();
// bonus.setUserInfo(userInfo);
// BigDecimal v = amount.multiply(BigDecimal.valueOf(percent));
// v = v.divide(BigDecimal.valueOf(100), RoundingMode.CEILING);
// bonus.setAmount(v);
// bonus.setPercentage(percent);
// bonus.setOrderId(orderId);
// if (userInfo != null && userInfo.invited() && !"000000".equals(userInfo.getCode())) {
// bonusRepository.save(bonus);
//// bonus = repository.save(bonus);
// if (userInfo.hasFcm()) {
// sendNotification(userInfo.getFcm(), "Bonus alert !!", userInfo.display() + ", You received bonus of $" + formatter.format(v) + " in your account");
// }
// }
// return userInfo;
// }
//
// return null;
// }
//}
package com.example.afrishop_v3.enums;
public enum CategoryEnum {
WOMEN(1,"Women"),
CURVE(3,"Curve+Plus"),
MEN(5,"Men"),
KIDS(4,"Kids");
private Integer categoryId;
private String categoryName;
CategoryEnum(Integer categoryId, String categoryName){
this.categoryId= categoryId;
this.categoryName= categoryName;
}
public Integer getCategoryId() {
return categoryId;
}
public String getCategoryName() {
return categoryName;
}
}
......@@ -63,6 +63,8 @@ public class TbCfDescripiton{
*/
private String twoType;
private String tempId;
private Integer sort;
public Integer getSort() {
......
......@@ -19,6 +19,9 @@ import java.util.Date;
@Data
public class TbCfExpressTemplate{
/**
* 模板id
*/
......@@ -89,6 +92,13 @@ public class TbCfExpressTemplate{
*/
private Date updateTime;
public TbCfExpressTemplate() {
}
public TbCfExpressTemplate(String templateId) {
this.templateId = templateId;
}
/**
* 设置:模板id
*/
......
......@@ -41,6 +41,8 @@ public class TbCfGoodstwotype{
*/
private String goodstwotypeUrl;
private String tempId;
@Transient
private boolean autoLoad = false;
......
......@@ -2,6 +2,7 @@ package com.example.afrishop_v3.models;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.relational.core.sql.In;
import javax.persistence.Entity;
import javax.persistence.Id;
......@@ -41,6 +42,11 @@ public class TbCfGoodstype{
*/
private String goodstypeImage;
/**
* 临时ID
*/
private Integer tempId;
/**
* 设置:商品分类Id
*/
......
......@@ -93,7 +93,7 @@ public class TbCfStationItem {
/**
* 是否置顶 Y:是 N:否
*/
private String itemTop;
private Integer itemTop;
/**
* 供应商
*/
......@@ -127,6 +127,16 @@ public class TbCfStationItem {
private String handled;
private String tempId;
public String getTempId() {
return tempId;
}
public void setTempId(String tempId) {
this.tempId = tempId;
}
@JsonIgnore
@ManyToOne
@JoinColumn(columnDefinition = "template", name = "template")
......@@ -394,19 +404,7 @@ public class TbCfStationItem {
return itemSku;
}
/**
* 设置:是否置顶 Y:是 N:否
*/
public void setItemTop(String itemTop) {
this.itemTop = itemTop;
}
/**
* 获取:是否置顶 Y:是 N:否
*/
public String getItemTop() {
return itemTop;
}
/**
* 设置:供应商
......
package com.example.afrishop_v3.quartz;
import com.example.afrishop_v3.enums.CategoryEnum;
import com.example.afrishop_v3.models.*;
import com.example.afrishop_v3.repository.TbCfDescripitonRepository;
import com.example.afrishop_v3.repository.TbCfGoodstwotypeRepository;
import com.example.afrishop_v3.repository.TbCfGoodstypeRepository;
import com.example.afrishop_v3.repository.TbCfStationItemRepository;
import com.example.afrishop_v3.util.HttpClientUtil;
import com.example.afrishop_v3.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URISyntaxException;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
@Component
@Slf4j
public class ItemTask implements InitializingBean, DisposableBean {
@Autowired
private TbCfGoodstypeRepository tbCfGoodstypeRepository;
@Autowired
private TbCfGoodstwotypeRepository goodstwotypeRepository;
@Autowired
private TbCfDescripitonRepository descripitonRepository;
@Autowired
private TbCfStationItemRepository tbCfStationItemRepository;
private volatile int sort=0;
private volatile Integer page=1;
private final Integer limit=48;
private int total_page=0;
private final String CATEGORY_URL="https://apiv2.lovelywholesale.com/lw-api/head/switch-top-category";
private final String url1="https://apiv2.lovelywholesale.com/lw-api/list/get_child_cat";
private final String ITEM_URL="https://goapi.lovelywholesale.com/search/category/products";
private final String ITEM_DETAIL_URL="https://apiv2.lovelywholesale.com/lw-api/product/item/";
private final int num=Runtime.getRuntime().availableProcessors();
private final ThreadPoolExecutor executor=new ThreadPoolExecutor(num,20,10, TimeUnit.SECONDS, new LinkedBlockingQueue(1024), Executors.defaultThreadFactory(),new ThreadPoolExecutor.DiscardPolicy());
private final ReentrantLock lock=new ReentrantLock();
@Override
public void afterPropertiesSet() throws Exception {
importData();
}
@Override
public void destroy() throws Exception {
executor.shutdown();
}
//=================lovelywholesale商品导入逻辑=================
//棒棒哒!思密哒!
//TODO 温馨提示:是要补充的部分!
/**
* 商品主体信息
*/
public void importData() {
for (int i = 0; i < num; i++) {
executor.execute(()-> {
log.info("线程"+Thread.currentThread().getName()+"开始执行任务!");
try {
importCategory();
} catch (IOException e) {
e.printStackTrace();
}
});
}
}
/**
* 商品详情、sku、属性。。。(还未做)
*/
public void importDetail(){
for (int i = 0; i < 16; i++) {
executor.execute(()->{
List<TbCfStationItem> items = tbCfStationItemRepository.findAllByTempIdIsNotNull();
items.forEach(item->{
String goods_id = item.getTempId();
try {
String result = HttpClientUtil.createConnection(ITEM_DETAIL_URL+goods_id, null, "utf-8");
//TODO 待处理。。。
//商品详情、属性、sku等,处理result,入库如下几张表
// tb_cf_item_skus tb_cf_item_param tb_cf_item_desc attributes attributes_desc tb_cf_category tb_cf_option
// tb_cf_item_comment(商品评价:可选)
// 难受。。。
} catch (IOException e) {
e.printStackTrace();
}
});
});
}
}
/**
* 一、二、三级分类导入
* @throws IOException
*/
// @Test
public void importCategory() throws IOException {
String topCategory = null;
List<Integer> ids= Arrays.asList(1,3,5,4);
for (int i = 0; i < ids.size(); i++) {
Integer catId = ids.get(i);
if (CategoryEnum.WOMEN.getCategoryId()==catId){
topCategory=CategoryEnum.WOMEN.getCategoryName();
}else if (CategoryEnum.CURVE.getCategoryId()==catId){
topCategory=CategoryEnum.CURVE.getCategoryName();
}else if (CategoryEnum.MEN.getCategoryId()==catId){
topCategory=CategoryEnum.MEN.getCategoryName();
}else if (CategoryEnum.KIDS.getCategoryId()==catId){
topCategory=CategoryEnum.KIDS.getCategoryName();
}
// lock.lock();
String categoryId= IdUtil.createIdbyUUID();
//一级分类
categoryId = importTopCategory(topCategory,categoryId,catId);
Map<String,Object> params=new LinkedHashMap<>();
params.put("top_cat_id",catId);
String response=HttpClientUtil.sendPostWithBodyParameter(CATEGORY_URL,params);
JSONObject jsonObject = JSONObject.fromObject(response);
JSONObject data = jsonObject.getJSONObject("data");
JSONArray categorys = data.getJSONArray("categorys");
for (int j = 0; j < categorys.size(); j++) {
String categoryId2=IdUtil.createIdbyUUID();
JSONObject category = categorys.getJSONObject(j);
String tempId2 = category.getString("nav_id");
String navName = category.getString("nav_name");
//二级分类
TbCfGoodstwotype goodstwotype=new TbCfGoodstwotype();
if (!goodstwotypeRepository.existsByGoodstwotypeTitleAndTempId(navName,tempId2)){
goodstwotype.setGoodstwotypeId(categoryId2);
goodstwotype.setGoodstypeId(categoryId);
goodstwotype.setGoodstwotypeTitle(navName);
}else {
goodstwotype = goodstwotypeRepository.findFirstByGoodstwotypeTitleAndTempId(navName,tempId2);
categoryId2=goodstwotype.getGoodstwotypeId();
}
goodstwotype.setTempId(tempId2);
goodstwotypeRepository.save(goodstwotype);
//三级分类
Map<String, String> children = getCategoryChildren(tempId2);
String finalCategoryId = categoryId;
String finalCategoryId1 = categoryId2;
children.entrySet().forEach(c->{
String id = c.getKey();
String[] split = c.getValue().split("-");
String tempId3 =split[0];
String name =split[1];
TbCfDescripiton descripiton=new TbCfDescripiton();
String categoryId3=IdUtil.createIdbyUUID();
if (!descripitonRepository.existsByDescripitionNameAndTempId(name,tempId3)){
descripiton.setDescripitionId(categoryId3);
descripiton.setDescripitionName(name);
descripiton.setGoodstypeId(finalCategoryId);
descripiton.setGoodstwotypeId(finalCategoryId1);
}else {
descripiton = descripitonRepository.findFirstByDescripitionNameAndTempId(name,tempId3);
categoryId3=descripiton.getDescripitionId();
}
descripiton.setTempId(tempId3);
descripitonRepository.save(descripiton);
String str=catId+","+tempId2+","+tempId3;
//商品数据
try {
importItems(finalCategoryId, finalCategoryId1,categoryId3,id,str);
// lock.unlock();
} catch (IOException | URISyntaxException e) {
// lock.unlock();
e.printStackTrace();
}
});
}
}
}
/**
* 商品导入逻辑
* @param categoryId
* @param categoryId2
* @param categoryId3
* @throws IOException
*/
public void importItems(String categoryId,String categoryId2,String categoryId3,String catId,String str) throws IOException, URISyntaxException {
do {
page++ ;
Map<String,Object> params=new LinkedHashMap<>();
params.put("offset",page);
params.put("limit",limit);
params.put("category_id",catId);
params.put("original_category_id",catId);
params.put("is_virtual",1);
String response = HttpClientUtil.sendPostWithBodyParameter(ITEM_URL, params);
JSONObject jsonObject = JSONObject.fromObject(response);
JSONObject data = jsonObject.getJSONObject("data");
total_page = data.getInt("total_page");
JSONArray items = data.getJSONArray("search_list");
for (int i = 0; i < items.size(); i++) {
JSONObject goods = items.getJSONObject(i);
String goods_id = goods.getString("goods_id");
String goods_name = goods.getString("goods_name");
//现价
String usd_shop_price = goods.getString("usd_shop_price");
//原价
String usd_market_price = goods.getString("usd_market_price");
String aws_goods_thumb = goods.getString("aws_goods_thumb");
//TODO
//看情况改吧
//商品入库
TbCfStationItem item=new TbCfStationItem();
item.setItemId(IdUtil.createIdbyUUID());
item.setTempId(goods_id);
item.setItemName(goods_name);
item.setItemBrief(goods_name);
item.setEnableFlag(2);
item.setCreateTime(new Date());
item.setItemCode("2021-"+new Random().nextInt(999999));
item.setDiscountPrice(new BigDecimal(usd_shop_price));
item.setItemPrice(new BigDecimal(usd_market_price));
item.setExpress(new TbCfExpressTemplate("ef57cb80e2e74a42850119c014b06c96"));
//处理标记
item.setHandled("W");
item.setItemCategory(categoryId);
item.setItemCategorytwo(categoryId2);
item.setItemDescritionId(categoryId3);
//商品库存
item.setItemCount(500L);
item.setItemTop(0);
item.setItemImg(aws_goods_thumb);
//额外的属性,看情况填充
item.setItemTags(str);//搜索关键字
item.setSupplier(null);//供应商
tbCfStationItemRepository.save(item);
}
}while (page<total_page);
}
/**
* 一级分类导入
*/
public String importTopCategory(String topCategory,String categoryId,int catId){
TbCfGoodstype goodstype=new TbCfGoodstype();
if (!tbCfGoodstypeRepository.existsByGoodstypeTitle(topCategory)){
//新增
goodstype.setGoodstypeId(categoryId);
goodstype.setGoodstypeTitle(topCategory);
goodstype.setTempId(catId);
tbCfGoodstypeRepository.save(goodstype);
return categoryId;
}else {
TbCfGoodstype type = tbCfGoodstypeRepository.findByGoodstypeTitle(topCategory);
type.setTempId(catId);
tbCfGoodstypeRepository.save(type);
return type.getGoodstypeId();
}
}
/**
* 通过二级分类id查询三级分类
* @param categoryId
* @return
* @throws IOException
*/
public Map<String,String> getCategoryChildren(String categoryId) throws IOException {
Map<String,String> results=new LinkedHashMap<>();
Map<String,Object> params=new LinkedHashMap<>();
params.put("nav_id",categoryId);
String response=HttpClientUtil.sendPostWithBodyParameter(url1,params);
JSONObject jsonObject = JSONObject.fromObject(response);
JSONObject data = jsonObject.getJSONObject("data");
JSONArray categorys = data.getJSONArray("category");
for (int j = 0; j < categorys.size(); j++) {
JSONObject category = categorys.getJSONObject(j);
JSONArray childs = category.getJSONArray("child");
for (int i = 0; i < childs.size(); i++) {
JSONObject child = childs.getJSONObject(i);
String nav_id = child.getString("nav_id");
String name = child.getString("nav_name");
String cat_id = child.getJSONObject("cat_info").getString("cat_id");
results.put(cat_id,nav_id+"-"+name);
}
}
return results;
}
}
package com.example.afrishop_v3.repository;
import com.example.afrishop_v3.models.TbCfDescripiton;
import com.example.afrishop_v3.models.TbCfGoodstwotype;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
......@@ -10,4 +12,9 @@ public interface TbCfDescripitonRepository extends PagingAndSortingRepository<Tb
List<TbCfDescripiton> findAllByGoodstwotypeIdOrderBySort(String categoryTwo);
int countByGoodstwotypeId(String id);
boolean existsByDescripitionNameAndTempId(String name,String tempId);
TbCfDescripiton findFirstByDescripitionNameAndTempId(String name,String tempId);
}
package com.example.afrishop_v3.repository;
import com.example.afrishop_v3.models.TbCfGoodstwotype;
import com.example.afrishop_v3.models.TbCfGoodstype;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
......@@ -10,4 +12,11 @@ public interface TbCfGoodstwotypeRepository extends PagingAndSortingRepository<T
int countByGoodstypeId(String id);
@Query(value = "select max(sort) from TbCfGoodstwotype where goodstypeId=:goodstypeId")
int findMaxSort(String goodstypeId);
boolean existsByGoodstwotypeTitleAndTempId(String name,String tempId);
TbCfGoodstwotype findFirstByGoodstwotypeTitleAndTempId(String name,String tempId);
}
package com.example.afrishop_v3.repository;
import com.example.afrishop_v3.models.TbCfGoodstype;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface TbCfGoodstypeRepository extends PagingAndSortingRepository<TbCfGoodstype,String> {
@Query(value = "select max(goodstypeSort) from TbCfGoodstype")
int findMaxSort();
boolean existsByGoodstypeTitle(String name);
TbCfGoodstype findByGoodstypeTitle(String name);
}
......@@ -62,4 +62,7 @@ public interface TbCfStationItemRepository extends PagingAndSortingRepository<Tb
@Transactional
int updateItmeImg(@Param("itemImg") String itemImg, @Param("itemId") String itemId);
// @Query("select i from #{#entityName} i where tempId is not null")
List<TbCfStationItem> findAllByTempIdIsNotNull();
}
......@@ -34,6 +34,7 @@ public class PayPalUtil {
Response response = client.newCall(request).execute();
String string = response.body().string();
System.out.println("================"+string);
net.sf.json.JSONObject jsonObject = JSONObject.fromObject(string);
String token_type = jsonObject.getString("token_type");
String access_token = jsonObject.getString("access_token");
......
server:
servlet:
context-path: /afrishop
port: 8099
port: 8012
spring:
datasource:
......
//package com.example.afrishop_v3;
//
//import com.example.afrishop_v3.enums.CategoryEnum;
//import com.example.afrishop_v3.models.Country;
//import com.example.afrishop_v3.util.HttpClientUtil;
//import net.sf.json.JSONArray;
//import net.sf.json.JSONObject;
//import org.junit.Test;
//
//import java.io.IOException;
//import java.util.*;
//import java.util.stream.Collectors;
//
//public class MainTest {
//// usd_shop_price(现价) usd_market_price(原价)
// //https://apiv2.lovelywholesale.com/lw-api/product/item/296341?Origin=https:%2F%2Fm.lovelywholesale.com%2F&v=1619262060361
// private final String ITEM_URL="https://goapi.lovelywholesale.com/search/category/products";
// private volatile Integer page=1;
// private final Integer limit=48;
// private int total_page=0;
//// @Test
// public void importItems(Integer category_id) throws IOException {
// JSONArray items=null;
// do {
// page++ ;
// Map<String,Object> params=new LinkedHashMap<>();
// params.put("offset",page);
// params.put("limit",limit);
// params.put("category_id",category_id);
// params.put("original_category_id",category_id);
// params.put("is_virtual",1);
// String response = HttpClientUtil.sendPostWithBodyParameter(ITEM_URL, params);
// JSONObject jsonObject = JSONObject.fromObject(response);
// JSONObject data = jsonObject.getJSONObject("data");
// total_page = data.getInt("total_page");
// items = data.getJSONArray("search_list");
// for (int i = 0; i < items.size(); i++) {
// JSONObject item = items.getJSONObject(i);
// String itemId = item.getString("goods_id");
// String itemName = item.getString("goods_name");
// String categoryName = item.getString("category_name");
// }
//
// }while (page<total_page);
//
//
// }
//
// private final String CATEGORY_URL="https://apiv2.lovelywholesale.com/lw-api/head/switch-top-category";
//
// @Test
// public void importCategory() throws IOException {
// String topCategory = null;
// List<Integer> ids= Arrays.asList(1,3,5,4);
// for (int i = 0; i < ids.size(); i++) {
// Integer catId = ids.get(i);
// if (CategoryEnum.WOMEN.getCategoryId()==catId){
// topCategory=CategoryEnum.WOMEN.getCategoryName();
// }else if (CategoryEnum.CURVE.getCategoryId()==catId){
// topCategory=CategoryEnum.CURVE.getCategoryName();
// }else if (CategoryEnum.MEN.getCategoryId()==catId){
// topCategory=CategoryEnum.MEN.getCategoryName();
// }else if (CategoryEnum.KIDS.getCategoryId()==catId){
// topCategory=CategoryEnum.KIDS.getCategoryName();
// }
// Map<String,Object> params=new LinkedHashMap<>();
// params.put("top_cat_id",catId);
// String response=HttpClientUtil.sendPostWithBodyParameter(CATEGORY_URL,params);
// JSONObject jsonObject = JSONObject.fromObject(response);
// JSONObject data = jsonObject.getJSONObject("data");
// JSONArray categorys = data.getJSONArray("categorys");
// for (int j = 0; j < categorys.size(); j++) {
// JSONObject category = categorys.getJSONObject(j);
// String categoryId = category.getString("nav_id");
// String navName = category.getString("nav_name");
// Map<String, String> children = getCategoryChildren(categoryId);
// System.err.println("一级分类:"+topCategory+"---"+"二级分类-:"+categoryId+"---"+navName);
// //二级分类入库
//// children.entrySet().stream().forEach(System.err::println);
// //三级分类入库
// //通过三级分类查询商品、入库
// children.forEach((k, v) ->{
// try {
// importItems(Integer.parseInt(k));
// } catch (IOException e) {
// e.printStackTrace();
// }
// });
// }
//
//
// }
//
// }
//
// private final String url="https://apiv2.lovelywholesale.com/lw-api/list/get_child_cat";
//
//// @Test
// public Map<String,String> getCategoryChildren(String categoryId) throws IOException {
// Map<String,String> results=new LinkedHashMap<>();
// Map<String,Object> params=new LinkedHashMap<>();
// params.put("nav_id",categoryId);
// String response=HttpClientUtil.sendPostWithBodyParameter(url,params);
// JSONObject jsonObject = JSONObject.fromObject(response);
// JSONObject data = jsonObject.getJSONObject("data");
// JSONArray categorys = data.getJSONArray("category");
// for (int j = 0; j < categorys.size(); j++) {
// JSONObject category = categorys.getJSONObject(j);
// JSONArray childs = category.getJSONArray("child");
// for (int i = 0; i < childs.size(); i++) {
// JSONObject child = childs.getJSONObject(i);
// String name = child.getString("nav_name");
// String cat_id = child.getJSONObject("cat_info").getString("cat_id");
// System.err.println(cat_id+"---"+name);
// results.put(cat_id,name);
// }
// }
// return results;
// }
//
//}
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论