8000 GitHub - suminhthanh/zolakit-swift: Unofficial native Zalo iOS protocol SDK for Swift — messaging, contacts, groups, timeline and voice/video calls (iOS 16+ / macOS 13+, zero dependencies) · GitHub
[go: up one dir, main page]

Skip to content

About

Unofficial native Zalo iOS protocol SDK for Swift — messaging, contacts, groups, timeline and voice/video calls (iOS 16+ / macOS 13+, zero dependencies)

Resources

Stars

0 stars

Watchers

0 watching

Forks

 
 

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

ZolaKit

Thư viện Swift gọi Zalo cá nhân bằng giao thức của app Zalo iOS — nhắn tin, danh bạ, nhóm, Nhật ký và gọi thoại/video.

Unofficial native Zalo iOS client protocol for Swift — messaging, contacts, groups, timeline and voice/video calls.

Swift 5.10+ Platforms SwiftPM Dependencies License: MIT

Note

ZolaKit không phải API chính thức của Zalo/VNG. Thư viện nói chuyện với máy chủ Zalo bằng đúng giao thức mà app Zalo iOS dùng (client_type = 2, phiên bản giao thức 261002802): đăng nhập như một iPhone, nhận tin qua socket mã hoá UXChatSocket, gửi tin qua kênh failover, gọi điện qua relay ZRTC. Không dùng Zalo Web, không cần trình duyệt, không cần cookie.

Warning

Dùng thư viện này có thể khiến tài khoản Zalo bị khoá hoặc bị cấm. Tác giả không chịu trách nhiệm cho bất kỳ thiệt hại nào. Chỉ dùng với tài khoản của chính bạn, tuân thủ điều khoản sử dụng của Zalo, và không dùng để spam, quấy rối, thu thập dữ liệu người khác hay gửi tin hàng loạt.


Mục lục


Tính năng

Nhóm Bạn làm được gì
Tài khoản Đăng nhập SĐT + mật khẩu như iPhone, xử lý OTP (gọi/SMS hoặc thiết bị gần đây) và trang xác minh bảo mật; định danh thiết bị riêng cho mỗi máy; lưu/khôi phục phiên trong Keychain (macOS/Catalyst: tệp quyền 0600); thông tin tài khoản; gửi vào Cloud của tôi.
Tin nhắn 1-1 & nhóm Văn bản, trả lời (quote), nhắc tên @, ảnh (cả album), video, tệp, tin nhắn thoại (.m4a/.aac/.amr), sticker, link xem trước, vị trí, danh thiếp, thả cảm xúc, thu hồi, xoá phía tôi, đang soạn, đã xem; nhận tin realtime; đồng bộ hộp thư và tải lịch sử nhóm cũ hơn.
Danh bạ Tìm theo SĐT / username, hồ sơ người dùng, danh sách bạn bè, gửi/chấp nhận/từ chối/thu hồi lời mời kết bạn, trạng thái kết bạn, gợi ý kết bạn, đặt biệt danh, chặn/bỏ chặn, huỷ kết bạn.
Nhóm Danh sách nhóm, thông tin & thành viên, tạo nhóm, thêm/xoá thành viên, đổi tên, bật/tắt link mời; bình chọn, ghi chú, nhắc hẹn và bảng ghim của nhóm.
Hội thoại Ghim hội thoại, tắt thông báo, thẻ phân loại (tạo/sửa/xoá/gắn thẻ), tin nhắn nhanh, trả lời tự động.
Nhật ký & Khoảnh khắc Đọc Nhật ký bạn bè, đọc bình luận, thả tim, bình luận bài viết, đăng bài chữ/ảnh (Chỉ mình tôi hoặc Bạn bè), xoá bài; đọc thanh Khoảnh khắc và story của từng người.
Gọi thoại & video Gọi đi, nghe máy, từ chối, kết thúc, bật/tắt camera, nâng cấp gọi thoại → video; lắng nghe cuộc gọi đến; engine âm thanh Opus/G.711 có khử vọng (AEC), engine hình H.264 (VideoToolbox) qua relay ZRTC.
Tiện ích Kho lịch sử SQLite (tìm kiếm tiếng Việt không dấu), gợi ý sticker theo ngữ cảnh (hiểu kiểu gõ Telex), danh mục cảm xúc đầy đủ, chuẩn hoá âm thanh thoại.

Toàn bộ là Swift thuần, không phụ thuộc thư viện ngoài, dùng actor cho an toàn đa luồng.

Yêu cầu

  • iOS 16+ / macOS 13+ (chạy được cả Mac Catalyst)
  • Swift 5.10+ (Xcode 15.3 trở lên)
  • Một tài khoản Zalo đăng nhập được bằng SĐT + mật khẩu

Cài đặt

Swift Package Manager

// Package.swift
dependencies: [
    .package(url: "https://github.com/hailinhmacduc/ZolaKit-Swift.git", from: "1.0.0")
],
targets: [
    .target(name: "YourApp", dependencies: [
        .product(name: "ZolaKit", package: "ZolaKit-Swift")
    ])
]

Xcode

File → Add Package Dependencies… → dán https://github.com/hailinhmacduc/ZolaKit-Swift.git → chọn sản phẩm ZolaKit.

import ZolaKit

Bắt đầu nhanh

1. Đăng nhập

import ZolaKit

let auth = ZolaLoginClient()
var outcome = try await auth.login(phone: "0901234567", password: "mat-khau")

// Zalo có thể yêu cầu OTP ở lần đăng nhập đầu trên "thiết bị" mới
if case .challenge = outcome {
    let request = try await auth.requestVerificationCode(
        phone: "0901234567",
        method: .callOrSms,                       // hoặc .recentDevice
        existingChallenge: await auth.latestChallenge()
    )
    print(request.deliveryMessage)                // "Zalo sẽ gọi/nhắn mã tới…"
    let otp = "123456"                            // người dùng nhập
    outcome = try await auth.submitVerificationCode(
        phone: "0901234567", password: "mat-khau",
        code: otp, challenge: request.challenge
    )
}

switch outcome {
case .success(let result):
    let session = try result.makeSession()
    try ZolaKeychainSessionStore().save(session)  // lưu để lần sau khỏi đăng nhập
    let api = Zola().login(session: session)
    print("Đã đăng nhập UID:", await api.getOwnId())
case .secureVerification(let check):
    print("Zalo yêu cầu xác minh trên trang:", check.secureUrl)
case .rejected(let code, let message, _):
    print("Đăng nhập thất bại:", code ?? -1, message ?? "")
case .challenge:
    break
}

Lần sau chỉ cần khôi phục phiên:

let api = try Zola().loadKeychainSession(uid: 100_000_101)

2. Lắng nghe tin nhắn mới

for try await event in api.events(intervalSeconds: 2) {
    switch event.type {
    case "message.new":
        guard let msg = event.message else { continue }
        print("[\(msg.isGroup ? "nhóm" : "1-1") \(msg.threadId)] \(msg.senderName): \(msg.text)")
    case "message.reaction":
        print("Có người thả cảm xúc:", event.reaction as Any)
    case "session.expired":
        print("Phiên hết hạn — cần đăng nhập lại")
        return
    default:
        break
    }
}

events(...) trả về AsyncThrowingStream<ZolaEvent, Error>, gộp tin từ socket realtime, tin offline và tin preload. Các loại sự kiện: message.new, message.updated, message.reaction, session.expired (kèm delivery, typing khi có).

3. Gửi tin nhắn

let receipt = try await api.sendMessage(
    "Xin chào từ ZolaKit!",
    threadId: 100_000_102,
    type: .user,          // .group cho nhóm
    dryRun: false         // ⚠️ mặc định là true — xem mục dryRun
)
print(receipt.sent, receipt.serverGlobalMsgId ?? 0)

Chế độ an toàn dryRun

Hầu hết hàm ghi lên Zalo nhận tham số dryRun. Khi dryRun == true, ZolaKit dựng đầy đủ gói tin (mã hoá, ký, đóng khung) nhưng không gửi, rồi trả về receipt để bạn kiểm tra.

  • Nhóm hàm nguyên bản (sendMessage, sendText1To1, sendGroupText, sendVoice1To1, sendLink1To1, sendLocation1To1, sendContactCard1To1, sendToMe, các hàm Nhật ký/Khoảnh khắc, thẻ phân loại, bảng ghim…) mặc định dryRun = true — phải truyền dryRun: false thì mới gửi thật.
  • Nhóm hàm tương thích zca-js (uploadAndSendPhoto, uploadAndSendFile, sendSticker, addReaction, undo, deleteMessage, createGroup, blockUser…) mặc định dryRun = false.
  • Các hàm gửi media vào nhóm ở tầng thấp (sendPhotoGroup, sendVideoGroup, sendFileGroup, sendStickerGroup, sendGroupVoice, sendReactionGroup, pinNativeGroupMessage…) cần thêm groupSendEnabled: true — chốt chặn tránh vô tình gửi vào nhóm.

Hãy thử với dryRun: true trước khi bật gửi thật trong app của bạn.


Hướng dẫn theo chức năng

Các ví dụ dưới đây được biên dịch tự động trong Tests/ZolaKitTests/ReadmeExamplesCompileTests.swift, nên luôn khớp với API thật.

Tài khoản & phiên đăng nhập

let me = try await api.fetchAccountInfo()
print(me.uid, me.displayName, me.avatarUrl)

_ = try await api.sendToMe(text: "Ghi chú vào Cloud của tôi", dryRun: false)
let alive = try await api.keepAlive()        // kiểm tra phiên còn sống
  • ZolaLoginClient tự sinh định danh thiết bị riêng (IDFA, zcid, mã thiết bị ZDK) cho mỗi máy và lưu trong ZolaDeviceIdentityStore (Keychain ThisDeviceOnly). Đăng nhập lại trên cùng máy sẽ dùng lại đúng định danh đó.
  • ZolaKeychainSessionStore lưu ZolaSession (khoá phiên, cryptKey, keySet socket…) theo UID; ZolaFileSessionStore đọc/ghi JSON với quyền 0600 khi cần mang phiên sang tiến trình khác.
  • ZolaLoginOutcome có 4 trường hợp: .success, .challenge (cần OTP), .secureVerification (Zalo bắt mở trang xác minh secureUrl, xong gọi completeSecureVerification), .rejected.

Hộp thư & tin nhắn

// Đồng bộ hộp thư (1-1 + nhóm)
let conversations = try await api.syncInbox(discoverGroups: true)
await api.primeWatermarks(from: conversations)   // tránh phát lại tin cũ khi bắt đầu nghe
for c in conversations.prefix(20) {
    print(c.title, c.unreadCount, c.lastMessage?.text ?? "")
}
let userId: Int64 = 100_000_102
let groupId: Int64 = 900_000_201

// Văn bản vào nhóm, có @nhắc tên (pos/len tính theo ký tự trong text)
_ = try await api.sendGroupText(
    gid: groupId,
    text: "Chào @An",
    mentions: [ZolaMention(type: 0, uid: 100_000_101, pos: 5, len: 3)],
    dryRun: false
)

// Trả lời một tin vừa nhận
if let quote = incoming.quote {
    _ = try await api.sendQuotedText(text: "Đã nhận!", threadId: userId, quote: quote, dryRun: false)
}

// Ảnh / video / tệp / tin nhắn thoại — tự tải lên CDN của Zalo rồi gửi
_ = try await api.uploadAndSendPhoto(imageData: jpeg, threadId: userId, type: .user, caption: "Ảnh nè")
_ = try await api.uploadAndSendVideo(videoData: mp4, threadId: userId, type: .user)   // tự lấy thời lượng + ảnh bìa
_ = try await api.uploadAndSendFile(fileData: pdf, fileName: "bao-gia.pdf", threadId: userId, type: .user)
_ = try await api.uploadAndSendVoiceFile(audioData: m4a, threadId: userId, type: .user, durationMs: 3_000)

// Sticker, link, vị trí, danh thiếp
_ = try await api.sendStickerResolvingDetail(stickerId: 23_285, cateIdHint: 10_425, threadId: userId, type: .user)
_ = try await api.sendLink1To1(to: userId, url: "https://zalo.me", dryRun: false)
_ = try await api.sendLocation1To1(to: userId, latitude: 21.0288, longitude: 105.8520, title: "Hồ Gươm", dryRun: false)
_ = try await api.sendContactCard1To1(to: userId, contactUid: 100_000_103, contactName: "Lê Chi", dryRun: false)

// Cảm xúc, thu hồi, xoá phía tôi, đang soạn, đã xem
_ = try await api.addReaction("❤️", message: incoming, type: .user)   // nhận cả "/-heart", "👍", "😆", "😮", "😢", "😡"…
_ = try await api.undo(message: incoming, threadId: userId, type: .user)
_ = try await api.deleteMessage(incoming, threadId: userId, type: .user, onlyMe: true)
_ = try await api.sendTypingEvent(threadId: userId, type: .user)
_ = try await api.sendSeenEvent(messages: [incoming], type: .user)

// Tải lịch sử nhóm cũ hơn
let page = try await api.fetchOlderGroupHistory(gid: groupId, beforeGlobalMsgId: incoming.id)
print(page.messages.count, page.exhausted)

Tin nhắn thoại: .m4a/.wav/.caf/.mp3 được chuyển sang ADTS .aac như app Zalo gửi (ZolaADTS); khi nhận, ZolaAudioNormalizer / ZolaAMR chuẩn hoá .aac/.m4a/.amr để phát được bằng AVFoundation. Video lớn được chia gói 2 MB khi tải lên.

Danh bạ & kết bạn

if let user = try await api.findUser("0901234567") {
    print(user.uid, user.displayName, user.isFriend)
    let outcome = try await api.sendFriendRequest(toUid: user.uid, message: "Chào bạn, kết bạn nhé!")
    print(outcome)   // .sent hoặc .becameFriends (nếu họ đã mời bạn trước)
}

// Phân biệt rõ "không có Zalo" và "lỗi"
switch try await api.findUserByPhone("0987654321") {
case .found(let user): print("Tìm thấy", user.uid)
case .notFound:        print("SĐT chưa đăng ký Zalo")
case .failed(let code, let message): print(code, message)
}

let friends  = try await api.getAllFriends()
let profile  = try await api.getUserInfo(100_000_102)
let requests = try await api.fetchFriendRequests()          // lời mời đến + gợi ý
_ = try await api.acceptFriendRequest(fromUid: 100_000_104)
_ = try await api.rejectFriendRequest(fromUid: 100_000_105)
_ = try await api.undoFriendRequest(toUid: 100_000_106)      // thu hồi lời mời đã gửi
_ = try await api.changeFriendAlias("Chị Chi kế toán", friendId: 100_000_103)
_ = try await api.blockUser(100_000_107)

Nhóm

let groups = try await api.getAllGroups()
let info   = try await api.getGroupInfo(gid: 900_000_201)
print(info.name, info.totalMembers, info.adminIds)

let created = try await api.createGroup(name: "Nhóm dự án", members: [100_000_102, 100_000_103])
_ = try await api.addUserToGroup(groupId: 900_000_201, memberIds: [100_000_104])
_ = try await api.removeUserFromGroup(groupId: 900_000_201, memberIds: [100_000_104])
_ = try await api.changeGroupName("Nhóm dự án 2026", groupId: 900_000_201)
let link = try await api.enableGroupLink(groupId: 900_000_201)   // trả về link mời

Ngoài ra: fetchGroupPoll(pollId:groupId:) (chi tiết bình chọn), fetchNativePinBoard / pinNativeGroupMessage / unpinNativeGroupMessage (bảng ghim); sự kiện ghi chú/nhắc hẹn/bình chọn được tách thành boardCard trên ZolaMessage.

Ghim, tắt thông báo, thẻ phân loại

_ = try await api.setPinnedConversations(pinned: true, threadIds: [100_000_102], type: .user)
_ = try await api.setMute(threadId: 900_000_201, durationSeconds: 3_600, type: .group)   // -1 = tắt vô thời hạn

let tags = try await api.fetchChatTags()
print(tags.labelData.map(\.text))
let tag = try await api.createChatTag(text: "Khách VIP", color: "#0068FF", dryRun: false)
_ = try await api.updateConversationTags(
    threadId: 100_000_102, isGroup: false, addTagIds: [tag.id], removeTagIds: [], dryRun: false
)

Nhật ký & Khoảnh khắc

// Hàm đọc cũng mặc định dryRun: true (trả nil) — truyền false để gọi máy chủ.
if let page = try await api.fetchTimelineFeed(dryRun: false) {
    for post in page.posts {
        print(post.authorName, post.caption, post.photos.count, post.likeCount)
    }
    if let first = page.posts.first {
        let comments = try await api.fetchFeedComments(feedId: first.id, dryRun: false)
        _ = try await api.reactToFeed(feedId: first.id, like: true, dryRun: false)
        _ = try await api.commentOnFeed(feedId: first.id, text: "Đẹp quá!", dryRun: false)
    }
    if let next = page.nextCursor {
        _ = try await api.fetchTimelineFeed(cursor: next, dryRun: false)   // trang kế
    }
}

// Đăng / xoá bài
let feedId = try await api.postTimelineText("Hôm nay trời đẹp", privacy: .onlyMe, dryRun: false)
if let feedId { _ = try await api.deleteTimelinePost(feedId: feedId, dryRun: false) }
// Ảnh: postTimelinePhoto(jpegData:width:height:caption:privacy:dryRun:)

// Khoảnh khắc (story) — chỉ đọc, không tăng lượt xem
if let bar = try await api.fetchStoryUsers(dryRun: false) {
    for user in bar.users {
        let stories = try await api.fetchUserStories(userId: user.uid, dryRun: false)
        print(user.name, stories?.count ?? 0)
    }
}

Gọi thoại & gọi video

ZolaKit làm cả báo hiệu (mời, đổ chuông, nghe, kết thúc… qua socket 0x7d0) lẫn media (ZolaVoipMediaEngine: Opus 48 kHz / G.711 qua relay ZRTC UDP, khử vọng bằng Voice-Processing I/O; video H.264 qua VideoToolbox).

let myUid = Int64(await api.getOwnId()) ?? 0

await api.setVoipEventHandler { event in
    switch event {
    case .incomingInvite(let callId, let partnerUid, let isVideo, let callerName, _, let rtp, _, let sessionId):
        print("Cuộc gọi đến từ \(callerName)")
        Task {
            do {
                try await api.answerVoipCall(partnerUid: partnerUid, callId: callId, isVideo: isVideo,
                                             rtpAddress: rtp, sessionId: sessionId)
                let engine = ZolaVoipMediaEngine(callId: callId)
                engine.configureZrtcSession(isCaller: false, selfUid: myUid, partnerUid: partnerUid, sessionId: sessionId)
                let parts = rtp.split(separator: ":")
                if parts.count == 2, let port = UInt16(parts[1]) {
                    try engine.start(relay: .init(host: String(parts[0]), port: port), preferredCodec: .opus)
                }
            } catch {
                print("Không nghe máy được:", error)
            }
        }
    case .answered(let callId, _):          print("Đã nghe máy", callId)
    case .ended(let callId, _, let reason): print("Kết thúc", callId, reason)
    case .failed(_, _, let code, let message): print("Lỗi", code, message)
    default: break
    }
}
try await api.startVoipIncomingListener()

// Gọi đi
let call = try await api.startVoipCall(partnerUid: 100_000_102, isVideo: false)
if let engine = await api.takePreparedVoipMediaEngine(forCallId: call.callId) {
    engine.setSpeakerphone(true)   // engine đã bắt tay relay sẵn trong lúc mời
}

// Cúp máy
try await api.cancelVoipCall(partnerUid: 100_000_102, callId: call.callId, durationSeconds: 42, isConnected: true)

Video:

engine.setVideoMode(enabled: true, cameraEnabled: true, preferFrontCamera: true)
engine.onRemoteVideoPixelBuffer = { pixelBuffer, time in
    // hiển thị bằng AVSampleBufferDisplayLayer / Metal
}

Các hàm khác: ackVoipRinging, rejectVoipCall, sendVoipCameraState, upgradeVoipToVideo, voipCallEndpoints(forCallId:), stopVoipIncomingListener, sendCallBubble1To1 (ghi log cuộc gọi vào khung chat).

Cần thêm trong app của bạn:

Info.plist Giá trị
NSMicrophoneUsageDescription lý do dùng micro
NSCameraUsageDescription lý do dùng camera (gọi video)
ZolaKitAECTrial 1 để bật khử vọng (Voice-Processing I/O) — nên bật cho gọi video
UIBackgroundModes audio để giữ cuộc gọi khi tắt màn hình

Important

ZolaKit không kèm CallKit/PushKit. Thông báo đẩy cuộc gọi của Zalo chỉ gửi tới app Zalo chính thức, nên app của bạn nhận cuộc gọi đến khi startVoipIncomingListener() đang chạy (app đang mở hoặc đang giữ phiên âm thanh nền). Giao diện cuộc gọi hệ thống là phần việc của app.

Lưu lịch sử trên máy (SQLite)

let store = try ZolaMessageStore(fileURL: dbURL)          // SQLite WAL, quyền 0600
let uid = Int64(await api.getOwnId()) ?? 0
let conversations = try await api.syncInbox()
try store.upsertConversations(conversations.map { (accountUid: uid, conversation: $0) })

let recent = try store.messages(accountUid: uid, threadId: 100_000_102, limit: 50)
let hits   = try store.matchingThreadKeys(query: "hop dong bao hanh")   // gõ không dấu vẫn khớp "hợp đồng bảo hành"

Hỗ trợ nhiều tài khoản trong cùng một tệp, phân trang beforeTsMs, nâng ID tạm (c:<cliMsgId>) lên ID máy chủ (g:<globalMsgId>) khi tin được xác nhận, xoá theo tin/hội thoại/tài khoản.

Gợi ý sticker tiếng Việt

// Khớp tức thì, không gọi mạng — phân biệt chữ đang gõ Telex dở ("buôn" trước khi gõ "f") với chữ đã có dấu
if let match = ZolaStickerSuggester.instantMatch(for: "cảm ơn nhé") {
    print(match)
}
// Gộp gợi ý của Zalo (suggest/search) với bộ sticker đã kiểm chứng
let suggestions = await api.suggestContextualStickers(for: "cảm ơn nhé", limit: 12)

Danh sách API

Tất cả là phương thức của ZolaClient (một actor), trừ khi ghi khác. Tham số type: ZolaThreadType nhận .user hoặc .group.

Khởi tạo & đăng nhập

API Mô tả
Zola().login(session:) Tạo ZolaClient từ một ZolaSession
Zola().loginWithPassword(phone:password:) Đăng nhập một bước, trả ZolaLoginOutcome
Zola().loadKeychainSession(uid:) Khôi phục phiên đã lưu trong Keychain
Zola().loadFileSession(url:) Khôi phục phiên từ tệp JSON
ZolaLoginClient.login(phone:password:) Đăng nhập (precheck → mật khẩu)
ZolaLoginClient.requestVerificationCode(phone:method:existingChallenge:) Xin mã OTP (.callOrSms / .recentDevice)
ZolaLoginClient.submitVerificationCode(phone:password:code:challenge:) Gửi OTP
ZolaLoginClient.completeSecureVerification(...) Hoàn tất xác minh trang bảo mật
ZolaLoginResult.makeSession() Chuyển kết quả đăng nhập thành ZolaSession
ZolaKeychainSessionStore.save / load / delete Lưu phiên trong Keychain
getOwnId(), getContext(), fetchAccountInfo(), keepAlive() Thông tin phiên & tài khoản

Nhận tin

API Mô tả
events(intervalSeconds:includePreload:) Luồng ZolaEvent realtime (tên kiểu zca-js)
eventStream(intervalSeconds:includePreload:) Như trên (tên gốc)
syncInbox(discoverGroups:) Danh sách hội thoại + tin gần nhất
primeWatermarks(from:) Đánh dấu mốc để không phát lại tin cũ
pollOnce(...), drainOfflineHistory(...) Lấy tin một lần / rút hết tin offline
fetchOlderGroupHistory(gid:beforeGlobalMsgId:) Lịch sử nhóm cũ hơn
setRealtimeEventHandler(_:) Nhận sự kiện qua callback thay vì stream

Gửi tin

API Mô tả
sendMessage(_:threadId:type:dryRun:) Văn bản (1-1 hoặc nhóm), hỗ trợ quote/ttl qua ZolaMessagePayload
sendText1To1(to:text:...), sendGroupText(gid:text:mentions:...) Văn bản tầng gốc, nhắc tên trong nhóm
sendQuotedText(text:threadId:quote:) Trả lời tin
uploadAndSendPhoto(imageData:threadId:...) Ảnh (có mediaGroup để gửi album)
uploadAndSendVideo(videoData:threadId:...) Video
uploadAndSendFile(fileData:fileName:threadId:...) Tệp tài liệu
uploadAndSendVoiceFile(audioData:threadId:durationMs:...), sendVoiceFile(...) Tin nhắn thoại từ dữ liệu âm thanh
sendVoice(voiceUrl:threadId:...), sendVoice1To1, sendVoiceGroup Tin nhắn thoại từ URL đã tải lên
sendSticker(...), sendStickerResolvingDetail(...) Sticker
sendLink1To1, sendLocation1To1, sendContactCard1To1, sendFile1To1, sendPhoto1To1 Link, vị trí, danh thiếp, tệp/ảnh từ URL
sendPhotoGroup, sendVideoGroup, sendFileGroup, sendStickerGroup, sendGroupVoice, sendMediaGroup Media vào nhóm (cần groupSendEnabled: true)
sendToMe(text:) Gửi vào Cloud của tôi
addReaction(_:message:type:), sendReaction1To1, sendNativeReaction1To1, sendReactionGroup Thả / gỡ cảm xúc
undo(message:threadId:type:), recallNative(...) Thu hồi
deleteMessage(_:threadId:type:onlyMe:) Xoá tin
sendTypingEvent(threadId:type:), sendSeenEvent(messages:type:) Đang soạn / đã xem
uploadAttachment(...), uploadMediaNativeHTTP(...), uploadMediaForPublicURL(...) Chỉ tải lên, không gửi
parseLink(_:), resolveLinkMetadata(_:) Lấy tiêu đề/ảnh xem trước của link

Danh bạ

API Mô tả
findUser(_:countryCode:), findUserByPhone(_:), findUserByUsername(_:) Tìm người dùng
getMultiUsersByPhones(_:) Tra nhiều SĐT một lần (dùng có chừng mực)
getUserInfo(_:), getUserProfile(uid:) Hồ sơ
getAllFriends(), listFriends() Danh sách bạn bè
sendFriendRequest(toUid:message:) Gửi lời mời
fetchFriendRequests(), getFriendRecommendations() Lời mời đến, gợi ý
fetchSentFriendRequests(), getSentFriendRequest() Lời mời đã gửi
acceptFriendRequest(fromUid:), rejectFriendRequest(fromUid:), undoFriendRequest(toUid:) Xử lý lời mời
getPeerFriendStatus(_:), getFriendRequestStatus(_:) Trạng thái kết bạn
changeFriendAlias(_:friendId:), removeFriendAlias(_:), getAliasList() Biệt danh
blockUser(_:), unblockUser(_:), removeFriend(_:) Chặn / huỷ kết bạn
getQR(_:) Mã QR của người dùng

Nhóm & hội thoại

API Mô tả
getAllGroups(), listJoinedGroups(), getGroupInfo(gid:) Nhóm và thành viên
createGroup(name:members:), addUserToGroup(groupId:memberIds:), removeUserFromGroup(groupId:memberIds:) Quản lý thành viên
changeGroupName(_:groupId:) Đổi tên nhóm
enableGroupLink(groupId:), disableGroupLink(groupId:), getGroupLinkDetail(groupId:) Link mời
fetchGroupPoll(pollId:groupId:) Bình chọn
fetchNativePinBoard, pinNativeUserMessage, pinNativeGroupMessage, unpinNative… Bảng ghim
getPinConversations(), setPinnedConversations(pinned:threadIds:type:) Ghim hội thoại
getMute(), fetchMuteList(), setMute(threadId:durationSeconds:unmute:type:) Tắt thông báo
fetchChatTags(), createChatTag, updateChatTag, deleteChatTags, updateConversationTags, getLabels(), updateLabels(...) Thẻ phân loại
getQuickMessageList(), getAutoReplyList() Tin nhắn nhanh, trả lời tự động
getStickers(_:), getStickersDetail(_:), fetchStickerPackItems(cateId:), suggestContextualStickers(for:) Sticker
custom(url:params:method:) Gọi một endpoint native tuỳ ý (tham số mã hoá theo zcid)

Nhật ký & Khoảnh khắc

API Mô tả
fetchTimelineFeed(cursor:dryRun:) Đọc Nhật ký (phân trang bằng ZolaFeedCursor)
fetchFeedComments(feedId:lastCommentId:dryRun:) Bình luận của một bài
reactToFeed(feedId:like:dryRun:), commentOnFeed(feedId:text:dryRun:) Thả tim, bình luận
postTimelineText(_:privacy:dryRun:), postTimelinePhoto(jpegData:...), deleteTimelinePost(feedId:) Đăng / xoá bài
fetchStoryUsers(page:lastUserId:dryRun:), fetchUserStories(userId:dryRun:) Khoảnh khắc

Gọi thoại & video

API Mô tả
setVoipEventHandler(_:) Nhận ZolaVoipCallEvent: connecting, ringing, answered, busy, rejected, ended, incomingInvite, partnerCameraChanged, failed
startVoipIncomingListener(), stopVoipIncomingListener() Lắng nghe cuộc gọi đến
startVoipCall(partnerUid:isVideo:) Gọi đi, trả ZolaVoipCallReceipt (callId, relay, sessionId…)
takePreparedVoipMediaEngine(forCallId:) Lấy engine media đã bắt tay relay sẵn
answerVoipCall, ackVoipRinging, rejectVoipCall, cancelVoipCall Nghe / đổ chuông / từ chối / kết thúc
sendVoipCameraState, upgradeVoipToVideo, isActiveVoipCallVideo() Camera, nâng lên gọi video
ZolaVoipMediaEngine configureZrtcSession, start(relay:), setMuted, setSpeakerphone, setVideoMode, setCameraEnabled, onRemoteVideoPixelBuffer, stop()

Tiện ích

API Mô tả
ZolaMessageStore Kho SQLite: upsertMessages, upsertConversations, messages, threads, matchingThreadKeys, searchMessagesInThread, delete…
ZolaStickerSuggester.instantMatch(for:) Gợi ý sticker tức thì
ZolaADTS, ZolaAMR, ZolaAudioNormalizer Chuyển đổi / chuẩn hoá âm thanh thoại
ZolaReactionCatalog Danh mục mã cảm xúc đầy đủ của Zalo
ZolaTextNormalizer Bỏ dấu tiếng Việt để tìm kiếm

Tương thích tên hàm zca-js

Nếu bạn đã quen zca-js, phần lớn tên hàm được giữ để chuyển code dễ hơn:

zca-js ZolaKit
new Zalo().login(credentials) Zola().login(session:) / Zola().loginWithPassword(phone:password:)
api.listener.on("message", …) for try await e in api.events()
api.sendMessage(msg, threadId, type) api.sendMessage(msg, threadId:type:dryRun:)
api.sendSticker(sticker, threadId, type) api.sendSticker(stickerId:cateId:stickerType:threadId:type:)
api.addReaction(icon, dest) api.addReaction(_:message:type:)
api.undo(payload, threadId, type) api.undo(message:threadId:type:)
api.deleteMessage(dest, onlyMe) api.deleteMessage(_:threadId:type:onlyMe:)
api.findUser(phone) api.findUser(_:)
api.getUserInfo(userId) api.getUserInfo(_:)
api.getAllFriends() api.getAllFriends()
api.sendFriendRequest(msg, userId) api.sendFriendRequest(toUid:message:)
api.acceptFriendRequest(userId) api.acceptFriendRequest(fromUid:)
api.getAllGroups() / api.getGroupInfo(id) api.getAllGroups() / api.getGroupInfo(gid:)
api.createGroup(options) api.createGroup(name:members:)
api.addUserToGroup(memberId, groupId) api.addUserToGroup(groupId:memberIds:)
api.changeGroupName(name, groupId) api.changeGroupName(_:groupId:)
api.blockUser(userId) api.blockUser(_:)
api.sendTypingEvent(threadId, type) api.sendTypingEvent(threadId:type:)
api.getStickers(keyword) api.getStickers(_:)
api.getLabels() api.getLabels() / api.fetchChatTags()
api.getOwnId() api.getOwnId()

Khác biệt chính: zca-js giả lập Zalo Web (cookie + IMEI trình duyệt), còn ZolaKit là client iOS gốc (đăng nhập bằng SĐT + mật khẩu, socket mã hoá, gọi thoại/video, Nhật ký…). Hai bên không dùng chung phiên.


Kiến trúc

Sources/ZolaKit/
├── ZolaLogin.swift                 Đăng nhập native, OTP, xác minh, định danh thiết bị
├── ZolaSessionStore.swift          Lưu phiên: Keychain / tệp 0600
├── ZolaZCA.swift                   Lớp API kiểu zca-js (Zola, sendMessage, findUser…)
├── ZolaClient.swift                Actor chính: socket, hộp thư, gửi/nhận, bạn bè, nhóm
├── ZolaCrypto.swift                AES-CBC/GCM, X25519, khung ChatElement, ký MD5
├── ZolaTransport.swift             HTTP: ký tham số, mã hoá zcid, failover
├── ZolaModels.swift                Mô hình dữ liệu (ZolaMessage, ZolaUser, ZolaGroup…)
├── ZolaNativeMediaUpload.swift     Tải lên ảnh/video/tệp/thoại theo kiểu app iOS
├── ZolaGroupMedia.swift            Gửi media vào nhóm
├── ZolaNativeChatSignals.swift     Đang soạn, đã xem, đã nhận, thu hồi qua socket
├── ZolaNativePinBoard.swift        Bảng ghim
├── ZolaGroupPoll.swift             Bình chọn
├── ZolaChatTags.swift              Thẻ phân loại
├── ZolaTimelineFeed.swift          Nhật ký (đọc)
├── ZolaFeedComposer.swift          Đăng / xoá bài
├── ZolaFeedComments.swift          Bình luận
├── ZolaSocialActions.swift         Thả tim, bình luận
├── ZolaStoryFeed.swift             Khoảnh khắc
├── ZolaMessageStore.swift          Kho lịch sử SQLite
├── ZolaStickerSuggester.swift      Gợi ý sticker
├── ZolaADTS.swift, ZolaAMR.swift   Âm thanh thoại
└── Call/                           Gọi thoại & video
    ├── ZolaClient+VoipCall.swift              Báo hiệu cuộc gọi đi/đến
    ├── ZolaClient+IncomingCallListener.swift  Lắng nghe cuộc gọi đến
    ├── ZolaVoipSocket.swift                   Phiên socket VoIP, máy trạng thái
    ├── ZolaVoipMediaEngine.swift              Âm thanh RTP/ZRTC, AEC
    ├── ZolaVoipVideoEngine.swift              H.264 RTP/RTCP, camera
    └── ZolaCrypto+Voip.swift, ZolaRequestBuilder+Voip.swift, ZolaAudio*.swift

Luồng dữ liệu:

  1. Đăng nhập (register.zaloapp.com): precheck → mật khẩu (mã hoá) → (OTP) → nhận sessionKey, cryptKey, danh sách máy chủ socket và keySet.
  2. Nhận tin: UXChatSocket (TCP, AES-256-GCM, bắt tay X25519) cho realtime; HTTP femc/mfetch cho tin offline và preload; tự xoay keySet khi máy chủ báo -67.
  3. Gửi tin: khung ChatElement nhị phân, mã hoá bằng cryptKey, gửi qua failover/socket; xác nhận bằng deliver.gmi của máy chủ.
  4. Gọi: lệnh VoIP (cmd 401…425) trên socket chung + media UDP qua relay ZRTC.

Bảo mật & giữ phiên đăng nhập

  • Không in/ghi log ZolaSession, sessionKey, cryptKey, zcid. description của ZolaSession và ZolaLoginResult đã che giá trị nhạy cảm.
  • Lưu phiên bằng ZolaKeychainSessionStore (Keychain ThisDeviceOnly); trên macOS/Catalyst dùng tệp quyền 0600.
  • Mỗi máy có định danh thiết bị riêng (ZolaDeviceIdentityStore). Đừng sao chép một định danh sang nhiều máy hay nhiều tài khoản.
  • ZolaKit chặn mọi endpoint Zalo Web (*-wpa.chat.zalo.me, xem ZolaClient.isForbiddenWebWpaURL) vì gọi Web bằng phiên iOS có thể khiến Zalo từ chối hoặc thu hồi phiên.
  • Phiên bị Zalo vô hiệu hoá (lỗi 102, -96, sự kiện session.expired) không cứu được bằng code — chỉ đăng nhập lại. Đừng đăng nhập lại liên tục; hãy báo người dùng.
  • Giữ tần suất gửi như người thật. Gửi hàng loạt, thêm bạn hàng loạt hay vào nhóm hàng loạt là cách nhanh nhất để mất tài khoản.

Chạy test

swift build
swift test                               # toàn bộ (~430 test, chạy offline)
swift test --filter ZolaKitCallTests     # chỉ phần gọi thoại/video

Test chạy hoàn toàn offline: dùng transport giả lập và khung byte mẫu với dữ liệu giả, không cần tài khoản Zalo.

Câu hỏi thường gặp

ZolaKit có dùng chung phiên với zca-js / Zalo Web không? Không. ZolaKit đăng nhập như một iPhone; phiên của bên này không dùng được cho bên kia.

Đăng nhập bằng ZolaKit có ảnh hưởng app Zalo trên điện thoại không? ZolaKit đóng vai một iPhone nên Zalo có thể yêu cầu OTP, cảnh báo đăng nhập thiết bị mới, hoặc đăng xuất phiên di động khác. Nên thử với tài khoản riêng.

Vì sao sendMessage trả về sent == false? Bạn chưa truyền dryRun: false. Xem Chế độ an toàn dryRun.

Có chạy trên Linux / server không? Phần lõi dùng Foundation, CryptoKit, Network, Security (Keychain), AVFoundation và SQLite của Apple, nên hiện chỉ hỗ trợ iOS/macOS.

Zalo đổi giao thức thì sao? ZolaKit bám theo giao thức của Zalo iOS 26.10.02 (261002802). Khi Zalo nâng cấp, một số lệnh có thể đổi. Hãy mở issue kèm log (đã che thông tin phiên).

Đóng góp

Issue và pull request đều được chào đón. Khi gửi PR:

  • Chạy swift test và giữ toàn bộ test xanh.
  • Không đưa dữ liệu thật vào repo: SĐT, UID, tên, ảnh, zcid, IDFA, khoá phiên, cookie. Dùng giá trị giả như các test hiện có.
  • Không thêm tính năng gửi tin / kết bạn / vào nhóm hàng loạt.

Repo này là bản phát hành dạng snapshot; việc cập nhật và gộp PR do người duy trì quyết định.

Giấy phép

MIT © 2026 hailinhmacduc.

ZolaKit là dự án độc lập, không liên kết, không được tài trợ hay chứng thực bởi Zalo, VNG Corporation hay Apple. "Zalo" là nhãn hiệu của VNG Corporation.

About

Unofficial native Zalo iOS protocol SDK for Swift — messaging, contacts, groups, timeline and voice/video calls (iOS 16+ / macOS 13+, zero dependencies)

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

0