xinyb
2024-07-11 8b55156d7d8b0af9eafe8302fe0dcde31ac0e053
提交 | 用户 | age
a6a76f 1 package com.yc.sdk.miniapp.action;
F 2
3 import cn.binarywang.wx.miniapp.api.WxMaService;
4 import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
5 import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
6 import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
7 import com.google.gson.JsonArray;
8 import com.google.gson.JsonObject;
9 import com.yc.action.BaseAction;
b0744c 10 import com.yc.action.login.LoginAction;
a6a76f 11 import com.yc.entity.DataSourceEntity;
b0744c 12 import com.yc.entity.UserAccountEntity;
a6a76f 13 import com.yc.entity.attachment.AttachmentEntity;
F 14 import com.yc.entity.attachment.AttachmentWhereEntity;
2e95e7 15 import com.yc.factory.FactoryBean;
a6a76f 16 import com.yc.multiData.MultiDataSource;
F 17 import com.yc.multiData.SpObserver;
18 import com.yc.sdk.miniapp.service.MaUserIfc;
19 import com.yc.sdk.shopping.entity.CustomerEntity;
20 import com.yc.sdk.shopping.entity.SettingEntity;
21 import com.yc.sdk.shopping.service.SettingIfc;
22 import com.yc.sdk.shopping.service.department.DepartmentIfc;
2e95e7 23 import com.yc.sdk.shopping.service.imagedata.ShoppingImageDataIfc;
a6a76f 24 import com.yc.sdk.shopping.service.order.OrderIfc;
F 25 import com.yc.sdk.shopping.service.register.AccountIfc;
26 import com.yc.sdk.shopping.util.SettingKey;
27 import com.yc.sdk.weixincp.entity.MyWxCpUser;
28 import com.yc.sdk.weixincp.service.ERPUserIfc;
29 import com.yc.sdk.weixincp.util.AvatarFile;
30 import com.yc.sdk.weixincp.util.RandomString;
31 import com.yc.sdk.weixinmp.action.MpServiceInit;
32 import com.yc.sdk.weixinmp.entity.MyWxMpUser;
33 import com.yc.sdk.weixinopen.entity.TabBarEntity;
34 import com.yc.sdk.weixinopen.service.MiniAppCodeIfc;
35 import com.yc.service.upload.AttachmentIfc;
2e95e7 36 import com.yc.utils.FileUtil;
a6a76f 37 import com.yc.utils.SessionKey;
b0744c 38 import me.chanjar.weixin.common.error.WxErrorException;
F 39 import me.chanjar.weixin.open.api.WxOpenService;
2e95e7 40 import org.apache.commons.io.FileUtils;
b0744c 41 import org.apache.commons.lang3.StringUtils;
F 42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44 import org.springframework.beans.factory.annotation.Autowired;
45 import org.springframework.dao.DataAccessException;
46 import org.springframework.stereotype.Controller;
47 import org.springframework.web.bind.annotation.GetMapping;
48 import org.springframework.web.bind.annotation.RequestMapping;
2e95e7 49 import org.springframework.web.multipart.MultipartFile;
J 50 import org.springframework.web.multipart.MultipartHttpServletRequest;
b0744c 51 import redis.clients.jedis.Jedis;
F 52 import redis.clients.jedis.JedisPool;
53
54 import javax.servlet.http.HttpServletRequest;
55 import javax.servlet.http.HttpServletResponse;
56 import javax.servlet.http.HttpSession;
57 import java.io.File;
2e95e7 58 import java.io.IOException;
b0744c 59 import java.util.List;
a6a76f 60
F 61 /**
62  * 微信小程序用户接口
63  *
64  * @author <a href="https://github.com/binarywang">Binary Wang</a>
65  */
66 @Controller
67 @RequestMapping("/wx/miniapp/user/")
68 public class WxMaUserController extends BaseAction{
69     private final Logger logger = LoggerFactory.getLogger(this.getClass());
70
71     //@Autowired
72     //private WxMaService wxService;
73     @Autowired 
74     private JedisPool jedisPool;
75     @Autowired
76     AccountIfc accountIfc;
77     //public final static String SESSION_KEY = "session_key:" ;
78     @Autowired
79     MaUserIfc maUserIfc ;
80     @Autowired
81     DepartmentIfc departmentIfc ;
82     @Autowired
83     SettingIfc settingIfc;
84     @Autowired
85     ERPUserIfc erpUserIfc;
86     @Autowired
87     OrderIfc orderIfc; 
88     @Autowired
89     MiniAppCodeIfc miniAppCodeIfc ;
90     @Autowired
91     private AttachmentIfc attachmentIfc;
b0744c 92     @Autowired
F 93     LoginAction loginAction;
2e95e7 94     @Autowired
J 95     ShoppingImageDataIfc imgData;
96     
a6a76f 97     @GetMapping("/getSessionId.do")
F 98     public void getSessionId(HttpServletRequest request, HttpServletResponse response) {
99         HttpSession session=request.getSession();
100         JsonObject json = new JsonObject();
101         //JsonObject errJson = new JsonObject();
102         json.addProperty("JSESSIONID", session.getId());
103         this.printJson(response, json.toString());
104         return;    
105     }
106     
107     /**
108      * 登陆接口
109      */
110     //@RequestMapping("/wx/miniapp/user/login.do")
111     @GetMapping("/login.do")
112     public void login(String code,HttpServletRequest request, HttpServletResponse response) {
113         HttpSession session=request.getSession();
114         //Map<String,String> map = new HashMap<String,String>() ;
115         String sessionId = session.getId();
116         JsonObject json = new JsonObject();
117         JsonObject errJson = new JsonObject();
118         
119         if (StringUtils.isBlank(code)) {
120             errJson.addProperty("warning", "必须传递 code 参数"+"【/login.do】");
121             json.add("error", errJson);
122             this.printJson(response, json.toString());
123             return;    
124         }
125         String fromUserId = request.getParameter(SettingKey.FROMUSERID) ;
c05864 126         String fromUserRowId = request.getParameter(SettingKey.FROMUSERROWID) ;
a6a76f 127         String corpId = request.getParameter(SessionKey.WEIXIN_CORPID) ;
F 128         if (corpId == null || "".equals(corpId)) {
129             corpId = request.getParameter(SessionKey.WEIXIN_APPID) ;
130         }
131         if (corpId == null || "".equals(corpId)) {
132             corpId = (String) session.getAttribute(SessionKey.WEIXIN_CORPID);
133         }
134         if (corpId == null || "".equals(corpId)) {
135             errJson.addProperty("warning","必须传递 AppId 参数【/login.do】");
136             json.add("error", errJson);
137             this.printJson(response, json.toString());
138             return;    
139         }
140         String sceneCode = request.getParameter("SceneCode") ;   //小程序入口
141         String fromOpenId = request.getParameter(SettingKey.FROMOPENID) ;
142         
ad9fb8 143         DataSourceEntity corpEntity ;
J 144         try {
145             corpEntity =  MultiDataSource.getDataSourceMapByMaAppId(corpId);
146             if (corpEntity == null  ) {
147                 errJson.addProperty("warning","在数据源中没有找到该小程序的 AppId 参数设置,传递 AppId 【"+ corpId +"】参数不正确!【/login.do】");
148                 json.add("error", errJson);
149                 this.printJson(response, json.toString());
150                 return;    
151             }
152             if (SpObserver.isDemoInstance("_"+corpEntity.getDbId() )) {
153                 errJson.addProperty("warning", "未找到数据源【"+ corpEntity.getDbId() +"】【CorpId:"+ corpId+ "】,请在数据源中设置好【/login.do】");
154                 json.add("error", errJson);
155                 this.printJson(response, json.toString());
156                 return;    
157             }
158         }catch (Exception e) {
159             e.printStackTrace();
160             errJson.addProperty("warning",(e.getCause()!=null?e.getCause().getMessage(): e.getMessage())+"【/login.do】");
a6a76f 161             json.add("error", errJson);
F 162             this.printJson(response, json.toString());
ad9fb8 163             return;            
a6a76f 164         }
F 165         try (Jedis jedis = this.jedisPool.getResource()){
166             SpObserver.setDBtoInstance("_"+corpEntity.getDbId());//切换数据源
167             session.setAttribute(SessionKey.WEIXIN_CORPID, corpId);
168             
169             //String hostUrl = SettingKey.getHostUrl(request) ;
170             //DataSourceEntity corpEntity = MultiDataSource.getDataSourceMapByCorpURL(hostUrl) ;
171
172             /*  未托管时写法 
173             final WxMaService wxService = MaServiceInit.getWxMaService(corpEntity, jedisPool);
174             if (wxService == null) {
175                 throw new IllegalArgumentException(String.format("未找到对应appid的配置,请核实!"));
176             }
177             WxMaJscode2SessionResult result = wxService.getUserService().getSessionInfo(code);
178             */
179             
180             //第三方托管方式写法 
181             WxOpenService wxOpenService = MpServiceInit.getWxOpenService();
182             WxMaJscode2SessionResult result = wxOpenService.getWxOpenComponentService().miniappJscode2Session(corpEntity.getMiniAppId(), code);
183             
184 //            try {
185 //                SpObserver.setDBtoInstance("_"+corpEntity.getDbId());//切换数据源
186 //                T110203Entity customerEntity = accountIfc.getLoginInfoByOpenId(result.getOpenid());
187 //            }catch (Exception e) {
188 //                throw e  ;
189 //            }finally{
190 //                SpObserver.setDBtoInstance();
191 //            }
192             
193           //保存到会话
194             session.setAttribute(SessionKey.SHOPPING_DBID,corpEntity.getDbId() + "") ;
195             session.setAttribute(SessionKey.WEIXIN_FROM,"3") ;  //小程序为 3 
196             session.setAttribute(SessionKey.WEIXIN_CORPID,corpEntity.getMiniAppId()) ;
197             session.setAttribute(SessionKey.WEIXIN_OPENID,result.getOpenid()) ;
7b4b85 198             
a6a76f 199             //json.addProperty(SessionKey.WEIXIN_OPENID, result.getOpenid());   //这里不需要了,在 loginByOpenId  程序里面已经有处理 
F 200             //json.addProperty("JSESSIONID", session.getId());    //这里不需要了,在 loginByOpenId  程序里面已经有处理 
201             
202             //System.out.println(this.getClass()+ " sessionid:" + session.getId() + ",openid:" + result.getOpenid() + " sessionKey:" + result.getSessionKey()+",unionId:"+result.getUnionid());
203             
ad9fb8 204             // MyWxMpUser myWxMpUser = maUserIfc.getUser(result.getOpenid()) ;   //要放到  maUserIfc.saveUserOpenId()  前执行 ,主要检查是否存在 该 小程序用户信息,如果不存在,则需要拉取 
a6a76f 205             
F 206             //保存  openid 
c05864 207              MyWxMpUser myWxMpUser = maUserIfc.saveUserOpenId(result.getOpenid(),fromUserId,fromUserRowId,sessionId,sceneCode,fromOpenId) ;
a6a76f 208             
F 209             //保存 SessionKey,写入redis ,等 /info.do 调用 
210             jedis.set(SettingKey.SESSIONKEY.concat(":"+corpEntity.getMiniAppId()).concat(":"+result.getOpenid()), result.getSessionKey());
211             
c05864 212             request.setAttribute(SettingKey.FROMUSERID, myWxMpUser.getFromUserId());
a6a76f 213             //ERP登录,设置 session 需要用到的变量给 商城 使用 
22907b 214              loginByOpenId(result.getOpenid(),(myWxMpUser != null&&myWxMpUser.isPullUserInfo() ? true:false) ,result.getSessionKey(),myWxMpUser,request,  response) ;
a6a76f 215
F 216              //this.printJson(response, json.toString());   //这里不需要了,在 loginByOpenId  程序里面已经有处理 
217             return;    
218             //return JsonUtils.toJson(session);
219         } catch (WxErrorException e) {
220             e.printStackTrace();
221             this.logger.error(e.getMessage(), e);
222             String msg = "" ;
223             if (e.getError().getErrorCode() == 61005) {   //61005  component ticket is expired 
224                 msg = "微信错误代码:"+e.getError().getErrorCode()+",错误说明:"+ e.getError().getErrorMsg() + ",请等5分钟再试【/login.do】" ;
225             }else {
226                 msg = "微信错误代码:"+e.getError().getErrorCode()+",错误说明:"+ e.getError().getErrorMsg() + "【/login.do】";
227             }
228             errJson.addProperty("warning",msg);
229             json.add("error", errJson);
230             this.printJson(response, json.toString());
231             return;    
232         }catch (Exception e) {
233             e.printStackTrace();
234             errJson.addProperty("warning",(e.getCause()!=null?e.getCause().getMessage(): e.getMessage())+"【/login.do】");
235             json.add("error", errJson);
236             this.printJson(response, json.toString());
237             return;            
238         }finally {
239             SpObserver.setDBtoInstance();
240         }
241     }
242
243     /**
244      * <pre>
245      * 获取用户信息接口
246      * </pre>
247      */
248     @GetMapping("/info.do")
249     public void info(String signature, String rawData, String encryptedData, String iv,
250             HttpServletRequest request, HttpServletResponse response) {
251         HttpSession session=request.getSession();
252         String fromUserId = request.getParameter(SettingKey.FROMUSERID) ;
253         
254         JsonObject json = new JsonObject();
255         JsonObject errJson = new JsonObject();
256         
257         String corpId = request.getParameter(SessionKey.WEIXIN_CORPID) ;
258         if (corpId == null || "".equals(corpId)) {
259             corpId = request.getParameter(SessionKey.WEIXIN_APPID) ;
260         }
261         if (corpId == null || "".equals(corpId)) {
262             corpId = (String) session.getAttribute(SessionKey.WEIXIN_CORPID);
263         }
264         
265         if (corpId == null || "".equals(corpId)) {
266             corpId = (String) session.getAttribute(SessionKey.WEIXIN_CORPID);
267         }
268         
269         
270         
271         if (corpId == null || "".equals(corpId)) {
272             errJson.addProperty("warning","必须传递 AppId 参数【/info.do】");
273             json.add("error", errJson);
274             this.printJson(response, json.toString());
275             return;    
276         }
277         
278         DataSourceEntity corpEntity = null ;
279         try {
280             corpEntity =  MultiDataSource.getDataSourceMapByMaAppId(corpId);
281         
282             if (corpEntity == null  ) {
283                 errJson.addProperty("warning","在数据源中没有找到该小程序的 AppId 参数设置,传递 AppId 【"+ corpId +"】参数不正确!【/info.do】");
284                 json.add("error", errJson);
285                 this.printJson(response, json.toString());
286                 return;    
287             }
288             
289             if (SpObserver.isDemoInstance("_"+corpEntity.getDbId() )) {
290                 errJson.addProperty("warning", "未找到数据源【"+ corpEntity.getDbId() +"】【CorpId:"+ corpId+ "】,请在数据源中设置好【/info.do】");
291                 json.add("error", errJson);
292                 this.printJson(response, json.toString());
293                 return;    
294             }
295             
296             session.setAttribute(SessionKey.WEIXIN_CORPID, corpId);
297             session.setAttribute(SessionKey.WEIXIN_APPID, corpId);
298         }catch (Exception e) {
299             e.printStackTrace();
300             errJson.addProperty("warning",e.getCause()!=null?e.getCause().getMessage(): e.getMessage()+"【/info.do】");
301             json.add("error", errJson);
302             this.printJson(response, json.toString());
303             return;    
304         }
305             
306         //String hostUrl = SettingKey.getHostUrl(request) ;
307         //DataSourceEntity corpEntity = MultiDataSource.getDataSourceMapByCorpURL(hostUrl) ;
308         //Map<String,String> map = new HashMap<String,String>() ;
309         //System.out.println(this.getClass()+ " sessionId:"+ session.getId()+ ",sessionKey:" + sessionKey );
310         /*
311         final WxMaService wxService = MaServiceInit.getWxMaService(corpEntity, jedisPool);
312         if (wxService == null) {
313             throw new IllegalArgumentException(String.format("未找到对应appid的配置,请核实!"));
314         }
315         */
316         
317         
318         //第三方托管方式写法 
319         WxMaService wxService = null;
320         try {
321             wxService = MaServiceInit.getWxMaServiceByOpenComponentByAppId(corpEntity.getMiniAppId()) ;
322             if (wxService==null) {
323                 errJson.addProperty("warning","在数据源中没有找到该小程序的 AppId 参数设置(WxMaService),可能传递 AppId 【"+ corpId +"】参数不正确!【/info.do】");
324                 json.add("error", errJson);
325                 this.printJson(response, json.toString());
326                 return;    
327             }
328         }catch (Exception e) {
329             e.printStackTrace();
330             errJson.addProperty("warning",e.getCause()!=null?e.getCause().getMessage(): e.getMessage()+"【/info.do】");
331             json.add("error", errJson);
332             this.printJson(response, json.toString());
333             return;    
334         }
335         String openId = (String)session.getAttribute(SessionKey.WEIXIN_OPENID);
336         
337        try (Jedis jedis = this.jedisPool.getResource()){
338            SpObserver.setDBtoInstance("_"+corpEntity.getDbId());//切换数据源
339                String sessionKey = jedis.get(SettingKey.SESSIONKEY.concat(":"+corpEntity.getMiniAppId()).concat(":"+openId));
340                if (sessionKey == null || "".equals(sessionKey)) {
341                    sessionKey = request.getParameter(SettingKey.SESSIONKEY) ;
342                }
343                if (sessionKey == null || "".equals(sessionKey)) {
344                 errJson.addProperty("warning", "获取会话信息sessionKey失败,导致无法解密获取的用户信息,可能原因是会话已过期,请强制退出微信然后再重试【/wx/miniapp/user/info.do】");
345                 json.add("error", errJson);
346                 this.printJson(response, json.toString());
347                 return;
348             }
349                if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
350                    errJson.addProperty("warning","user check failed【/info.do】");
351                    json.add("error", errJson);
352                    this.printJson(response, json.toString());
353                    return;        
354                }
355            
356            // 用户信息校验
357            
358            
359            //String unionId = (String)session.getAttribute(SessionKey.WEIXIN_MINIAPP_UNIONID);
360           // WxMpUser erpWxMPUser = null ;
361            
362            
363            
364            // 解密用户信息
365            WxMaUserInfo wxMaUserInfo = wxService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
366           
22907b 367            MyWxMpUser myWxMpUser = maUserIfc.saveUser(openId, wxMaUserInfo, request,fromUserId,true);
a6a76f 368                       
F 369            //ERP登录,设置 session 需要用到的变量给 商城 使用 
22907b 370            loginByOpenId(openId,false, sessionKey,myWxMpUser,request,  response) ;
a6a76f 371            
F 372     
373        }catch(DataAccessException e ) {
374             e.printStackTrace();
375             errJson.addProperty("warning",(e.getCause()!=null?e.getCause().getMessage(): e.getMessage())+"【/info.do】");
376             json.add("error", errJson);
377             this.printJson(response, json.toString());
378             return;    
379         
380         } catch (Exception e) {
381             e.printStackTrace();
382             
383             errJson.addProperty("warning",(e.getCause()!=null?e.getCause().getMessage(): e.getMessage())+"【/info.do】");
384             json.add("error", errJson);
385             this.printJson(response, json.toString());
386             return;        
387             
388         }finally {
389             SpObserver.setDBtoInstance();
390         }
391     }
392
393     @GetMapping("/loginByOpenId.do")
22907b 394     public void loginByOpenId (String openId,boolean isPullUserInfo,String mySessionKey,MyWxMpUser myWxMpUser, HttpServletRequest request, HttpServletResponse response) {
a6a76f 395         HttpSession session=request.getSession();
F 396         JsonObject json = new JsonObject();
397         JsonObject errJson = new JsonObject();
398         String fromUserId = request.getParameter(SettingKey.FROMUSERID) ;
c05864 399         if (fromUserId == null||"".equals(fromUserId)) {
J 400             fromUserId = (String) request.getAttribute(SettingKey.FROMUSERID);
401         }
402         
403         if ((fromUserId == null||"".equals(fromUserId)) && myWxMpUser != null) {
404             fromUserId = myWxMpUser.getFromUserId();
405         }
a6a76f 406         
F 407         String corpId = request.getParameter(SessionKey.WEIXIN_CORPID) ;
408         if (corpId == null || "".equals(corpId)) {
409             corpId = request.getParameter(SessionKey.WEIXIN_APPID) ;
410         }
411         if (corpId == null || "".equals(corpId)) {
412             corpId = (String) session.getAttribute(SessionKey.WEIXIN_CORPID);
413         }
414         
415         if (corpId == null || "".equals(corpId)) {
416             errJson.addProperty("warning","必须传递 AppId 参数【/loginByOpenId.do】");
417             json.add("error", errJson);
418             this.printJson(response, json.toString());
419             return;    
420         }
421         
422         DataSourceEntity corpEntity = null ;
423         try {
424             corpEntity =  MultiDataSource.getDataSourceMapByMaAppId(corpId);
425             if (corpEntity == null  ) {
426                 errJson.addProperty("warning","在数据源中没有找到该小程序的 AppId 参数设置,传递 AppId 【"+ corpId +"】参数不正确!【/loginByOpenId.do】");
427                 json.add("error", errJson);
428                 this.printJson(response, json.toString());
429                 return;    
430             }
431             if (SpObserver.isDemoInstance("_"+corpEntity.getDbId() )) {
432                 errJson.addProperty("warning", "未找到数据源【"+ corpEntity.getDbId() +"】【CorpId:"+ corpId+ "】,请在数据源中设置好【/loginByOpenId.do】");
433                 json.add("error", errJson);
434                 this.printJson(response, json.toString());
435                 return;    
436             }
437             session.setAttribute(SessionKey.WEIXIN_CORPID, corpId);
438         } catch (Exception e) {
439             e.printStackTrace();
440             
441             errJson.addProperty("warning",(e.getCause()!=null?e.getCause().getMessage(): e.getMessage())+"【/loginByOpenId.do】");
442             json.add("error", errJson);
443             this.printJson(response, json.toString());
444             return;        
445         }
446         
447         //String hostUrl = SettingKey.getHostUrl(request) ;
448         //DataSourceEntity corpEntity = MultiDataSource.getDataSourceMapByCorpURL(hostUrl) ;
d8f266 449         String keFuTelephone = "";
a6a76f 450         try {
F 451                SpObserver.setDBtoInstance("_"+corpEntity.getDbId());//切换数据源
22907b 452                SettingEntity settingEntity = settingIfc.getSettingEntity(request) ;
a6a76f 453
F 454                // GroupId : 0 未分组 , 1 黑名单 , 2 星标组
ad9fb8 455                 if (myWxMpUser != null &&  myWxMpUser.getGroupId() != null && myWxMpUser.getGroupId() == 1 ) {
J 456                     errJson.addProperty("warning","您的微信账号【" + myWxMpUser.getNickname()+"】已经被禁用,禁止访问!【/loginByOpenId.do】");
a6a76f 457                     json.add("error", errJson);
F 458                     this.printJson(response, json.toString());
459                     return;    
460                 }
461                 //获取导购信息用于发送AI雷达提示消息 
462                 MyWxCpUser wxCpUser =  maUserIfc.getSendAIMessageUser( fromUserId, corpEntity.getSystemDescribe(), openId) ;
463                 if (wxCpUser != null) {
464                     maUserIfc.updateLastUserIdAndShopCcCode(wxCpUser.getUserId(),wxCpUser.getShopCcCode(),openId);
465                     session.setAttribute(SettingKey.FROMUSERID,wxCpUser.getUserId());
466                     session.setAttribute(SettingKey.FROMUSERNAME,wxCpUser.getName());
d8f266 467                     keFuTelephone = wxCpUser.getKeFuTelephone();
a6a76f 468                 }
F 469                 //String userId = maUserIfc.getFromUserId(fromUserId,corpEntity.getSystemDescribe(),openId) ;
470                 //json.addProperty("UserId", userId==null?"":userId);
471                 
472                 //测试该用户是否导购员
473                 boolean isShopGuide = false ; 
474                 if (settingEntity.isStartupLeagueShopCcCode()) {
475                     isShopGuide = maUserIfc.isShopGuide(openId) ;
476                 }else {
477                     String openIds = orderIfc.getOpenIdsFromSalesOrderNoticeTemplated(null,120230,true,120230) ;
478                     if (openIds !=null) {
479                         String shopGuideOpenId[] = openIds.split(";") ;
480                         for (int i=0;i < shopGuideOpenId.length;i++) {
481                             if (openId.equals(shopGuideOpenId[i])) {
482                                 isShopGuide = true ;
483                                 break ;
484                             }
485                         }
486                     }
487                 }
488                 session.setAttribute(SettingKey.isShopGuide,isShopGuide);
489                 json.addProperty(SettingKey.isShopGuide,isShopGuide);  //该用户是否导购员
490                 
491 //                MyWxCpUser wxCpUser = null ;
492 //                if (erpWxMPUser!=null && erpWxMPUser.getTel()!=null && !"".equals(erpWxMPUser.getTel())) {
493 //                    wxCpUser = erpUserIfc.getWorkAppUserByTelephone(erpWxMPUser.getTel());
494 //                }
495                 
496                 json.addProperty("UserId", wxCpUser!=null ? wxCpUser.getUserId():"");  //该导购员 userid
497                 json.addProperty("UserName", wxCpUser!=null ? wxCpUser.getName():"");  //该导购员 name
498                 
499                 //再次取数,以获取最新的 介绍人和姓名,因为在 maUserIfc.updateLastUserId(wxCpUser.getUserId(),openId) 可能更新介绍人信息
ad9fb8 500                 myWxMpUser = maUserIfc.getUser(openId) ;   
J 501                 json.addProperty(SettingKey.ReferralsType, myWxMpUser.getReferralsType());   //介绍人类别
502                 json.addProperty(SettingKey.ReferralsCode, myWxMpUser.getReferralsCode());   //介绍人编号
503                 json.addProperty(SettingKey.ReferralsName, myWxMpUser.getReferralsName());   //介绍人姓名
504                 json.addProperty("Telephone", myWxMpUser.getTel());   //电话号码 
d8f266 505                 json.addProperty("KeFuTelephone", keFuTelephone);   //客服电话号码(如果启用多门店,则取门店电话,否则取公司表中的电话) 
J 506                 
a6a76f 507                 
F 508                 CustomerEntity customerEntity = accountIfc.getLoginInfoByMiniAppOpenId(openId);
509                 if (customerEntity != null) {    
510                     //session.setAttribute(SessionKey.USERCODE,customerEntity.getCltCode());
511                     //session.setAttribute(SessionKey.USERNAME,customerEntity.getCltName());
512                     //保存到会话
513                     if (customerEntity.getCltCode() != null && !"".equals(customerEntity.getCltCode())) {
514                         session.setAttribute(SettingKey.CLTCODE, customerEntity.getCltCode());
515                     }else{
516                         session.removeAttribute(SettingKey.CLTCODE);
517                     }
518                     session.setAttribute(SettingKey.CLTNAME, customerEntity.getCltName());
519                     session.setAttribute(SettingKey.CLTTEL, customerEntity.getTel());
520                     session.setAttribute(SettingKey.CLTEMAIL, customerEntity.getEmail());
521                     session.setAttribute(SettingKey.COUNTRY, customerEntity.getCountryZoneId());
522                     session.setAttribute(SettingKey.PROVINCE, customerEntity.getProvinceZoneId());
523                     session.setAttribute(SettingKey.POSTCODE, customerEntity.getPostCode());
524                     
525                     //设置网店,打开页面时,可以确定显示哪个网店的数据,切换成城市时,需要改变这个参数的值
526                     String lastSelectShopCcCode = "" ,lastSelectShopCcName = "" ;
527                     
528                     if (settingEntity.getDefaultShopCcCode()!=null && !"".equals(settingEntity.getDefaultShopCcCode())) {
529                         if (customerEntity.getLastSelectShopCcCode()!= null && !customerEntity.getLastSelectShopCcCode().equals("")
530                             //    &&departmentIfc.hasOpenShoppingByShopCcCode(customerEntity.getLastSelectShopCcCode())  //需要判断网店是否 open 状态 , 注释掉,因为有可能启用了 联盟 功能,注释 by Johns Wang,2020-05-21
531                                 ) {
532                             lastSelectShopCcCode = customerEntity.getLastSelectShopCcCode() ;
533                             lastSelectShopCcName = customerEntity.getLastSelectShopCcName() ;
534                         }else if (customerEntity.getShopCcCode()!= null && !customerEntity.getShopCcCode().equals("")
535                                 //&&departmentIfc.hasOpenShoppingByShopCcCode(customerEntity.getShopCcCode())  //需要判断网店是否 open 状态,注释掉,因为有可能启用了 联盟 功能,注释 by Johns Wang,2020-05-21
536                                 ) {
537                             lastSelectShopCcCode = customerEntity.getShopCcCode() ;
538                             lastSelectShopCcName = customerEntity.getShopCcName() ;
539                         }else {
540                             
541                             lastSelectShopCcCode = settingEntity.getDefaultShopCcCode()==null?"":settingEntity.getDefaultShopCcCode() ;
542                             lastSelectShopCcName = settingEntity.getDefaultShopCcName()==null?"":settingEntity.getDefaultShopCcName() ;
543                         }
544                         session.setAttribute(SettingKey.SHOPCCCODE,lastSelectShopCcCode);
545                         session.setAttribute(SettingKey.SHOPCCNAME,lastSelectShopCcName);
546                     }
547                     
548                     json.addProperty(SettingKey.SHOPCCCODE, lastSelectShopCcCode);  //门店编号 
549                     json.addProperty(SettingKey.SHOPCCNAME, lastSelectShopCcName);   //门店名称 
550                     json.addProperty(SettingKey.ReferralsType, customerEntity.getReferralsType());   //介绍人类别
551                     json.addProperty(SettingKey.ReferralsCode, customerEntity.getReferralsCode());   //介绍人编号
552                     json.addProperty(SettingKey.ReferralsName, customerEntity.getReferralsName());   //介绍人姓名 
553                     
554                     session.setAttribute(SettingKey.SELECTCITYAREAID,customerEntity.getAreaId() ) ;  //保存已经选择的城市
555                     session.setAttribute(SettingKey.MEMBERLEVELDESC,customerEntity.getMemberLevelDesc() ) ;  //会员级别描述
556                     session.setAttribute(SettingKey.SettlementByMonthly,customerEntity.isSettlementByMonthly() ) ;  //是否月结客户
557                 }
558                 
559                 if (settingEntity.isStartupLeagueShopCcCode() && wxCpUser!=null) {
560                     //json.addProperty(SettingKey.ReferralsType, customerEntity.getReferralsType());   //介绍人类别
561                     json.addProperty(SettingKey.ReferralsCode, wxCpUser.getUserId());   //介绍人编号
562                     json.addProperty(SettingKey.ReferralsName, wxCpUser.getName());   //介绍人姓名 
563                 }
564                 
565                 //保存到会话
566                 session.setAttribute(SessionKey.SHOPPING_DBID,corpEntity.getDbId() + "") ;
567                 session.setAttribute(SessionKey.WEIXIN_FROM,"3") ;
568                 session.setAttribute(SessionKey.WEIXIN_CORPID,corpEntity.getMiniAppId()) ;
7b4b85 569                 session.setAttribute(SessionKey.USER_LOGIN_TYPE, SessionKey.USER_LOGIN_TYPE_MINIAPP);//miniapp 小程序类型
J 570                 session.setAttribute(SessionKey.USERCODE,customerEntity!=null?customerEntity.getCltCode():openId) ;
571                 session.setAttribute(SessionKey.USER_NAME,customerEntity!=null?customerEntity.getCltName():myWxMpUser.getNickname());
a6a76f 572                 
ad9fb8 573                 session.setAttribute(SessionKey.WEIXIN_OPENID,myWxMpUser.getOpenId()) ;
J 574                 session.setAttribute(SessionKey.WEIXIN_NICKNAME, myWxMpUser.getNickname()) ;
575                 session.setAttribute(SessionKey.WEIXIN_HEADIMGURL,myWxMpUser.getHeadImgUrl()) ;
a6a76f 576                 
22907b 577                 //保存货币信息
J 578                 session.setAttribute(SettingKey.currency,myWxMpUser.getCurrency()) ;
579                 session.setAttribute(SettingKey.currencyName,myWxMpUser.getCurrencyName()) ;
580                 session.setAttribute(SettingKey.currencySign,myWxMpUser.getCurrencySign()) ;
b0744c 581                 //by danaus 2022/7/26 16:32
F 582                 UserAccountEntity userAccount =new UserAccountEntity();
583                 userAccount.setUserCode(session.getAttribute(SessionKey.USERCODE)+"");
584                 userAccount.setUserName(session.getAttribute(SessionKey.USER_NAME)+"");
585                 loginAction.processLoginUserToSessionV2(request.getRemoteAddr(),corpEntity.getDbId()+"",request,userAccount);
a6a76f 586                 json.addProperty(SessionKey.WEIXIN_OPENID, openId);
F 587                 json.addProperty("JSESSIONID", session.getId());
588                 
ad9fb8 589                 json.addProperty("openId", myWxMpUser.getOpenId());
J 590                 json.addProperty("nickName",myWxMpUser.getNickname() );  //昵称
591                 json.addProperty("language", myWxMpUser.getLanguage());  //语言
a8d792 592                 json.addProperty("city",""); //, myWxMpUser.getCity());  //城市
J 593                 json.addProperty("province",""); //, myWxMpUser.getProvince());   //省份
594                 json.addProperty("country",""); //, myWxMpUser.getCountry());   //国家
ad9fb8 595                 json.addProperty("avatarUrl", myWxMpUser.getHeadImgUrl());   //原始头像 
J 596                 json.addProperty("WeiXinAvatarUnid", myWxMpUser.getWeiXinAvatarUnid());   //头像UNID
597                 json.addProperty("unionId", myWxMpUser.getUnionId());
a6a76f 598                 //json.addProperty("watermark", erpWxMPUser.getWatermark().getAppid());
F 599                 
600                 json.addProperty("isPullUserInfo", isPullUserInfo);    //是否需要拉取用户信息 
d16b1f 601                 //json.addProperty(SettingKey.SESSIONKEY, mySessionKey);   //为了安全,SessionKey 不需要传给小程序前端页面,Modified by Jonns Wang,2022-07-05
a6a76f 602                 json.addProperty("state", "success");
c05864 603                 //json.addProperty(SettingKey.FROMUSERID, fromUserId);  //输出给前端小程序使用,Added by Johns Wang,2022-07-08
a6a76f 604                 
F 605                 //System.out.println( this.getClass() + " : openid:" + openId + " fromUserId:" + fromUserId) ;
606                 //System.out.println( this.getClass() + " : json:" + json.toString()) ;
607                 
608                 List<TabBarEntity> tabBarList = miniAppCodeIfc.getTabBarList(corpEntity.getMiniAppId());
609                 JsonArray tabBarJsonArray = new JsonArray();
610                 for (int i =0 ;tabBarList!= null && i < tabBarList.size();i++) {
611                     tabBarJsonArray.add(tabBarList.get(i).getPathUrl()) ;
612                 }
613                 json.add("tabBarList",tabBarJsonArray) ;
614                 
615                 this.printJson(response, json.toString());
616                 return;    
617          }catch(DataAccessException e ) {
618                 e.printStackTrace();
619                 errJson.addProperty("warning",(e.getCause()!=null?e.getCause().getMessage(): e.getMessage()) + "【/loginByOpenId.do】");
620                 json.add("error", errJson);
621                 this.printJson(response, json.toString());
622                 return;    
623             
624             } catch (Exception e) {
625                 e.printStackTrace();
626                 
627                 errJson.addProperty("warning",(e.getCause()!=null?e.getCause().getMessage(): e.getMessage())+ "【/loginByOpenId.do】");
628                 json.add("error", errJson);
629                 this.printJson(response, json.toString());
630                 return;        
631                 
632             }finally {
633                 SpObserver.setDBtoInstance();
634             }
635     }
636     
637     
638     /**
639      * <pre>
640      * 获取用户绑定手机号信息
641      * </pre>
642      */
643     @GetMapping("/phone.do")
644     public void phone(String signature, String rawData, String encryptedData, String iv,
645             HttpServletRequest request, HttpServletResponse response) {
646         HttpSession session=request.getSession();
647         JsonObject json = new JsonObject();
648         JsonObject errJson = new JsonObject();
649         
650         String corpId = request.getParameter(SessionKey.WEIXIN_CORPID) ;
651         if (corpId == null || "".equals(corpId)) {
652             corpId = request.getParameter(SessionKey.WEIXIN_APPID) ;
653         }
654         if (corpId == null || "".equals(corpId)) {
655             corpId = (String) session.getAttribute(SessionKey.WEIXIN_CORPID);
656         }
657         
658         if (corpId == null || "".equals(corpId)) {
268665 659             errJson.addProperty("warning","必须传递 AppId 参数"+ "【/phone.do】");
a6a76f 660             json.add("error", errJson);
F 661             this.printJson(response, json.toString());
662             return;    
663         }
664         
665         DataSourceEntity corpEntity =  MultiDataSource.getDataSourceMapByMaAppId(corpId);
666         if (corpEntity == null  ) {
268665 667             errJson.addProperty("warning","在数据源中没有找到该小程序的 AppId 参数设置,传递 AppId 【"+ corpId +"】参数不正确!【/wx/miniapp/user/phone.do】");
a6a76f 668             json.add("error", errJson);
F 669             this.printJson(response, json.toString());
670             return;    
671         }
672         if (SpObserver.isDemoInstance("_"+corpEntity.getDbId() )) {
268665 673             errJson.addProperty("warning", "未找到数据源【"+ corpEntity.getDbId() +"】【CorpId:"+ corpId+ "】,请在数据源中设置好【/wx/miniapp/user/phone.do】");
a6a76f 674             json.add("error", errJson);
F 675             this.printJson(response, json.toString());
676             return;    
677         }
678         try (Jedis jedis = this.jedisPool.getResource()){
679             session.setAttribute(SessionKey.WEIXIN_CORPID, corpId);
680             String openId = (String)session.getAttribute(SessionKey.WEIXIN_OPENID);
681             
682             //String hostUrl = SettingKey.getHostUrl(request) ;
683             //DataSourceEntity corpEntity = MultiDataSource.getDataSourceMapByCorpURL(hostUrl) ;
684             String sessionKey = jedis.get(SettingKey.SESSIONKEY.concat(":"+corpEntity.getMiniAppId().concat(":"+openId)));
685             if (sessionKey == null || "".equals(sessionKey)) {
686                    sessionKey = request.getParameter(SettingKey.SESSIONKEY) ;
687                }
688             if (sessionKey == null || "".equals(sessionKey)) {
689                 errJson.addProperty("warning", "获取会话信息sessionKey失败,导致无法解密获取的电话号码,可能原因是会话已过期,请强制退出微信然后再重试【/wx/miniapp/user/phone.do】");
690                 json.add("error", errJson);
691                 this.printJson(response, json.toString());
692                 return;
693             }
694             
695             
696             //第三方托管方式写法 
697             WxMaService wxService = null;
698             try {
699             wxService = MaServiceInit.getWxMaServiceByOpenComponentByAppId(corpEntity.getMiniAppId()) ;
700             }catch (Exception e) {
701                 e.printStackTrace();
268665 702                 errJson.addProperty("warning",(e.getCause()!=null?e.getCause().getMessage(): e.getMessage())+ "【/wx/miniapp/user/phone.do】");
a6a76f 703                 json.add("error", errJson);
F 704                 this.printJson(response, json.toString());
705                 return;    
706             }
707             
708             
709             // 用户信息校验
710             if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
268665 711                 errJson.addProperty("warning","user check failed"+ "【/wx/miniapp/user/phone.do】");
a6a76f 712                 json.add("error", errJson);
F 713                 this.printJson(response, json.toString());
714                 return;    
715             }
716     
717             // 解密
718             WxMaPhoneNumberInfo phoneNoInfo = wxService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
719             if (phoneNoInfo != null) {
720                 json.addProperty("phoneNumber", phoneNoInfo.getPhoneNumber());
721                 json.addProperty("purePhoneNumber", phoneNoInfo.getPurePhoneNumber());
722                 json.addProperty("countryCode", phoneNoInfo.getCountryCode());
723                 json.addProperty("watermark", phoneNoInfo.getWatermark().getAppid());
724             }else {
268665 725                 errJson.addProperty("warning","获取电话信息出错"+ "【/wx/miniapp/user/phone.do】");
a6a76f 726                 json.add("error", errJson);
F 727             }
728             
729             this.printJson(response, json.toString());
730             return;
731         }catch (Exception e) {
732             errJson.addProperty("warning",e.getCause()!=null?e.getCause().getMessage():e.getMessage());
733             json.add("error", errJson);
734             this.printJson(response, json.toString());
735             return;
736         }
737     }
738
739     /**
740      * 更新所有小程序用户的头像 
741      * @param request
742      * @param response
743      */
744     @GetMapping("/updateAllWeiXinAvatar.do")
745     public void updateAllWeiXinAvatar (HttpServletRequest request, HttpServletResponse response) {
746         JsonObject json = new JsonObject();
747         JsonObject errJson = new JsonObject();
748         String filePathFile = request.getSession().getServletContext().getRealPath("/") + "uploads"+File.separator+"smallpic"+File.separator ;
749         
750         List<DataSourceEntity> corpList = MultiDataSource.getDataSourceMapsByMaAppId();
751         for (int i = 0 ; corpList !=null && i < corpList.size();i++) {
752             //if (! corpList.get(i).getDb().equalsIgnoreCase("SuoFeiYa"))  continue ;   //testing ... 
753             File file = null ;
754             try {
755                 SpObserver.setDBtoInstance("_"+corpList.get(i).getDbId());//切换数据源
756                 List<MyWxMpUser> userList = maUserIfc.getNotExistsAvatorList() ;
757                 for(int j = 0 ;userList != null && j < userList.size() ; j++) {
758                     String fileName = filePathFile + RandomString.getRandomString(4) +".jpg";
759                     file = AvatarFile.getAvatarFile (userList.get(j).getHeadImgUrl(),fileName,filePathFile) ;  //获取微信图像 File 对象
760                     String unidStr = userList.get(j).getWeiXinAvatarUnid() ;
761                     String unids[] ;
762                     String unid = null ;
763                     Integer seq = null ;
764                     if (unidStr != null && !"".equals(unidStr)) {
765                        unids = unidStr.split(";") ;
766                        unid = unids[0] ;
767                        if (unids.length > 1) {
768                            seq = Integer.valueOf( unids[unids.length - 1]) ;
769                        }
770                     }
771                     AttachmentEntity attachmentEntity = new AttachmentEntity() ;
772                     attachmentEntity.setUnid(unid);
773                     attachmentEntity.setSeq(seq);
774                     attachmentEntity.setFormId(730102);
775                     attachmentEntity.setDoccode(userList.get(j).getOpenId());
776                     attachmentEntity.setFieldId("WeiXinAvatarUnid");
777                     attachmentEntity.setRowId(userList.get(j).getOpenId());
778                     attachmentEntity.setPhysicalFile(null);
779                     attachmentEntity.setPhysicalPath(null);
780                     attachmentEntity.setOriginalFileName(file.getName());
781                     attachmentEntity.setFileSize(file.length() );
782                     attachmentEntity.setFileType("jpg");
783                     // attachmentEntity.setAuthorCode(postBeanInfo.getUsercode());
784                     // attachmentEntity.setAuthorName(postBeanInfo.getUsername());
785                     
786                     AttachmentWhereEntity attachmentWhereEntity = attachmentIfc.saveAttachment(attachmentEntity , file,"1");
787                     if (attachmentWhereEntity != null) {
788                         maUserIfc.updateWeiXinAvatarUnid(userList.get(j).getOpenId(), attachmentWhereEntity.getUnid()+";" + attachmentWhereEntity.getSeq()) ;
789                     }
790                 }
791                
792             } catch (Exception e) {
793                 e.printStackTrace();
794                 errJson.addProperty("warning","数据源:" + corpList.get(i).getDbId() + "【" + corpList.get(i).getDb() + "】"+  (e.getCause()!=null?e.getCause().getMessage(): e.getMessage())+ "【/updateAllWeiXinAvatar.do】");
795                 json.add("error", errJson);
796                 this.printJson(response, json.toString());
797                 return;        
798                 
799             }finally {
800                 SpObserver.setDBtoInstance();
801                 if (file != null && file.exists()&&file.isFile()) {
802                     log.info("del>>userCode:"+request.getSession().getAttribute(SessionKey.USERCODE)+"|dbid:"+request.getSession().getAttribute(SessionKey.DATA_BASE_ID)+"|"+file.getAbsolutePath());
803                     file.delete();
804                 }
805             }
806         }
807         json.addProperty("state", "success");
808              this.printJson(response, json.toString());
809              return;
810     }
2e95e7 811     
J 812     /**
813      * 更新小程序用户昵称 
814      * @param request
815      * @param response
816      */
817     @RequestMapping("/uploadNickName.do")
818     public void uploadNickName(HttpServletRequest request, HttpServletResponse response)  {//
819         HttpSession session=request.getSession();
820         String openId = (String)session.getAttribute(SessionKey.WEIXIN_OPENID);
821         JsonObject json = new JsonObject();
822         JsonObject errJson = new JsonObject();
823         String nickName = request.getParameter("nickName") ;
8b5515 824         if (StringUtils.isBlank(nickName)) {
X 825             nickName = "微信用户";
826         }
2e95e7 827         try {
J 828             DataSourceEntity dataSourceEntity = MultiDataSource.getDataSourceMap( request) ;
829             SpObserver.setDBtoInstance("_" + dataSourceEntity.getDbId());
830             
831             //保存昵称
832             maUserIfc.updateNickName(openId, nickName);
2e628d 833             session.setAttribute(SessionKey.WEIXIN_NICKNAME, nickName) ;  //必须保存到会话
2e95e7 834             json.addProperty("state", "success");
J 835             this.printJson(response, json.toString());
836             return;
837            
838         } catch (DataAccessException e) {
839             e.printStackTrace();
840             errJson.addProperty("warning", (e.getCause()!=null?e.getCause().getMessage():e.getMessage()));
841             json.add("error", errJson);
842             this.printJson(response, json.toString());
843             return;
844         } catch (Exception e) {
845             e.printStackTrace();
846             errJson.addProperty("warning", (e.getCause()!=null?e.getCause().getMessage():e.getMessage()));
847             json.add("error", errJson);
848             this.printJson(response, json.toString());
849             return;
850         } finally {
851             SpObserver.setDBtoInstance();
852         }
853     }
854     
855     /**
856      * 上传小程序用户头像  
857      * @param request
858      * @param response
859      */
860     @RequestMapping("/uploadAvatar.do")
861     public void uploadAvatar(HttpServletRequest request, HttpServletResponse response)  {//
862         MultipartHttpServletRequest multipartRequest= FileUtil.getMultipartHttpServletRequest(request);
863         MultipartFile file = multipartRequest.getFile("file");
864         if(file==null){
865             file= multipartRequest.getFiles("data").get(0);
866         }
867         HttpSession session=request.getSession();
868         String openId = (String)session.getAttribute(SessionKey.WEIXIN_OPENID);
869         
870         JsonObject json = new JsonObject();
871         JsonObject errJson = new JsonObject();
872        
873          String fieldId = "WeiXinAvatarUnid" ;  //multipartRequest.getParameter("fieldId"); 
874          String attachmentType = "1" ; //1 表示 9 类型控件,只能上传一个图片,2表示19类型控件,允许上传多个附件
875         
876         Integer formId = 730102;
877         File newFile = new File(file.getOriginalFilename()); 
878         try {
879             DataSourceEntity dataSourceEntity = MultiDataSource.getDataSourceMap( request) ;
880             SpObserver.setDBtoInstance("_" + dataSourceEntity.getDbId());
881             SettingEntity settingEntity = settingIfc.getSettingEntity(request) ;
882             MyWxMpUser myWxMpUser = maUserIfc.getUser(openId);
883             if (myWxMpUser == null) {
884                 errJson.addProperty("warning","请先登录");
885                 json.add("error", errJson);
886                 this.printJson(response, json.toString());
887                 return;
888             }
889             
890             String unids = myWxMpUser.getWeiXinAvatarUnid();
891             String unid = null,seqStr = null;
892             Integer seq = null;
893             if (unids!=null && !"".equals(unids)) {
894                 String unidArray[] = unids.split(";");
895                 unid = unidArray[0];
896                 if (unidArray.length>1) {
897                     seqStr = unidArray[unidArray.length-1];   //取最后面的 seq 
898                 }
899                 try {
900                     if (seqStr!=null&&!"".equals(seqStr)) {
901                         seq = Integer.valueOf( seqStr) ;
902                     }
903                 }catch (NumberFormatException e) {
904                     errJson.addProperty("warning", (e.getCause()!=null?e.getCause().getMessage():e.getMessage()));
905                     json.add("error", errJson);
906                     this.printJson(response, json.toString());
907                     return;
908                 }
909             }
910             
911             FileUtils.copyInputStreamToFile(file.getInputStream(), newFile);
912             
913             AttachmentEntity attachmentEntity = new AttachmentEntity() ;
914             attachmentEntity.setDoccode(null) ;
915             attachmentEntity.setRowId(null) ;
916             attachmentEntity.setFormId(formId) ;
917             attachmentEntity.setUnid(unid) ;
918             attachmentEntity.setSeq(seq) ;
919             attachmentEntity.setFieldId(fieldId);
920             attachmentEntity.setPhysicalFile(newFile.getName());
921             attachmentEntity.setOriginalFileName(newFile.getName());
922             
923             AttachmentIfc attachmentIfc = (AttachmentIfc) FactoryBean.getBean("AttachmentImpl");
924             //保存附件
925             AttachmentWhereEntity attachmentWhereEntity = attachmentIfc.saveAttachment( attachmentEntity , newFile,attachmentType) ;
926             
927             //保存头像
928             if (attachmentWhereEntity!=null) {
929                 maUserIfc.updateWeiXinAvatarUnid(openId, attachmentWhereEntity.getUnid()+";"+attachmentWhereEntity.getSeq()) ;            
930             }
931             
932             //输出 url 
933             String url = imgData.getImageUrl(attachmentWhereEntity.getUnid() +";" + attachmentWhereEntity.getSeq(), settingEntity.getImageProductWidth(),
934                         settingEntity.getImageProductHeight(), settingEntity.isShowProductOrgImage(),
935                         settingEntity.isFromCached(), request); 
2e628d 936             session.setAttribute(SessionKey.WEIXIN_HEADIMGURL,url) ;  //必须保存到会话
2e95e7 937             //json.addProperty(SettingKey.DOCCODE, docCode);
J 938             //json.addProperty(SettingKey.ROWID, rowId);
939             json.addProperty(SettingKey.UNID, attachmentWhereEntity.getUnid());
940             json.addProperty("seq", attachmentWhereEntity.getSeq());
941             json.addProperty("url", url);
942             
943             json.addProperty("state", "success");
944             this.printJson(response, json.toString());
945             return;
946           //  return  attachmentWhereEntity.getUnid() +";/getImage.do?uuid=" + unid + "&type=1&dbid=" + dbid;
947         } catch (DataAccessException e) {
948             e.printStackTrace();
949             errJson.addProperty("warning", (e.getCause()!=null?e.getCause().getMessage():e.getMessage()));
950             json.add("error", errJson);
951             this.printJson(response, json.toString());
952             return;
953         } catch (IOException e) {
954             e.printStackTrace();
955             errJson.addProperty("warning", (e.getCause()!=null?e.getCause().getMessage():e.getMessage()));
956             json.add("error", errJson);
957             this.printJson(response, json.toString());
958             return;
959         }catch (Exception e) {
960             e.printStackTrace();
961             errJson.addProperty("warning", (e.getCause()!=null?e.getCause().getMessage():e.getMessage()));
962             json.add("error", errJson);
963             this.printJson(response, json.toString());
964             return;
965         } finally {
966             SpObserver.setDBtoInstance();
967             if (newFile != null && newFile.exists()&&newFile.isFile()) {
968                 log.info("del>>userCode:"+request.getSession().getAttribute(SessionKey.USERCODE)+"|dbid:"+request.getSession().getAttribute(SessionKey.DATA_BASE_ID)+"|"+newFile.getAbsolutePath());
969                 newFile.delete() ;
970             }
971         }
972     }    
973     
a6a76f 974 }