k94314517
2024-09-04 f563ada63ac903d087bf884705c376c9cf1384b3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
package com.doumee.biz.zbom.impl;
 
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.doumee.biz.system.SystemDictDataBiz;
import com.doumee.biz.zbom.ZbomCRMService;
import com.doumee.biz.zbom.model.crm.*;
import com.doumee.biz.zbom.model.crm.response.CRMBaseResponse;
import com.doumee.biz.zbom.model.crm.response.CRMCustomerListResponse;
import com.doumee.biz.zbom.model.crm.response.CRMDaogouBindListResponse;
import com.doumee.core.constants.ResponseStatus;
import com.doumee.core.exception.BusinessException;
import com.doumee.core.utils.Constants;
import com.doumee.core.utils.DateUtil;
import com.doumee.core.utils.HttpsUtil;
import com.doumee.dao.business.CrmInterfaceLogMapper;
import com.doumee.dao.business.CustomerLogMapper;
import com.doumee.dao.business.model.CrmInterfaceLog;
import com.doumee.dao.business.model.CustomerLog;
import com.doumee.dao.business.model.Member;
import com.doumee.dao.business.model.Users;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Base64Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
 
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
 
/**
 * 志邦CRM客户信息提交接口
 * @author 江蹄蹄
 * @date 2023/11/30 15:33
 */
@Service
@Slf4j
public class ZbomCRMServiceImpl implements ZbomCRMService {
 
    @Autowired
    private CustomerLogMapper customerLogMapper;
    @Autowired
    private CrmInterfaceLogMapper crmInterfaceLogMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private SystemDictDataBiz systemDictDataBiz;
 
 
 
    /**
     * 志邦客户信息提交接口
     * @param customerLog
     * @return
     */
    @Override
    @Async
    public void dealCustomerLogData(CustomerLog customerLog){
        if(StringUtils.isBlank(customerLog.getPhone())){
            return;
        }
        CrmCustomerInfoRequest entity = new CrmCustomerInfoRequest();
        entity.setId(customerLog.getId());
        entity.setName(customerLog.getName());
        entity.setPhone(zbomEncode(customerLog.getPhone()));
        entity.setAreaname(customerLog.getAreaName());
        entity.setAreacode(customerLog.getAreaCode());
        entity.setOpenid(customerLog.getOpenid());
//        提交类型 0-测试装修风格;1-0元定制;2装修计算器
        if(Constants.equalsInteger(customerLog.getType(),Constants.ONE)){
            entity.setSource(CRMConstants.CRM_SOURCE.SOURCE_MP01);
            entity.setChannel(CRMConstants.CRM_SOURCE.SOURCE_MP01+"00");
        }else{
            entity.setSource(CRMConstants.CRM_SOURCE.SOURCE_MP02);
            entity.setChannel(CRMConstants.CRM_SOURCE.SOURCE_MP02+"00");
        }
//        entity.setOpenId(customerLog.getOpenid());
        entity.setOpenid(customerLog.getOpenid());
        entity.setDate(DateUtil.dateToString(customerLog.getCreateDate(),"yyyy/MM/dd HH:mm"));
        CrmCustomerPostRequest obj = new CrmCustomerPostRequest();
        obj.setCusInfo(new ArrayList<>());
        obj.getCusInfo().add(entity);
        int status ;
        String crmInfo;
        String param = JSONObject.toJSONString(obj);
        CRMBaseResponse result = sendCusHttpRequest(CRMConstants.IntegerUrl.POST_CUS_DATA_URL,CRMConstants.IntegerName.POST_CUS_DATA_NAME,param);
        if (result != null && (StringUtils.equalsIgnoreCase(result.getCode(), CRMConstants.CODE_SUCCESS))) {
            status = 1;
            crmInfo="提交成功";
        }else{
            status = 2;
            crmInfo="提交失败["+ result!=null?result.getMsg():"接口请求失败!"+"]";
        }
        customerLogMapper.update(null,new UpdateWrapper<CustomerLog>().lambda()
                .eq(CustomerLog::getId,entity.getId())
                .set(CustomerLog::getCrmStatus,Constants.ONE )
                .set(CustomerLog::getCrmInfo,crmInfo )
                .set(CustomerLog::getCrmDate,new Date() ));// 更新状态
    }
    /**
     * 获取导购绑定列表
     * @param entity
     * @return
     */
    @Override
    public  CRMBaseResponse<List<CRMDaogouBindListResponse>> getDaogouBindList(CrmDaogouBindListRequest entity ){
        int status ;
        String crmInfo;
        String param = JSONObject.toJSONString(entity);
        CRMBaseResponse<List<CRMDaogouBindListResponse>> result = sendHttpRequest(CRMConstants.IntegerUrl.DAOGOU_BIND_LIST_URL,
                CRMConstants.IntegerName.DAOGOU_BIND_LIST_NAME,
                param,
                new TypeReference<CRMBaseResponse<List<CRMDaogouBindListResponse>>>(){});
        return result;// 默认失败
    }
 
    /**
     * 获取客户列表
     * @param entity
     * @return
     */
    @Override
    public CRMBaseResponse<List<CRMCustomerListResponse>> getCustomerList(CrmCustomerListRequest entity ){
        int status ;
        String crmInfo;
        String param = JSONObject.toJSONString(entity);
        CRMBaseResponse<List<CRMCustomerListResponse>> result = sendHttpRequest(CRMConstants.IntegerUrl.CUS_BEFORE_PAGE_LIST_URL
                ,CRMConstants.IntegerName.CUS_BEFORE_PAGE_LIST_NAME
                ,param
                ,new TypeReference<CRMBaseResponse<List<CRMCustomerListResponse>>>(){});
        return result;// 默认失败
    }
 
    public   <T> CRMBaseResponse<T> sendCusHttpRequest(String interfaceUrl,  String name,  String param){
        log.info("【"+name+"】================开始===="+ JSONObject.toJSONString(param));
        String appKey = (String) redisTemplate.opsForValue().get(Constants.RedisKeys.ZBOM_CRM_POSTCUS_API_KEY);
        String url = redisTemplate.opsForValue().get(Constants.RedisKeys.ZBOM_CRM_API_URL) + interfaceUrl ;
        long _t = System.currentTimeMillis();
        if (StringUtils.isNotBlank(appKey)||StringUtils.isNotBlank(url)) {
            String res = null;
            int success = 0;
            try {
                url += "?type=postCusData&_t=" + _t + "&token=" + DigestUtils.md5Hex( "postCusData" + _t + appKey);
                Map<String,String> headers = new HashMap<>();
                res = HttpsUtil.postJson(url,param);
                TypeReference typeReference =
                        new TypeReference<CRMBaseResponse<T>>(){};
                CRMBaseResponse<T>  result = JSONObject.parseObject(res, typeReference.getType());
                logResult(result,name);
                if(StringUtils.equals(result.getCode(),CRMConstants.CODE_SUCCESS)){
                    return  result;
                }else{
                    success =1;
                }
            }catch (Exception e){
                success = 1;
                log.error("【"+name+"】================失败===="+ JSONObject.toJSONString(param));
            }finally {
                saveInterfaceLog(url,name,param,success,res);
            }
        }
        return  null;
    }
    public   <T> CRMBaseResponse<T> sendHttpRequest(String interfaceUrl,  String name,  String param,TypeReference<CRMBaseResponse<T>> typeReference){
        log.info("【"+name+"】================开始===="+ JSONObject.toJSONString(param));
        String appKey = (String) redisTemplate.opsForValue().get(Constants.RedisKeys.ZBOM_CRM_API_KEY);
        String url = redisTemplate.opsForValue().get(Constants.RedisKeys.ZBOM_CRM_API_URL) + interfaceUrl ;
        long _t = System.currentTimeMillis();
        if (StringUtils.isNotBlank(appKey)||StringUtils.isNotBlank(url)) {
            String res = null;
            int success = 0;
            try {
                url += "?timestamp=" + _t + "&sign=" + DigestUtils.md5Hex( _t + appKey);
                Map<String,String> headers = new HashMap<>();
                res = HttpsUtil.postJson(url,param);
                CRMBaseResponse<T>  result = JSONObject.parseObject(res, typeReference.getType());
                logResult(result,name);
                if(StringUtils.equals(result.getCode(),CRMConstants.CODE_SUCCESS)){
                    return  result;
                }else{
                    success =1;
                }
            }catch (Exception e){
                success = 1;
                log.error("【"+name+"】================失败===="+ JSONObject.toJSONString(param));
            }finally {
                saveInterfaceLog(url,name,param,success,res);
            }
        }
        return  null;
    }
    private static void logResult(CRMBaseResponse res,String name) {
        if(StringUtils.equals(res.getCode(), CRMConstants.CODE_SUCCESS)){
            log.info("【CRM接口:"+name+"】================成功====\n"+res);
        }else{
            log.error("【CRM接口:"+name+"】================失败====:\n"+ res);
        }
    }
    public  void  saveInterfaceLog(String url,String name,String  param,Integer success,String respone){
            if(crmInterfaceLogMapper ==null){
                return;
            }
            CrmInterfaceLog log = new CrmInterfaceLog();
            log.setCreateDate(new Date());
            log.setUrl(url);
            log.setEditDate(log.getCreateDate());
            log.setPlat(Constants.ZERO);
            log.setName(name);
            log.setIsdeleted(Constants.ZERO);
            log.setRequest(param);
            log.setType(Constants.ONE);
            log.setSuccess(success);
            log.setRepose(respone);
            crmInterfaceLogMapper.insert(log);
    }
 
    /**
     * 志邦字符串加密
     * @param str
     * @return
     */
 
    @Override
    public   String zbomEncode(String str)  {
        StringBuffer sb = new StringBuffer();
        String result = null;
        try {
            // 创建StringBuffer对象用来操作字符串
            String  urlStr =  (String) redisTemplate.opsForValue().get(Constants.RedisKeys.ZBOM_ENCODE_URL);
            sb = new StringBuffer(
                    urlStr + "?code=" + URLEncoder.encode(str, "UTF-8") + "&type=0&numstr=wy?");
            result = HttpsUtil.sendGet(sb.toString());
 
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            saveInterfaceLog(sb.toString(),"志邦字符串加密接口",str, result==null?1:0,result );
        }
        return  result;
    }
 
    /**
     * 跳转crm功能 获取授权地址
     * http://localhost:8080/core/oauth/authorize/jump?timestamp=1719998741&sign=41fbeb13965c43916876db7b5799e8ac&agent_phone_number=199077&bindKey=mp
     * @param userName
     * @return
     */
    @Override
    public    String getCrmGoUrl(String userName,Integer type,String iamId){
        try {
            // 创建StringBuffer对象用来操作字符串
            int _t = (int)(System.currentTimeMillis());
            String pageKey ="mp";//客户列表页面码
            String fileUrl = systemDictDataBiz.queryByCode(Constants.ZBOM,Constants.ZBOM_CRM_API_URL_MP).getCode();
            if(Constants.equalsInteger(type,Constants.ONE)){
                pageKey = "mpAddIntention";//新增意向页面码
                fileUrl = systemDictDataBiz.queryByCode(Constants.ZBOM,Constants.ZBOM_CRM_API_URL_MP_ADDINTENTION).getCode();
            }
            String  url =   redisTemplate.opsForValue().get(Constants.RedisKeys.ZBOM_CRM_API_URL)
                    + CRMConstants.IntegerUrl.GO_CRM_AUTH_URL
                    + "?bindKey="+pageKey
                    + "&tick=" + this.getTick(iamId, fileUrl);
            return url;
        }catch (Exception e){
            e.printStackTrace();
        }
       throw  new BusinessException(ResponseStatus.DATA_EMPTY.getCode(),"获取跳转地址失败哦!");
    }
 
    public String getTick(String iamId, String fileUrL) throws UnsupportedEncodingException {
        Map<String,Object> map = new HashMap<>();
        //用户IAM主键
        map.put("ssouserid",iamId);
        //售前小程序appid
        map.put("appid",systemDictDataBiz.queryByCode(Constants.ZBOM,Constants.ZBOM_IAM_BUSINESS_APPID).getCode());
        //跳转地址
        map.put("rediUrl",fileUrL);
        //时间戳
        map.put("timestamp",System.currentTimeMillis()/1000+"");
        //C端小程序appid
        map.put("sourceappid",systemDictDataBiz.queryByCode(Constants.ZBOM,Constants.ZBOM_IAM_CUSTOMER_APPID).getCode());
        System.out.println(JSONObject.toJSONString(map));
        //获取tick
        String tick = ZbomCRMServiceImpl.encrypt(
                systemDictDataBiz.queryByCode(Constants.ZBOM,Constants.ZBOM_CRM_API_URL_PRIVATE_KEY).getCode()
                ,JSONObject.toJSONString(map)
                ,systemDictDataBiz.queryByCode(Constants.ZBOM,Constants.ZBOM_CRM_API_URL_INIT_VECTOR).getCode());
 
        String tickEncoder = URLEncoder.encode(tick,"UTF-8");
 
        return tickEncoder;
    }
 
 
    public static String encrypt(String key, String value,String initVector) {
        try {
            IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
            SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            byte[] encrypted = cipher.doFinal(value.getBytes());
            return Base64Utils.encodeToString(encrypted);
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }
 
 
}