Administrator
5 days ago 267c06a5864bb617b1ff0ea82210346bf5573f5f
src/main/java/cc/mrbird/febs/pay/service/impl/XcxPayServiceImpl.java
@@ -18,17 +18,11 @@
import cc.mrbird.febs.pay.util.WeixinServiceUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.toolkit.Base64;
import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
@@ -46,7 +40,6 @@
import java.io.*;
import java.math.BigDecimal;
import java.net.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
@@ -57,6 +50,12 @@
@Service
@RequiredArgsConstructor
public class XcxPayServiceImpl implements IXcxPayService {
    @Autowired
    private HappyActivityOrderMapper happyActivityOrderMapper;
    @Autowired
    private HappyActivityMapper happyActivityMapper;
    @Autowired
    private MallOrderInfoMapper mallOrderInfoMapper;
@@ -85,9 +84,13 @@
        BrandWCPayRequestData payData;
        String productNames = "小程序充值";
        MallMember mallMember = mallMemberMapper.selectById(apiRechargeWalletDto.getMemberId());
        String rechargeNo = "CZ_"+MallUtils.getOrderNum();
        String rechargeNo = apiRechargeWalletDto.getRechargeNo();
        Long agentApplyId = apiRechargeWalletDto.getAgentApplyId() == null ? 0L : apiRechargeWalletDto.getAgentApplyId();
        Boolean debug = xcxProperties.getDebug();
        String attrStr = "{'rechargeNo':"+rechargeNo+",'memberId':"+mallMember.getId()+"}";
        String attrStr = "{'rechargeNo':"+rechargeNo
                +",'memberId':"+mallMember.getId()
                +",'agentApplyId':"+agentApplyId
                +",'type':"+apiRechargeWalletDto.getType()+"}";
        if (debug) {
            payData = weixinServiceUtil.createRechargeWallet("[测试]" + productNames, rechargeNo,
                    1, mallMember.getOpenId(), attrStr);
@@ -95,13 +98,6 @@
            payData = weixinServiceUtil.createRechargeWallet(productNames, rechargeNo,
                    unit.multiply(money).intValue(),mallMember.getOpenId(), attrStr);
        }
        mallMoneyFlowService.addMoneyFlow(
                mallMember.getId(),
                money,
                MoneyFlowTypeEnum.RECHARGE.getValue(),
                rechargeNo,
                FlowTypeEnum.BALANCE.getValue(),
                "余额充值",1);
        return payData;
    }
@@ -158,42 +154,41 @@
    @Override
    public FebsResponse getQrCode(WxGenerateQrCodeDto wxGenerateQrCodeDto) {
        //这里调用的是上面的获取access_token方法
        String access_token = redisUtils.get(WechatConfigure.WX_ACCESS_TOKEN_REDIS_KEY).toString();
        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+access_token;
        String scene = wxGenerateQrCodeDto.getScene();
        Map<String, String> param = new HashMap<>();
        param.put("scene",scene);
        //这里的page如果没有的话可以不写,默认是跳主页,如果写了没有的页面的话,会返回错误信息
        param.put("page",wxGenerateQrCodeDto.getPage());
        String json = JSON.toJSONString(param);
        ByteArrayInputStream inputStream = sendPost(url, json);
        try {
            System.out.println(inputStream);
            //这里判断的是返回的图片还是错误信息,一般错误信息不会大于200
            if (inputStream.available() <= 200){
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                int i;
                byte[] buffer = new byte[200];
                while ((i = inputStream.read(buffer)) != -1){
                    byteArrayOutputStream.write(buffer,0,i);
                }
                String str = new String(byteArrayOutputStream.toByteArray());
                System.out.println(str);
                //错误信息的格式在官方文档里有
                com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(str);
                if ("41030".equals(jsonObject.getString("errcode"))){
                    return new FebsResponse().fail().data("所传page页面不存在,或者小程序没有发布");
                }else if ("45009".equals(jsonObject.getString("errcode"))){
                    return new FebsResponse().fail().data("调用分钟频率受限");
                }
                byteArrayOutputStream.close();
            }
            inputStream.close();
        }catch (Exception e){
            return new FebsResponse().fail().data("获取二维码失败");
        }
        return new FebsResponse().success().data(inputStream);
//        //这里调用的是上面的获取access_token方法
//        String access_token = redisUtils.get(WechatConfigure.WX_ACCESS_TOKEN_REDIS_KEY).toString();
//        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+access_token;
//        String scene = wxGenerateQrCodeDto.getScene();
//        Map<String, String> param = new HashMap<>();
//        param.put("scene",scene);
//        //这里的page如果没有的话可以不写,默认是跳主页,如果写了没有的页面的话,会返回错误信息
//        param.put("page",wxGenerateQrCodeDto.getPage());
//        String json = JSON.toJSONString(param);
//        ByteArrayInputStream inputStream = sendPost(url, json);
//        try {
//            System.out.println(inputStream);
//            //这里判断的是返回的图片还是错误信息,一般错误信息不会大于200
//            if (inputStream.available() <= 200){
//                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//                int i;
//                byte[] buffer = new byte[200];
//                while ((i = inputStream.read(buffer)) != -1){
//                    byteArrayOutputStream.write(buffer,0,i);
//                }
//                String str = new String(byteArrayOutputStream.toByteArray());
//                byteArrayOutputStream.close();
//                //错误信息
//                com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(str);
//                if ("41030".equals(jsonObject.getString("errcode"))){
//                    return new FebsResponse().fail().data("所传page页面不存在,或者小程序没有发布");
//                }else if ("45009".equals(jsonObject.getString("errcode"))){
//                    return new FebsResponse().fail().data("调用分钟频率受限");
//                }
//            }
//            inputStream.close();
//        }catch (Exception e){
//            return new FebsResponse().fail().data("获取二维码失败");
//        }
        return new FebsResponse().success();
    }
    @Override
@@ -217,6 +212,27 @@
    }
    @Override
    public BrandWCPayRequestData startPaymentActivity(HappyActivityOrder dto) throws Exception {
        BigDecimal unit = new BigDecimal("100");
        BigDecimal money = new BigDecimal(dto.getAmount().toString());
        BrandWCPayRequestData payData;
        HappyActivity happyActivity = happyActivityMapper.selectById(dto.getActivityId());
        String productNames = getActivityNames(happyActivity.getId(),dto.getNumCnt());
        MallMember mallMember = mallMemberMapper.selectById(dto.getMemberId());
        Boolean debug = xcxProperties.getDebug();
        if (debug) {
            payData = weixinServiceUtil.createActivityOrder("[测试]" + productNames, dto.getOrderNo(),
                    1, mallMember.getOpenId(), String.valueOf(dto.getId()));
        } else {
            payData = weixinServiceUtil.createActivityOrder(productNames, dto.getOrderNo(),
                    unit.multiply(money).intValue(),mallMember.getOpenId(), String.valueOf(dto.getId()));
        }
        dto.setWxOrderNo(payData.getPrepay_id());
        happyActivityOrderMapper.updateById(dto);
        return payData;
    }
    @Override
    public void pushOrderToAddress(OrderStateDto info) {
        RestTemplate restTemplate = new RestTemplate();
        String url =  WechatConfigure.SEND_INFO_URL  + redisUtils.get(WechatConfigure.WX_ACCESS_TOKEN_REDIS_KEY);
@@ -226,10 +242,10 @@
        orderStateMsgVo.setTemplate_id(info.getTemplateId());//订阅消息模板id
        orderStateMsgVo.setPage(info.getPage());
        Map<String, WxTemplateData> m = new HashMap<>(4);
        m.put("character_string2", new WxTemplateData(info.getOrderNo()));
        m.put("thing11", new WxTemplateData(info.getGoodsName()));
        m.put("amount1", new WxTemplateData(info.getAmount()));
        m.put("character_string9", new WxTemplateData(info.getTakeCode()));
        m.put("thing19", new WxTemplateData(info.getAddressArea()));
        m.put("phone_number18", new WxTemplateData(info.getLeaderPhone()));
        m.put("thing3", new WxTemplateData(info.getGoodsName()));
        m.put("thing15", new WxTemplateData(info.getRemark()));
        orderStateMsgVo.setData(m);
        String s = JSONUtil.toJsonStr(orderStateMsgVo);
        log.info(s);
@@ -287,22 +303,84 @@
    }
    @Override
    public List<String> getTemplateId() {
        List<String> wxTemplates = new ArrayList<>();
        List<DataDictionaryCustom> wxTemplateList = dataDictionaryCustomMapper.selectDicByType(DataDictionaryEnum.WX_TEMPLATE_ID_ONE.getType());
    public List<HashMap<String, String>> getTemplateId() {
        List<HashMap<String, String>> wxTemplates = new ArrayList<>();
        List<DataDictionaryCustom> wxTemplateList = dataDictionaryCustomMapper.selectDicByType(DataDictionaryEnum.WX_TEMPLATE_ID_THREE.getType());
        if(CollUtil.isNotEmpty(wxTemplateList)){
            for(DataDictionaryCustom dic : wxTemplateList){
                wxTemplates.add(dic.getValue());
                HashMap<String, String> objectObjectHashMap = new HashMap<>();
                objectObjectHashMap.put("name",dic.getCode());
                objectObjectHashMap.put("value",dic.getValue());
                wxTemplates.add(objectObjectHashMap);
            }
        }
        return wxTemplates;
    }
    @Autowired
    private MallGoodsMapper mallGoodsMapper;
    @Autowired
    private MallTeamLeaderMapper mallTeamLeaderMapper;
    @Override
    public FebsResponse generateQrCode(WxGenerateQrCodeDto wxGenerateQrCodeDto) {
        Integer type = wxGenerateQrCodeDto.getType();
        if(1 == type){
            long goodsId = StrUtil.isBlank(wxGenerateQrCodeDto.getTypeParam()) ? 0L : Long.parseLong(wxGenerateQrCodeDto.getTypeParam());
            MallGoods mallGoods = mallGoodsMapper.selectById(goodsId);
            if(ObjectUtil.isNotNull(mallGoods)){
                String wxCodeImg = mallGoods.getWxCodeImg();
                if(StrUtil.isNotBlank(wxCodeImg)){
                    return new FebsResponse().success().data(wxCodeImg);
                }
            }
        }
        if(2 == type){
            String uniqueCode = wxGenerateQrCodeDto.getTypeParam();
            MallTeamLeader mallTeamLeader = mallTeamLeaderMapper.selectLeaderByUniqueCode(uniqueCode);
            if(ObjectUtil.isNotNull(mallTeamLeader)){
                String wxCodeImg = mallTeamLeader.getWxCodeImg();
                if(StrUtil.isNotBlank(wxCodeImg)){
                    return new FebsResponse().success().data(wxCodeImg);
                }
            }
        }
        if (type == 3) {
            String inviteId = wxGenerateQrCodeDto.getTypeParam();
            MallMember member = mallMemberMapper.selectInfoByInviteId(inviteId);
            if(ObjectUtil.isNotNull(member)){
                String wxCodeImg = member.getInviteImg();
                if(StrUtil.isNotBlank(wxCodeImg)){
                    return new FebsResponse().success().data(wxCodeImg);
                }
            }
        }
        String randomNum = MallUtils.getRandomNum(5);
        String imgName="/user_" + randomNum + "_acode_1.jpg";
        String codeImgPath = generateAcode(wxGenerateQrCodeDto.getScene(), wxGenerateQrCodeDto.getPage(), imgName, "800px", null);
        String codeImgPath = generateAcode(wxGenerateQrCodeDto.getScene(), wxGenerateQrCodeDto.getPage(), imgName, "400px", null);
        if(1 == type){
            long goodsId = StrUtil.isBlank(wxGenerateQrCodeDto.getTypeParam()) ? 0L : Long.parseLong(wxGenerateQrCodeDto.getTypeParam());
            MallGoods mallGoods = mallGoodsMapper.selectById(goodsId);
            mallGoods.setWxCodeImg(codeImgPath);
            mallGoodsMapper.updateById(mallGoods);
        }
        if(2 == type){
            String uniqueCode = wxGenerateQrCodeDto.getTypeParam();
            MallTeamLeader mallTeamLeader = mallTeamLeaderMapper.selectLeaderByUniqueCode(uniqueCode);
            mallTeamLeader.setWxCodeImg(codeImgPath);
            mallTeamLeaderMapper.updateById(mallTeamLeader);
        }
        if (type == 3) {
            String inviteId = wxGenerateQrCodeDto.getTypeParam();
            MallMember member = mallMemberMapper.selectInfoByInviteId(inviteId);
            if(ObjectUtil.isNotNull(member)){
                member.setInviteImg(codeImgPath);
                mallMemberMapper.updateById(member);
            }
        }
        return new FebsResponse().success().data(codeImgPath);
    }
@@ -361,9 +439,9 @@
     * @return
     */
    //图片上传路径
    public  static  final String IMG_UPLOAD_PATH="/mnt/sdc/webresource/groupbuy/wxcode";
    public  static  final String IMG_UPLOAD_PATH="/mnt/sdc/webresource/blnka/wxcode";
    public  String generateAcode(String scene,String path,String imgName,String width, Integer type){
        String urlPrefix="http://hwfile.csxuncong.com/groupbuy/wxcode";
        String urlPrefix="https://file.blnka.cn/blnka/wxcode";
        String imgPath=IMG_UPLOAD_PATH+imgName;
        if(!FileUtil.exist(imgPath)){
@@ -372,27 +450,28 @@
            String url = null;
            if (type == null) {
                // 该接口无数量限制,但是 scene 传参最大字符长度为32个字符
                url = StrFormatter.format("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={}",redisUtils.get(WechatConfigure.WX_ACCESS_TOKEN_REDIS_KEY).toString());
                obj.put("scene", scene);
                obj.put("path", path);
                url = StrUtil.format("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={}",redisUtils.get(WechatConfigure.WX_ACCESS_TOKEN_REDIS_KEY).toString());
                obj.set("scene", scene);
                obj.set("page", path);
            } else {
                // 该接口存在数量限制, 总共可生成10w个, 但参数是接在path后面
                url = StrFormatter.format("https://api.weixin.qq.com/wxa/getwxacode?access_token={}", redisUtils.get(WechatConfigure.WX_ACCESS_TOKEN_REDIS_KEY).toString());
                obj.put("path", path + "?" + scene );
                url = StrUtil.format("https://api.weixin.qq.com/wxa/getwxacode?access_token={}", redisUtils.get(WechatConfigure.WX_ACCESS_TOKEN_REDIS_KEY).toString());
                obj.set("page", path + "?" + scene );
            }
            //最小 280px,最大 1280px
            obj.put("width", width);
            obj.put("auto_color", false);
            obj.set("width", width);
            obj.set("auto_color", false);
            cn.hutool.json.JSONObject obj2 = JSONUtil.createObj();
            obj2.put("r", 0);
            obj2.put("g", 0);
            obj2.put("b", 0);
            obj.put("line_color", obj2);
            obj2.set("r", 0);
            obj2.set("g", 0);
            obj2.set("b", 0);
            obj.set("line_color", obj2);
            //是否需要透明底色,为 true 时,生成透明底色的小程序码
            obj.put("is_hyaline", false);
            obj.set("is_hyaline", false);
            try {
                HttpResponse execute = HttpRequest.post(url).body(obj.toString(), "application/json").execute();
                log.error("微信返回值:{}", execute.body());
                InputStream inputStream = execute.bodyStream();
                File file = new File(imgPath);
                FileUtil.writeFromStream(inputStream, file);
@@ -457,4 +536,21 @@
        }
        return productNames;
    }
    /**
     * 根据用户ID和订单ID获取所购买商品名称
     * @return 所含商品名称(多个以","隔开)
     */
    public String getActivityNames(Long activityId,Integer numCnt) {
        HappyActivity happyActivity = happyActivityMapper.selectById(activityId);
        StringBuffer productNameBuffer = new StringBuffer();
        Integer maxLength = 25;
        String goodsName = happyActivity.getName();
        if (goodsName.length() > maxLength) {
            productNameBuffer.append(goodsName.substring(0, maxLength) + "*"+numCnt);
        }else{
            productNameBuffer.append(goodsName+"*"+numCnt);
        }
        return productNameBuffer.toString();
    }
}