wxwork-sdk.service.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  1. import { Injectable } from '@angular/core';
  2. import { FmodeParse, FmodeObject } from 'fmode-ng/parse';
  3. import * as ww from '@wecom/jssdk';
  4. import { WxworkCorp } from 'fmode-ng/core';
  5. const Parse = FmodeParse.with('nova');
  6. export interface WxworkCurrentChat {
  7. type: 'chatId' | 'userId';
  8. id?: string;
  9. contact?: any;
  10. follow_user?: any;
  11. group?: any;
  12. }
  13. /**
  14. * 企微SDK服务
  15. * 封装企业微信JSSDK功能
  16. */
  17. @Injectable({
  18. providedIn: 'root'
  19. })
  20. export class WxworkSDKService {
  21. // 企业配置映射
  22. private companyMap: any = {
  23. 'cDL6R1hgSi': { // 映三色
  24. corpResId: 'SpL6gyD1Gu'
  25. }
  26. };
  27. // 应用套件映射
  28. private suiteMap: any = {
  29. 'crm': {
  30. suiteId: 'dk2559ba758f33d8f5'
  31. },
  32. 'project': { // 🔥 添加project应用的配置(使用相同的suiteId)
  33. suiteId: 'dk2559ba758f33d8f5'
  34. }
  35. };
  36. cid: string = '';
  37. appId: string = '';
  38. corpId: string = '';
  39. wecorp: WxworkCorp | null = null;
  40. ww = ww;
  41. registerUrl: string = '';
  42. constructor() {}
  43. /**
  44. * 初始化SDK
  45. */
  46. async initialize(cid: string, appId: string): Promise<void> {
  47. this.cid = cid;
  48. this.appId = appId;
  49. this.wecorp = new WxworkCorp(cid);
  50. await this.registerCorpWithSuite();
  51. }
  52. /**
  53. * 注册企业微信JSAPI
  54. */
  55. async registerCorpWithSuite(apiList?: string[]): Promise<boolean> {
  56. console.log('🔍 [registerCorpWithSuite] 开始注册JSSDK...');
  57. console.log('🔍 [registerCorpWithSuite] 平台检测:', this.platform());
  58. if (this.platform() !== 'wxwork') {
  59. console.warn('⚠️ [registerCorpWithSuite] 非企业微信环境,跳过注册');
  60. return false;
  61. }
  62. // 如果URL未变化且已注册,直接返回
  63. if (!apiList?.length && this.registerUrl === location.href) {
  64. console.log('✅ [registerCorpWithSuite] URL未变化,使用缓存的注册状态');
  65. return true;
  66. }
  67. apiList = apiList || this.getDefaultApiList();
  68. console.log('🔍 [registerCorpWithSuite] API列表:', apiList);
  69. try {
  70. console.log('🔍 [registerCorpWithSuite] 获取企业配置,CID:', this.cid);
  71. const corpConfig = await this.getCorpByCid(this.cid);
  72. console.log('🔍 [registerCorpWithSuite] 企业配置:', corpConfig);
  73. const suiteId = this.suiteMap[this.appId]?.suiteId;
  74. console.log('🔍 [registerCorpWithSuite] 套件ID:', suiteId);
  75. const now = new Date();
  76. return new Promise((resolve) => {
  77. console.log('🔍 [registerCorpWithSuite] 调用ww.register...');
  78. console.log('🔍 [registerCorpWithSuite] corpId:', corpConfig.corpId);
  79. console.log('🔍 [registerCorpWithSuite] agentId:', corpConfig.agentId);
  80. console.log('🔍 [registerCorpWithSuite] suiteId:', suiteId);
  81. console.log('🔍 [registerCorpWithSuite] url:', location.href);
  82. // 🔥 添加15秒超时机制
  83. const timeout = setTimeout(() => {
  84. console.warn('⚠️ [registerCorpWithSuite] 注册超时(15秒),可能原因:');
  85. console.warn(' 1. 回调函数未被触发');
  86. console.warn(' 2. 企业微信JSSDK加载失败');
  87. console.warn(' 3. 不在正确的群聊会话中');
  88. console.warn(' 4. 应用权限配置错误');
  89. resolve(false);
  90. }, 15000);
  91. ww.register({
  92. corpId: corpConfig.corpId,
  93. suiteId: suiteId,
  94. agentId: corpConfig.agentId,
  95. jsApiList: apiList!,
  96. getAgentConfigSignature: async () => {
  97. console.log('🔍 [registerCorpWithSuite] 获取签名...');
  98. const jsapiTicket = await this.wecorp!.ticket.get();
  99. console.log('🔍 [registerCorpWithSuite] Ticket:', jsapiTicket?.substring(0, 20) + '...');
  100. const signature = ww.getSignature({
  101. ticket: jsapiTicket,
  102. nonceStr: '666',
  103. timestamp: (now.getTime() / 1000).toFixed(0),
  104. url: location.href
  105. });
  106. console.log('🔍 [registerCorpWithSuite] 签名生成完成:', {
  107. nonceStr: '666',
  108. timestamp: (now.getTime() / 1000).toFixed(0),
  109. url: location.href
  110. });
  111. return signature;
  112. },
  113. onAgentConfigSuccess: () => {
  114. clearTimeout(timeout);
  115. console.log('✅ [registerCorpWithSuite] AgentConfig注册成功!');
  116. this.registerUrl = location.href;
  117. resolve(true);
  118. },
  119. onAgentConfigFail: (err: any) => {
  120. clearTimeout(timeout);
  121. console.error('❌ [registerCorpWithSuite] AgentConfig注册失败:', err);
  122. console.error('❌ 错误详情:', JSON.stringify(err, null, 2));
  123. console.error('❌ 请检查:');
  124. console.error(' 1. agentId是否正确');
  125. console.error(' 2. 应用是否已发布');
  126. console.error(' 3. jsapi_ticket是否有效');
  127. resolve(false);
  128. },
  129. onConfigFail: (err: any) => {
  130. clearTimeout(timeout);
  131. console.error('❌ [registerCorpWithSuite] Config注册失败:', err);
  132. console.error('❌ 错误详情:', JSON.stringify(err, null, 2));
  133. console.error('❌ 请检查:');
  134. console.error(' 1. corpId是否正确');
  135. console.error(' 2. suiteId是否正确');
  136. console.error(' 3. 企业是否已授权');
  137. resolve(false);
  138. }
  139. });
  140. });
  141. } catch (error) {
  142. console.error('❌ [registerCorpWithSuite] 注册过程出错:', error);
  143. return false;
  144. }
  145. }
  146. /**
  147. * 获取当前聊天对象
  148. */
  149. async getCurrentChatObject(): Promise<{
  150. GroupChat?: FmodeObject;
  151. Contact?: FmodeObject;
  152. currentChat: WxworkCurrentChat | null;
  153. }> {
  154. const currentChat = await this.getCurrentChat();
  155. if (!currentChat) {
  156. return { currentChat: null };
  157. }
  158. let GroupChat: FmodeObject | undefined;
  159. let Contact: FmodeObject | undefined;
  160. try {
  161. if (currentChat.type === 'chatId' && currentChat.group) {
  162. GroupChat = await this.syncGroupChat(currentChat.group);
  163. } else if (currentChat.type === 'userId' && currentChat.id) {
  164. const contactInfo = await this.wecorp!.externalContact.get(currentChat.id);
  165. Contact = await this.syncContact(contactInfo);
  166. }
  167. } catch (error) {
  168. console.error('getCurrentChatObject error:', error);
  169. }
  170. return { GroupChat, Contact, currentChat };
  171. }
  172. /**
  173. * 获取当前聊天场景
  174. */
  175. async getCurrentChat(): Promise<WxworkCurrentChat | null> {
  176. const isRegister = await this.registerCorpWithSuite();
  177. if (!isRegister) return null;
  178. try {
  179. const context = await ww.getContext();
  180. const entry = context?.entry;
  181. let type: 'chatId' | 'userId';
  182. let id: string | undefined;
  183. let contact: any;
  184. let chat: any;
  185. if (entry === 'group_chat_tools') {
  186. type = 'chatId';
  187. id = (await ww.getCurExternalChat())?.chatId;
  188. chat = await this.wecorp!.externalContact.groupChat.get(id!);
  189. } else if (entry === 'contact_profile' || entry === 'single_chat_tools') {
  190. type = 'userId';
  191. id = (await ww.getCurExternalContact())?.userId;
  192. contact = await this.wecorp!.externalContact.get(id!);
  193. } else {
  194. return null;
  195. }
  196. return {
  197. type,
  198. id,
  199. group: chat?.group_chat,
  200. contact: contact?.external_contact,
  201. follow_user: contact?.follow_user
  202. };
  203. } catch (error) {
  204. console.error('getCurrentChat error:', error);
  205. return null;
  206. }
  207. }
  208. /**
  209. * 获取当前用户信息
  210. */
  211. async getCurrentUser(): Promise<FmodeObject | null> {
  212. const userInfo = await this.getUserinfo();
  213. if (!userInfo) return null;
  214. return await this.getContactOrProfile(userInfo);
  215. }
  216. /**
  217. * 获取用户信息
  218. */
  219. async getUserinfo(code?: string): Promise<any> {
  220. // 优先检查缓存
  221. if (!code) {
  222. const userInfoStr = localStorage.getItem(`${this.cid}/USERINFO`);
  223. if (userInfoStr) {
  224. const userInfo = JSON.parse(userInfoStr);
  225. userInfo.cid = this.cid;
  226. return userInfo;
  227. }
  228. }
  229. // 从URL获取code
  230. const url = new URL(location.href);
  231. code = url.searchParams.get('code') || code;
  232. if (!code) return null;
  233. const result = await this.wecorp!.auth.getuserinfo(code);
  234. if (result?.errcode) {
  235. console.error(result?.errmsg);
  236. return null;
  237. }
  238. // 补全外部用户信息
  239. if (result?.external_userid) {
  240. const euser = await this.wecorp!.externalContact.get(result.external_userid);
  241. if (euser?.external_contact) {
  242. Object.assign(result, euser.external_contact);
  243. }
  244. }
  245. result.cid = this.cid;
  246. // 缓存用户信息
  247. localStorage.setItem(`${this.cid}/USERINFO`, JSON.stringify(result));
  248. return result;
  249. }
  250. /**
  251. * 同步群聊信息
  252. */
  253. async syncGroupChat(groupInfo: any): Promise<FmodeObject> {
  254. let query = new Parse.Query('GroupChat');
  255. query.equalTo('chat_id', groupInfo?.chat_id);
  256. let group = await query.first();
  257. if (!group?.id) {
  258. group = new Parse.Object('GroupChat');
  259. }
  260. // 生成入群方式
  261. if (!group?.get('joinUrl')) {
  262. const config_id1 = (await this.wecorp!.externalContact.groupChat.addJoinWay({
  263. scene: 1,
  264. chat_id_list: [groupInfo.chat_id]
  265. }))?.config_id;
  266. const joinUrl = (await this.wecorp!.externalContact.groupChat.getJoinWay(config_id1))?.join_way;
  267. group.set('joinUrl', joinUrl);
  268. }
  269. if (!group?.get('joinQrcode')) {
  270. const config_id2 = (await this.wecorp!.externalContact.groupChat.addJoinWay({
  271. scene: 2,
  272. chat_id_list: [groupInfo.chat_id]
  273. }))?.config_id;
  274. const joinQrcode = (await this.wecorp!.externalContact.groupChat.getJoinWay(config_id2))?.join_way;
  275. group.set('joinQrcode', joinQrcode);
  276. }
  277. // 更新群聊数据
  278. let needSave = false;
  279. if (group.get('chat_id') !== groupInfo.chat_id) needSave = true;
  280. if (group.get('name') !== groupInfo.name) needSave = true;
  281. if (group.get('owner') !== groupInfo.owner) needSave = true;
  282. if (group.get('notice') !== groupInfo.notice) needSave = true;
  283. if (group.get('member_version') !== groupInfo.member_version) {
  284. needSave = true;
  285. group.set('member_list', groupInfo.member_list);
  286. group.set('member_version', groupInfo.member_version);
  287. }
  288. group.set({
  289. chat_id: groupInfo.chat_id,
  290. name: groupInfo.name,
  291. owner: groupInfo.owner,
  292. notice: groupInfo.notice
  293. });
  294. if (this.cid) {
  295. group.set('company', { __type: 'Pointer', className: 'Company', objectId: this.cid });
  296. }
  297. if (needSave) {
  298. group = await group.save();
  299. }
  300. return group;
  301. }
  302. /**
  303. * 同步联系人信息
  304. */
  305. async syncContact(contactInfo: any): Promise<FmodeObject> {
  306. const externalContact = contactInfo.external_contact || contactInfo;
  307. const externalUserId = externalContact.external_userid;
  308. let query = new Parse.Query('ContactInfo');
  309. query.equalTo('external_userid', externalUserId);
  310. const Company = new Parse.Object('Company');
  311. Company.id = this.cid;
  312. query.equalTo('company', Company);
  313. let contact = await query.first();
  314. if (!contact?.id) {
  315. contact = new Parse.Object('ContactInfo');
  316. if (Company?.id) {
  317. contact.set('company', Company.toPointer());
  318. }
  319. }
  320. const name = externalContact.name || '';
  321. const mobile = externalContact.mobile || '';
  322. const data: any = {
  323. ...externalContact,
  324. follow_user: contactInfo.follow_user || externalContact.follow_user || []
  325. };
  326. let needSave = false;
  327. if (contact.get('external_userid') !== externalUserId) needSave = true;
  328. if (contact.get('name') !== name && name) needSave = true;
  329. if (contact.get('mobile') !== mobile && mobile) needSave = true;
  330. const oldData = contact.get('data');
  331. if (JSON.stringify(oldData) !== JSON.stringify(data)) needSave = true;
  332. contact.set('external_userid', externalUserId);
  333. contact.set('name', name);
  334. contact.set('mobile', mobile);
  335. contact.set('data', data);
  336. if (needSave) {
  337. contact = await contact.save();
  338. }
  339. return contact;
  340. }
  341. /**
  342. * 获取Profile或UserSocial
  343. */
  344. async getContactOrProfile(userInfo: any): Promise<FmodeObject> {
  345. let UserType: string;
  346. if (userInfo.openid || userInfo.external_userid) {
  347. UserType = 'UserSocial';
  348. } else if (userInfo.userid) {
  349. UserType = 'Profile';
  350. } else {
  351. throw new Error('Invalid user info');
  352. }
  353. // 构建查询条件
  354. const userCondition: any[] = [];
  355. const prefix = UserType === 'UserSocial' ? 'data.' : '';
  356. if (userInfo.openid) userCondition.push({ [`${prefix}openid`]: { $regex: userInfo.openid } });
  357. if (userInfo.userid) userCondition.push({ [`${prefix}userid`]: { $regex: userInfo.userid } });
  358. if (userInfo.mobile) userCondition.push({ [`${prefix}mobile`]: { $regex: userInfo.mobile } });
  359. if (userInfo.email) userCondition.push({ [`${prefix}email`]: { $regex: userInfo.email } });
  360. if (userInfo.external_userid) {
  361. userCondition.push({ [`${prefix}external_userid`]: { $regex: userInfo.external_userid } });
  362. }
  363. const query = Parse.Query.fromJSON(UserType, {
  364. where: {
  365. $or: userCondition
  366. }
  367. });
  368. query.equalTo('company', this.cid);
  369. let thisUser = await query.first();
  370. if (!thisUser?.id) {
  371. thisUser = new Parse.Object(UserType);
  372. }
  373. // 关联当前登录用户
  374. const current = Parse.User.current();
  375. if (current?.id && !thisUser?.get('user')?.id) {
  376. thisUser.set('user', current.toPointer());
  377. }
  378. return thisUser;
  379. }
  380. /**
  381. * 创建群聊
  382. */
  383. async createGroupChat(options: {
  384. groupName: string;
  385. userIds?: string[];
  386. externalUserIds?: string[];
  387. }): Promise<any> {
  388. const isRegister = await this.registerCorpWithSuite();
  389. if (!isRegister) return null;
  390. return new Promise((resolve, reject) => {
  391. ww.createCorpGroupChat({
  392. groupName: options.groupName,
  393. userIds: options.userIds,
  394. externalUserIds: options.externalUserIds,
  395. success: (data: any) => {
  396. resolve(data);
  397. },
  398. fail: (err: any) => {
  399. reject(err);
  400. }
  401. });
  402. });
  403. }
  404. /**
  405. * 添加成员到群聊
  406. */
  407. async addUserToGroup(options: {
  408. chatId: string;
  409. userIds?: string[];
  410. externalUserIds?: string[];
  411. }): Promise<any> {
  412. const isRegister = await this.registerCorpWithSuite();
  413. if (!isRegister) return null;
  414. return new Promise((resolve, reject) => {
  415. (ww as any).updateCorpGroupChat({
  416. chatId: options.chatId,
  417. userIds: options.userIds,
  418. externalUserIds: options.externalUserIds,
  419. success: (data:any) => {
  420. resolve(data);
  421. },
  422. fail: (err:any) => {
  423. reject(err);
  424. }
  425. });
  426. });
  427. }
  428. /**
  429. * 打开指定群聊
  430. */
  431. async openChat(chatId: string): Promise<void> {
  432. const isRegister = await this.registerCorpWithSuite();
  433. if (!isRegister) return;
  434. return new Promise((resolve, reject) => {
  435. ww.openEnterpriseChat({
  436. externalUserIds: [],
  437. groupName: '',
  438. chatId: chatId,
  439. success: () => {
  440. resolve();
  441. },
  442. fail: (err: any) => {
  443. reject(err);
  444. }
  445. });
  446. });
  447. }
  448. /**
  449. * 选择企业联系人
  450. */
  451. async selectEnterpriseContact(options?: {
  452. mode?: 'single' | 'multi';
  453. type?: Array<'department' | 'user'>;
  454. }): Promise<any> {
  455. const isRegister = await this.registerCorpWithSuite();
  456. if (!isRegister) return null;
  457. return new Promise((resolve, reject) => {
  458. (ww as any).selectEnterpriseContact({
  459. fromDepartmentId: -1,
  460. mode: options?.mode || 'multi',
  461. type: options?.type || ['department', 'user'],
  462. success: (data:any) => {
  463. resolve(data);
  464. },
  465. fail: (err:any) => {
  466. reject(err);
  467. }
  468. });
  469. });
  470. }
  471. /**
  472. * 获取企业配置
  473. */
  474. private async getCorpByCid(cid: string): Promise<any> {
  475. if (this.corpId) return { corpId: this.corpId };
  476. const query = new Parse.Query('CloudResource');
  477. const res = await query.get(this.companyMap[cid]?.corpResId);
  478. const config: any = res.get('config');
  479. return config;
  480. }
  481. /**
  482. * 判断平台
  483. */
  484. private platform(): string {
  485. const ua = navigator.userAgent.toLowerCase();
  486. if (ua.indexOf('wxwork') > -1) return 'wxwork';
  487. if (ua.indexOf('wechat') > -1) return 'wechat';
  488. return 'h5';
  489. }
  490. /**
  491. * 发送消息到当前聊天窗口
  492. */
  493. async sendChatMessage(options: {
  494. msgtype: 'text' | 'image' | 'news';
  495. text?: { content: string };
  496. news?: { link: string; title: string; desc: string; imgUrl: string };
  497. }): Promise<void> {
  498. console.log('🔍 [sendChatMessage] ========== 开始发送消息 ==========');
  499. console.log('🔍 [sendChatMessage] 消息类型:', options.msgtype);
  500. console.log('🔍 [sendChatMessage] 消息内容:', JSON.stringify(options, null, 2));
  501. console.log('🔍 [sendChatMessage] 开始注册JSSDK...');
  502. const isRegister = await this.registerCorpWithSuite(['sendChatMessage']);
  503. console.log('🔍 [sendChatMessage] JSSDK注册结果:', isRegister);
  504. if (!isRegister) {
  505. console.error('❌ [sendChatMessage] JSSDK注册失败');
  506. console.error('❌ 可能原因:');
  507. console.error(' 1. 企业微信配置错误(corpId, suiteId, agentId)');
  508. console.error(' 2. ticket获取失败');
  509. console.error(' 3. URL签名错误');
  510. console.error(' 4. 网络问题');
  511. throw new Error('JSSDK注册失败');
  512. }
  513. console.log('🔍 [sendChatMessage] 调用ww.sendChatMessage...');
  514. return new Promise((resolve, reject) => {
  515. ww.sendChatMessage({
  516. ...options,
  517. success: (res: any) => {
  518. console.log('✅ [sendChatMessage] 消息发送成功!');
  519. console.log('✅ [sendChatMessage] 响应数据:', res);
  520. resolve();
  521. },
  522. fail: (err: any) => {
  523. console.error('❌ [sendChatMessage] 消息发送失败!');
  524. console.error('❌ [sendChatMessage] 错误详情:', err);
  525. console.error('❌ [sendChatMessage] 错误消息:', err?.errMsg);
  526. console.error('❌ [sendChatMessage] 错误代码:', err?.errCode);
  527. // 提供详细的错误提示
  528. if (err?.errMsg?.includes('no permission')) {
  529. console.error('❌ 权限不足!请在企业微信管理后台开启sendChatMessage权限');
  530. } else if (err?.errMsg?.includes('not in session')) {
  531. console.error('❌ 不在聊天会话中!请从群聊工具或客户资料入口打开应用');
  532. }
  533. reject(err);
  534. }
  535. } as any);
  536. });
  537. }
  538. /**
  539. * 获取默认API列表
  540. */
  541. private getDefaultApiList(): string[] {
  542. return [
  543. 'getContext',
  544. 'getCurExternalChat',
  545. 'getCurExternalContact',
  546. 'createCorpGroupChat',
  547. 'updateCorpGroupChat',
  548. 'openEnterpriseChat',
  549. 'selectEnterpriseContact',
  550. 'checkJsApi',
  551. 'chooseImage',
  552. 'previewImage',
  553. 'uploadImage',
  554. 'downloadImage',
  555. 'getLocation',
  556. 'openLocation',
  557. 'scanQRCode',
  558. 'closeWindow',
  559. 'sendChatMessage' // 🔥 添加发送消息权限
  560. ];
  561. }
  562. }