Commit 7d5256bc by caiyt

优化取单二维码逻辑

parent cd42f1bf
......@@ -62,11 +62,6 @@
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
</dependencies>
......
......@@ -128,14 +128,20 @@ public class OrderController extends BaseController {
couponUserService.orderDetailCheckAndAssign(order.getOrderDetails());
}
int amount = order.getPaidAmount().movePointRight(2).intValue();
if (amount == 0) {
order.setPickCode(weixinService.generatePickCode(order));
}
AjaxResult ajaxResult = orderService.insertOrder(loginUser, order, couponUserId);
if (HttpStatus.SUCCESS != (int) ajaxResult.get(AjaxResult.CODE_TAG)) {
return ajaxResult;
}
int amount = order.getPaidAmount().movePointRight(2).intValue();
if (amount == 0) {
return AjaxResult.success(order.getId());
}
Map payInfo = weixinService.pay(request, "hooloo", order.getOrderNo(), order.getUserId(), amount);
if (payInfo != null) {
payInfo.put("orderId", order.getId());
......
package com.soss.web.controller.common;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CannedAccessControlList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import com.soss.framework.web.service.OssFileServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
......@@ -24,80 +13,12 @@ import org.springframework.web.multipart.MultipartFile;
*/
@RestController
@RequestMapping("/common")
public class CommonController
{
private static final Logger log = LoggerFactory.getLogger(CommonController.class);
@Value("${oss.dir}")
private String dir;
// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。关于其他Region对应的Endpoint信息,请参见访问域名和数据中心。
@Value("${oss.endpoint}")
private String endpoint ;
// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
@Value("${oss.accessKeyId}")
private String accessKeyId ;
@Value("${oss.accessKeySecret}")
private String accessKeySecret ;
// 填写Bucket名称,例如examplebucket。
@Value("${oss.bucketName}")
private String bucketName ;
public class CommonController {
@Autowired
private OssFileServiceImpl ossFileService;
@RequestMapping("/uploadOss")
public String uploadOss(MultipartFile file){
return uploadFile(file,dir);
}
private String uploadFile(MultipartFile multipartFile, String dir){
//填写文件名。文件名包含路径,不包含Bucket名称。
OSS ossClient = null;
try {
// 创建OSSClient实例。
ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
//判断桶是否存在,不存在则创建桶
if(!ossClient.doesBucketExist(bucketName)){
//创建bucket
ossClient.createBucket(bucketName);
//设置oss实例的访问权限:公共读
ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
}
//获取文件上传的流
InputStream inputStream = multipartFile.getInputStream();
//构建日期目录
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
String datePath = dateFormat.format(new Date());
//获取文件名
String originname = multipartFile.getOriginalFilename();
String fileUrl = dir + "/" + datePath + "/" + originname;
//文件上传到云服务器
ossClient.putObject(bucketName, fileUrl, inputStream);
return "https://" + bucketName + "." + endpoint + "/" + fileUrl;
} catch (OSSException oe) {
log.error("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
log.error("Error Message:" + oe.getErrorMessage());
log.error("Error Code:" + oe.getErrorCode());
log.error("Request ID:" + oe.getRequestId());
log.error("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
log.error("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
log.error("Error Message:" + ce.getMessage());
} catch (IOException e) {
log.error("上传oss发生异常",e);
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
return null;
public String uploadOss(MultipartFile file) {
return ossFileService.uploadFile(file);
}
}
\ No newline at end of file
......@@ -3,7 +3,7 @@ ruoyi:
version: 3.8.1
copyrightYear: 2022
demoEnabled: true
profile: D:/ruoyi/uploadPath
profile: C:\Users\caiyo\IdeaProjects4\soss\soss-admin\upload
addressEnabled: false
captchaType: math
......@@ -91,6 +91,7 @@ weixin:
templateId: Fu_CPIXa0cnJ4EDdVKqFQ4T3qTxBqv8vXMU7-sQgerg
pagePath: orderSubPackage/pages/orderInfo/index?orderId=
program: trial
# refund-no-prefix: RD
# program: formal
#mqtt:
# url: tcp://iot-06z00dhgql5j8bw.mqtt.iothub.aliyuncs.com:1883
......
......@@ -60,8 +60,22 @@
<version>3.8.1</version>
</dependency>
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.0</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package com.soss.framework.web.service;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CannedAccessControlList;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
@Service
@Slf4j
public class OssFileServiceImpl {
@Value("${oss.dir}")
private String dir;
// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。关于其他Region对应的Endpoint信息,请参见访问域名和数据中心。
@Value("${oss.endpoint}")
private String endpoint;
// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
@Value("${oss.accessKeyId}")
private String accessKeyId;
@Value("${oss.accessKeySecret}")
private String accessKeySecret;
// 填写Bucket名称,例如examplebucket。
@Value("${oss.bucketName}")
private String bucketName;
private OSS ossClient;
@PostConstruct
public void init() {
// 创建OSSClient实例。
ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
//判断桶是否存在,不存在则创建桶
if (!ossClient.doesBucketExist(bucketName)) {
//创建bucket
ossClient.createBucket(bucketName);
//设置oss实例的访问权限:公共读
ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
}
}
public String uploadFile(MultipartFile multipartFile) {
try {
return uploadFile(multipartFile.getInputStream(), multipartFile.getOriginalFilename());
} catch (IOException e) {
log.error("上传oss发生异常", e);
}
return null;
}
public String uploadFile(InputStream inputStream, String originName) {
try {
//构建日期目录
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
String datePath = dateFormat.format(new Date());
String fileUrl = dir + "/" + datePath + "/" + originName;
//文件上传到云服务器
ossClient.putObject(bucketName, fileUrl, inputStream);
return "https://" + bucketName + "." + endpoint + "/" + fileUrl;
} catch (OSSException oe) {
log.error("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
log.error("Error Message:" + oe.getErrorMessage());
log.error("Error Code:" + oe.getErrorCode());
log.error("Request ID:" + oe.getRequestId());
log.error("Host ID:" + oe.getHostId());
}
return null;
}
}
......@@ -12,6 +12,11 @@ import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.wxpay.sdk.WXPayUtil;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.soss.common.core.domain.entity.SysUser;
import com.soss.common.core.domain.model.LoginUser;
import com.soss.common.enums.RefundState;
......@@ -22,12 +27,10 @@ import com.soss.common.utils.ip.IpUtils;
import com.soss.common.utils.sign.Base64;
import com.soss.system.constants.OrderStatusConstant;
import com.soss.system.domain.*;
import com.soss.system.jiguang.impl.JiGuangPushServiceImpl;
import com.soss.system.mapper.CustomerMapper;
import com.soss.system.mapper.OrderDetailMapper;
import com.soss.system.mapper.OrderRefundMapper;
import com.soss.system.mapper.ShopMapper;
import com.soss.system.service.impl.MachineApiServiceImpl;
import com.soss.system.service.impl.OrderOperationLogServiceImpl;
import com.soss.system.service.impl.OrderServiceImpl;
import com.soss.system.utils.DistanceUtil;
......@@ -54,6 +57,8 @@ import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.InetAddress;
......@@ -83,13 +88,11 @@ public class WeixinServiceImpl {
@Autowired
private OrderOperationLogServiceImpl orderOperationLogService;
@Autowired
private MachineApiServiceImpl machineApiService;
@Autowired
private OrderRefundMapper orderRefundMapper;
@Autowired
private JiGuangPushServiceImpl jiGuangPushService;
@Autowired
private ShopMapper shopMapper;
@Autowired
private OssFileServiceImpl ossFileService;
private final ReentrantLock lock = new ReentrantLock();
......@@ -124,6 +127,34 @@ public class WeixinServiceImpl {
return res;
}
public String getAccessToken() {
String accessTokenKey = "ACCESS_TOKEN";
String accessToken = stringRedisTemplate.opsForValue().get(accessTokenKey);
if (StringUtils.isNotEmpty(accessToken)) {
return accessToken;
}
synchronized (this) {
if (StringUtils.isNotEmpty(accessToken)) {
return accessToken;
}
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";
String replaceUrl = url.replace("{0}", appid).replace("{1}", secret);
JSONObject res = restTemplate.getForObject(replaceUrl, JSONObject.class);
log.info("微信返回的信息为:【{}】", res);
if (res == null) {
return null;
}
accessToken = res.getString("access_token");
Integer expiresIn = res.getInteger("expires_in");
stringRedisTemplate.opsForValue().set(accessTokenKey, accessToken);
stringRedisTemplate.expire(accessTokenKey, expiresIn - 100, TimeUnit.SECONDS);
}
return accessToken;
}
@PostConstruct
public void initAreaData() {
try {
......@@ -383,20 +414,12 @@ public class WeixinServiceImpl {
//处理重复的通知
//接口调用的幂等性:无论接口被调用多少次,产生的结果是一致的。
String orderStatus =order.getState();
if("1".equals(orderStatus)){
if ("1".equals(orderStatus)) {
//更新订单状态
order.setPayTime(new Date());
order.setState("2");
JSONObject jsonObject =new JSONObject();
jsonObject.put("orderId",order.getId());
jsonObject.put("userId",order.getUserId());
String uid = UUID.randomUUID().toString();
stringRedisTemplate.opsForValue().set(uid, String.valueOf(order.getId()));
stringRedisTemplate.expire(uid,1, TimeUnit.DAYS);
jsonObject.put("secret",uid);
order.setPickCode(jsonObject.toJSONString());
order.setPickCode(generatePickCode(order));
orderService.updateOrder(order);
}
} finally {
//要主动释放锁
......@@ -409,12 +432,25 @@ public class WeixinServiceImpl {
log.info("支付成功,已应答");
return returnXml;
}
public String generatePickCode(Order order) {
String uid = UUID.randomUUID().toString();
stringRedisTemplate.opsForValue().set(uid, String.valueOf(order.getId()));
stringRedisTemplate.expire(uid, 1, TimeUnit.DAYS);
JSONObject jsonObject = new JSONObject();
jsonObject.put("orderId", order.getId());
jsonObject.put("userId", order.getUserId());
jsonObject.put("secret", uid);
return generateMiniQr(jsonObject.toJSONString() + "###");
}
/**
* 将通知参数转化为字符串
*
* @param request
* @return
*/
public String readData(HttpServletRequest request) {
public String readData(HttpServletRequest request) {
BufferedReader br = null;
try {
StringBuilder result = new StringBuilder();
......@@ -681,9 +717,26 @@ public class WeixinServiceImpl {
map.put("phoneNumber", encDataInf.getString("phoneNumber"));
map.put("customerName", customer.getUserName());
return map;
}catch (Exception e){
log.error("微信登录发生异常",e);
} catch (Exception e) {
log.error("微信登录发生异常", e);
throw new ServiceException("微信登录异常,请重新登录");
}
}
public String generateMiniQr(String content) {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
// 解决中文乱码
HashMap<EncodeHintType, Object> hints = new HashMap<>(16);
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
String fileName = System.currentTimeMillis() + ".png";
try {
BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, 350, 350, hints);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix, "PNG", byteArrayOutputStream);
return ossFileService.uploadFile(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()), fileName);
} catch (Exception e) {
log.error("生成二维码失败:{}", e.getMessage(), e);
}
return null;
}
}
......@@ -17,6 +17,7 @@ import com.soss.system.service.IOrderRefundService;
import io.jsonwebtoken.lang.Assert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
......@@ -45,6 +46,8 @@ public class OrderRefundServiceImpl implements IOrderRefundService {
private OrderDetailMapper orderDetailMapper;
@Autowired
private OrderMapper orderMapper;
@Value("${weixin.refund-no-prefix:R}")
private String refundNoPrefix;
/**
* 查询订单退款
......@@ -149,7 +152,7 @@ public class OrderRefundServiceImpl implements IOrderRefundService {
orderRefund.setUpdatedAt(new Date());
orderRefund.setState(RefundState.PENDING.getState());
orderRefund.setOrderNo(order.getOrderNo());
orderRefund.setRefundNo(GenerateCode.getCode("R", "%09d"));
orderRefund.setRefundNo(GenerateCode.getCode(refundNoPrefix, "%09d"));
orderRefund.setTotalFee(orderDetailAmount);
orderRefund.setOrderNo(order.getOrderNo());
if (StringUtils.isEmpty(orderRefund.getCreateUserName())) {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment