Lightspark Wallet Swift SDK
这是 Lightspark Wallet API 的 Swift 钱包 SDK。它可以从 iOS 环境中用于与 Lightspark Lightning 钱包集成。
安装
Swift 包管理器
Lightspark Wallet SDK 与 Swift 包管理器 v5 兼容(Swift 5 及以上)。只需将其添加到您的 Package.swift 中的依赖之中。
dependencies: [
.package(url: "https://github.com/lightsparkdev/swift-wallet-sdk.git", )
]
然后将其添加到您的目标依赖中
targets: [
.target(
name: "MyProject",
dependencies: [
.product(name: "LightsparkWallet", package: "swift-wallet-sdk"),
]
),
.testTarget(
name: "MyProjectTests",
dependencies: ["MyProject"])
]
安装完成后,您可以在您的 Swift 文件中导入 LightsparkWallet
。
import LightsparkWallet
开始使用
SDK 的主要入口点是 WalletClient
。要初始化 WalletClient
,需要一个访问令牌。这个 accessToken
可以通过 JWTAuthManager
获得。
let walletClient = WalletClient(accessToken: accessToken)
对于 WalletClient
中的每个操作,我们提供了三种使用方式
- 发布者:使用 Swift Combine 框架返回结果的发布者。
- 完成块:使用完成块进行回调。
- Swift async await 功能:使用 Swift async await 返回结果。
例如,要执行 getCurrentWallet
操作,可以这样做
// Using publisher
var cancellables = [AnyCancellables]()
walletClient.getCurrentWalletPublisher()
.sink() { completion in
// handle completion
} receiveValue { wallet in
// handle result
}
.store(in: &cancellables)
}
// Using completion block
walletClient.getCurrentWallet() { wallet, error in
// handle completion block
}
// Using async await
do {
let wallet = try await walletClient.getCurrentWallet()
} catch {
// handle error
}
JWT 鉴权
SDK 当前版本支持 JWT 鉴权,适用于客户端使用。要进行鉴权,您需要使用您的 Lightspark 账户 ID 和您自己的服务器为用户分配的 JWT 登录。
首先,您需要将您的账户公钥注册到 Lightspark。您可以通过 Lightspark API Tokens 页面 来完成此操作。您需要提供您想用于签名 JWTs 的账户公钥。您可以使用以下命令使用 _ES256_ 算法生成密钥对
openssl genrsa -out private.key 2048
这将生成一个名为 private.key 的私钥文件。然后您可以使用以下命令生成公钥文件
openssl rsa -in private.key -pubout -out public.key
然后您可以将公钥文件的 contenido 复制到 API Tokens 页面上的“JWT 公钥”字段。您还希望将私钥复制到您的服务器代码中(或者在秘密密钥存储或环境变量中),这样您就可以使用它来签名 JWTs。
接下来,您需要为用户创建一个 JWT。您应该从您自己的后端公开一个端点来创建这些令牌。例如,从 TypeScript + Node 服务器创建 JWT
import * as jwt from "jsonwebtoken";
// Create a JSON object that contains the claims for your JWT.
const claims = {
aud: "https://api.lightspark.com",
// Any unique identifier for the user.
sub: "511c7eb8-9afe-4f69-989a-8d1113a33f3d",
// True to use the test environment, false to use the production environment.
test: true,
iat: 1516239022,
// Expriation time for the JWT.
exp: 1799393363,
};
// Call the `sign()` method on the `jsonwebtoken` library, passing in the JSON object and your private key.
const token = jwt.sign(claims, "your private key");
// Now send the token back to the client so that they can use it to authenticate with the Lightspark SDK.
现在在客户端,您可以使用 JWT 和您的公司在 API Tokens 页面上的账户 ID 进行登录
let authManager = JWTAuthManager()
authManager.login(accountID: self.accountID, secret: self.walletToken) { accessToken, error in
guard let access = access else {
// handle error
return
}
let walletClient = WalletClient(accessToken: accessToken)
}
示例应用
有关更多示例,请参阅 /DemoApp 中的示例应用。