C# / .NET SDK

安装

安装适用于 .NET 的 Unimatrix SDK 的推荐方法是使用 nuget 包管理器,可在 NuGet 上获得。

如果您使用 .NET CLI 构建项目,运行以下命令将 UniSdk 添加为项目依赖:

dotnet add package UniSdk

如果您使用的是 Visual Studio IDE,请在程序包管理器控制台中运行以下命令:

Install-Package UniSdk

使用示例

以下示例展示如何使用 Unimatrix .NET SDK 快速调用 Unimatrix 服务。

初始化客户端

using UniSdk;

var client = new UniClient("your access key id", "your access key secret"); // 若使用简易验签模式仅传入第一个参数即可
client.SetEndpoint("https://api-cn.unimtx.com"); // 设置接入点到中国大陆, 若使用全球节点请移除此行代码

或者您也可以通过环境变量来配置您的访问凭证:

export UNIMTX_ACCESS_KEY_ID=your_access_key_id
export UNIMTX_ACCESS_KEY_SECRET=your_access_key_secret

发送短信

向单个收件人发送短信

using System;
using UniSdk;

class Program
{
    static void Main(string[] args)
    {
        var client = new UniClient();

        try
        {
            var resp = client.Messages.Send(new {
                to = "+861865800xxxx", // 以 E.164 格式传入手机号
                signature = "合一矩阵", // 替换为您的短信签名
                content = "您的验证码是123456,5分钟内有效。"
            });
            Console.WriteLine(resp.Data);
        }
        catch (UniException ex)
        {
            Console.WriteLine(ex);
        }
    }
}

或者使用异步方法:

using System;
using System.Threading.Tasks;
using UniSdk;

class Program
{
    static async Task Main(string[] args)
    {
        var client = new UniClient();

        try
        {
            var resp = await client.Messages.SendAsync(new {
                // ...
            });
            Console.WriteLine(resp.Data);
        }
        catch (UniException ex)
        {
            Console.WriteLine(ex);
        }
    }
}

使用模版和模版变量发送短信

client.Messages.Send(new {
    to = "+861865800xxxx",
    signature = "合一矩阵",
    templateId = "pub_verif_ttl2",
    templateData = new {
        code = "123456",
        ttl = "5"
    }
});

发送验证码

向用户发送验证码/一次性验证码(OTP),以下示例将向用户发送一个自动生成的验证码

using System;
using UniSdk;

class Program
{
    static void Main(string[] args)
    {
        var client = new UniClient();
        var resp = client.Otp.Send(new {
            to = "+861865800xxxx",
            signature = "合一矩阵" // 替换为您的短信签名
        });
        Console.WriteLine(resp.Data);
    }
}

校验验证码

校验用户提交的验证码/一次性验证码(OTP),以下示例将检查用户提供的验证码是否正确

using System;
using UniSdk;

class Program
{
    static void Main(string[] args)
    {
        var client = new UniClient();
        var resp = client.Otp.Verify(new {
            to = "+861865800xxxx",
            code = "123456" // 用户提交的验证码
        });
        Console.WriteLine(resp.Valid);
    }
}