HCaptchaSwift

一个轻量级的 hCaptcha 实现,用于服务器端的 Swift 应用程序。与官方的 HCaptcha-ios-sdk 不同,该软件包不依赖于 WKWebView 或任何其他 UI 层元素,而是仅仅实现了 HCaptcha 的后端验证部分。

添加软件包

目前仅支持 SwiftPM。

要添加软件包,只需在 Xcode 中选择 File / Add Packages...,然后将此 URL 粘贴到搜索/URL 框中:https://github.com/aronbudinszky/hcaptcha-swift

用法

步骤 1

您应该通过 标准文档记录的方法 和/或其中一个前端封装器/插件,在您的网站上显示 HCaptcha 小部件。

这将生成一个客户端 token,您可以提交并在服务器端进行验证。

步骤 2

生成客户端小部件后,使用此软件包可以轻松地通过任何选择的服务器端 Swift 解决方案(例如 Vapor)验证它生成的 token,如下所示:

        // Create the client
        let hCaptchaClient = HCaptchaSwift.Client(secret: "- your secret token -")

        // Now try to verify
        let response = try await hCaptchaClient.verify(
            "- verification token you received when the user completed the captcha -",
            remoteIp: "- user's remote ip (optional) -",
            siteKey: "- your site key (optional, but recommended)"
        )
        // - Note: In case of any errors (including when verification fails) the returned hCaptcha error codes will be thrown (see docs). But generally non-spam users won't be sending invalid verification tokens anyway (unless your implementation is weird / wrong), so regular users won't see these errors.

        guard response else {
            print("Verification failed.")
            // This usually won't happen, but good to check just in case. Typically an error should already be thrown above if this is false. (Unfortunately hCaptcha docs are a bit unclear on this.)
            return
        }
        
        print("Yay! You are not a bot!")