/** * 同步联系人 * @param $user_id * @param $contacts * @internal param $phones */ public function actionContacts($user_id, $contacts = '') { try { $contactsArray = json_decode($contacts); if (!$contactsArray || !is_array($contactsArray)) { $this->code(200, 'ok', []); } //区分用户类型:已注册、未注册 $data = []; foreach ($contactsArray as $obj) { $phoneArray = explode(',', $obj->phones); if (!$phoneArray) { continue; } $phoneArray = array_filter(array_unique($phoneArray)); $isFriend = 0; foreach ($phoneArray as $phone) { //清除空格 $phone = trim($phone); //未注册则跳过 $userInfo = User::findByUsernameAndNationCode($phone, 86); if (isset($userInfo['id']) && $userInfo['id'] == $user_id) { continue; } //已注册则添加为好友 if (0 != $userInfo['id']) { $isFriend = 1; //如果还不是好友则添加 $friendInfo = Friends::findByFriendIdAndUserId($userInfo['id'], $user_id); if (!$friendInfo) { $friends = new Friends(); $is = $friends->add(['user_id' => $user_id, 'friend_user_id' => $userInfo['id'], 'created_at' => time(), 'updated_at' => time()]); if (!$is) { throw new Exception('好友添加失败'); } } } } //构造返回数据 $data[] = ['contacts_id' => $obj->contacts_id, 'contacts_name' => $obj->contacts_name, 'phones' => $obj->phones, 'contacts_type' => $isFriend ? 1 : 2]; } //设置`该用户已同步过通讯录`的状态 $sync = new SyncContactsRecord(); $sync->add(['user_id' => $user_id, 'created_at' => time()]); //返回 $this->code(200, 'ok', $data); } catch (Exception $e) { $this->code(500, $e->getMessage()); } }