TencentImFriendService.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. <?php
  2. namespace App\Services;
  3. use App\Exceptions\TencentImFriendException;
  4. use App\Models\User;
  5. use App\Models\UserFriendApplyRecord;
  6. use App\Traits\TencentIm;
  7. use Illuminate\Support\Facades\DB;
  8. class TencentImFriendService
  9. {
  10. use TencentIm;
  11. const ADD_FRIEND_TYPE_SINGLE = 'Add_Type_Single'; //表示单向加好友
  12. const ADD_FRIEND_TYPE_BOTH = 'Add_Type_Both'; //表示双向加好友
  13. const IM_IDENTIFIER_PREFIX = 'IM_USER_';
  14. const CHECK_FRIEND_TYPE_SINGLE = 'CheckResult_Type_Single'; //只会检查 From_Account 的好友表中是否有 To_Account,不会检查 To_Account 的好友表中是否有 From_Account
  15. const CHECK_FRIEND_TYPE_BOTH = 'CheckResult_Type_Both'; //既会检查 From_Account 的好友表中是否有 To_Account,也会检查 To_Account 的好友表中是否有 From_Account
  16. const ADD_FRIEND_ADD_SOURCE_TYPE_ADDRESS_BOOK = 'AddSource_Type_100'; //加好友来源 通讯录
  17. const TENCENT_REST_APIS = [
  18. 'friendAddItem' => 'v4/sns/friend_add', //单个添加好友,
  19. 'friendGet' => 'v4/sns/friend_get', //拉取好友,
  20. 'friendCheck' => 'v4/sns/friend_check', //校验好友
  21. 'black_add' => 'v4/sns/black_list_add', //拉黑好友
  22. 'black_del' => 'v4/sns/black_list_delete', //删除拉黑好友
  23. ];
  24. static public function verifyUserApplyFriendExists(User $fromUser, User $toUser)
  25. {
  26. }
  27. //添加好友记录
  28. public function addApplyFriendRecord(User $user, array $options = [])
  29. {
  30. try {
  31. DB::beginTransaction();
  32. $toUser = User::find($options['to_user_id']);
  33. if (!$toUser) {
  34. throw new TencentImFriendException('好友账号不存在');
  35. }
  36. //检测是否已经有记录
  37. $friendApplyRecordModel = UserFriendApplyRecord::query()
  38. ->where(['from_user_id' => $user->id, 'to_user_id' => $toUser->id])
  39. ->latest()
  40. ->first();
  41. if ($friendApplyRecordModel) {
  42. if (UserFriendApplyRecord::APPLY_STATUS_100 === $friendApplyRecordModel->apply_status) {
  43. throw new TencentImFriendException('已发出好友添加申请,请勿重复操作');
  44. }
  45. if (UserFriendApplyRecord::APPLY_STATUS_101 === $friendApplyRecordModel->apply_status) {
  46. throw new TencentImFriendException('已经是好友关系,请勿重复操作');
  47. }
  48. if (UserFriendApplyRecord::APPLY_STATUS_101 === $friendApplyRecordModel->apply_status) {
  49. throw new TencentImFriendException('已经是好友关系,请勿重复操作');
  50. }
  51. }
  52. if (!$friendApplyRecordModel) {
  53. $friendApplyRecordModel = new UserFriendApplyRecord();
  54. }
  55. //添加发起申请记录
  56. $applyData = [
  57. 'from_user_id' => $user->id,
  58. 'to_user_id' => $toUser->id,
  59. 'type' => UserFriendApplyRecord::APPLY_TYPE_100,
  60. 'apply_status' => UserFriendApplyRecord::APPLY_STATUS_102,
  61. 'apply_raw_data' => [
  62. 'remark' => $options['remark'] ?? '',
  63. 'group' => $options['group_id'] ?? '',
  64. ],
  65. ];
  66. $friendApplyRecordModel->fill($applyData);
  67. //添加接收
  68. if (!$friendApplyRecordModel->save()) {
  69. throw new \Exception('写入好友申请记录失败');
  70. }
  71. DB::commit();
  72. return $friendApplyRecordModel;
  73. } catch (\Exception $e) {
  74. DB::rollBack();
  75. return ['error' => $e->getMessage()];
  76. } catch (TencentImFriendException $e) {
  77. DB::rollBack();
  78. return ['error' => $e->getMessage()];
  79. }
  80. }
  81. /**
  82. * 发起添加 IM 好友 (单个用户)
  83. * @param string $fromAccount
  84. * @param string $toAccount
  85. * @param array $options
  86. * @return \Psr\Http\Message\ResponseInterface
  87. * @throws TencentImFriendException
  88. * @throws \App\Exceptions\TencentImAccountException
  89. * @throws \App\Exceptions\TencentImException
  90. * @throws \GuzzleHttp\Exception\GuzzleException
  91. */
  92. public function friendAddItem(string $fromAccount, string $toAccount, array $options = [])
  93. {
  94. //TODO 请求添加好友前先拉取好友状态
  95. $res = $this->friendCheck($fromAccount,[$toAccount]);
  96. if($res['InfoItem'][0]['Relation']=='CheckResult_Type_BothWay'){
  97. $res['ResultItem'] = $res['InfoItem'];
  98. return $res;
  99. }
  100. $this->restApiName = self::TENCENT_REST_APIS['friendAddItem'];
  101. $baseApiHost = $this->getTencentImRestApiBaseHost();
  102. $params = self::prepareFriendAddItemOptions($fromAccount, $toAccount, $options);
  103. $apiResult = $this->requestApi($baseApiHost, $params);
  104. self::verifyApiResult($apiResult);
  105. if ($apiResult['ResultItem'][0]['ResultInfo'] || ($apiResult['ResultItem'][0]['ResultCode'] != 0)) {
  106. if($apiResult['ResultItem'][0]['ResultInfo']=='Err_SNS_FriendAdd_Friend_Exist'){
  107. return true;
  108. }
  109. throw new TencentImFriendException('添加好友失败: ' . $apiResult['ResultItem'][0]['ResultInfo']);
  110. }
  111. return $apiResult;
  112. }
  113. //拉取好友
  114. public function friendGet(string $fromAccount, int $pageStartIndex = 0)
  115. {
  116. $this->restApiName = self::TENCENT_REST_APIS['friendGet'];
  117. $baseApiHost = $this->getTencentImRestApiBaseHost();
  118. $params = [
  119. 'From_Account' => $fromAccount,
  120. 'StartIndex' => $pageStartIndex,
  121. 'StandardSequence' => $StandardSequence ?? 0,
  122. 'CustomSequence' => $CustomSequence ?? 0
  123. ];
  124. $apiResult = $this->requestApi($baseApiHost, $params);
  125. return $apiResult;
  126. }
  127. //检验好友
  128. public function friendCheck(string $fromAccount, array $toAccounts, string $checkType = self::ADD_FRIEND_TYPE_BOTH)
  129. {
  130. $this->restApiName = self::TENCENT_REST_APIS['friendCheck'];
  131. $baseApiHost = $this->getTencentImRestApiBaseHost();
  132. $params = [
  133. 'From_Account' => $fromAccount,
  134. 'To_Account' => $toAccounts,
  135. 'CheckType' => 'CheckResult_Type_Both'
  136. ];
  137. $apiResult = $this->requestApi($baseApiHost, $params);
  138. self::verifyApiResult($apiResult);
  139. return $apiResult;
  140. }
  141. /**
  142. * 构建添加好友api 请求数组
  143. * @param string $fromAccount 需要添加好友的用户IM id
  144. * @param string $toAccount 被申请添加好友的用户IM id
  145. * @param array $options
  146. * @param string $options ['AddType'] 加好友方式
  147. * @param string $options ['AddSource'] 好友来源
  148. * @param string $options ['ForceAddFlags'] 管理员强制加好友标记:1表示强制加好友,0表示常规加好友方式
  149. * @param string $options ['Remark'] 好友备注
  150. * @param string $options ['AddWording'] 形成好友关系时的附言信息
  151. * @param string $options ['GroupName'] 分组信息,添加好友时只允许设置一个分组
  152. * @return array
  153. */
  154. static public function prepareFriendAddItemOptions(string $fromAccount, string $toAccount, array $options)
  155. {
  156. // string $addType = self::ADD_FRIEND_TYPE_BOTH,
  157. // string $addSource = self::ADD_FRIEND_ADD_SOURCE_TYPE_ADDRESS_BOOK,
  158. // string $remark = '',
  159. // bool $forceAddFlags = false
  160. $result = [
  161. 'From_Account' => $fromAccount,
  162. // 'AddSource' => $options['AddSource'] ?? self::ADD_FRIEND_ADD_SOURCE_TYPE_ADDRESS_BOOK, //好友来源
  163. 'AddType' => $options['AddType'] ?? self::ADD_FRIEND_TYPE_BOTH, //加好友方式
  164. 'ForceAddFlags' => empty($options['ForceAddFlags']) ? 0 : ($options['ForceAddFlags'] ? 1 : 0), //管理员强制加好友标记:1表示强制加好友,0表示常规加好友方式
  165. ];
  166. $AddFriendItem = [];
  167. $AddFriendItem['To_Account'] = $toAccount;
  168. //好友来源
  169. $AddFriendItem['AddSource'] = $options['AddSource'] ?? self::ADD_FRIEND_ADD_SOURCE_TYPE_ADDRESS_BOOK;
  170. //好友备注
  171. if (!empty($options['Remark'])) {
  172. $AddFriendItem['Remark'] = $options['Remark'];
  173. }
  174. //形成好友关系时的附言信息
  175. if (!empty($options['AddWording'])) {
  176. $AddFriendItem['AddWording'] = $options['AddWording'];
  177. }
  178. //分组信息,添加好友时只允许设置一个分组
  179. if (!empty($options['GroupName'])) {
  180. $AddFriendItem['GroupName'] = $options['GroupName'] ? 1 : 0;
  181. }
  182. $result['AddFriendItem'][] = $AddFriendItem;
  183. unset($options);
  184. unset($AddFriendItem);
  185. return $result;
  186. }
  187. //拉黑
  188. public function friend_black_add(string $fromAccount, string $toAccount)
  189. {
  190. $this->restApiName = self::TENCENT_REST_APIS['black_add'];
  191. $baseApiHost = $this->getTencentImRestApiBaseHost();
  192. $params = [
  193. 'From_Account' => $fromAccount,
  194. 'To_Account' => array($toAccount),
  195. ];
  196. $apiResult = $this->requestApi($baseApiHost, $params);
  197. return $apiResult;
  198. }
  199. //取消拉黑
  200. public function friend_black_del(string $fromAccount, string $toAccount)
  201. {
  202. $this->restApiName = self::TENCENT_REST_APIS['black_del'];
  203. $baseApiHost = $this->getTencentImRestApiBaseHost();
  204. $params = [
  205. 'From_Account' => $fromAccount,
  206. 'To_Account' => array($toAccount),
  207. ];
  208. $apiResult = $this->requestApi($baseApiHost, $params);
  209. return $apiResult;
  210. }
  211. }