Integrazione dei pagamenti Semantic Kernel.
Nessun pacchetto Semantic Kernel necessario. Avvolgi il vero client blockchain0x in una KernelFunction (Python o Java), o chiama l'API REST da una KernelFunction C#. In entrambi i casi l'agente sposta USDC su Base.
Non esiste un pacchetto Semantic Kernel. In Python avvolgi il vero client blockchain0x in un metodo decorato con @kernel_function; in C#, dove non viene fornito alcun SDK .NET, un [KernelFunction] chiama direttamente l'API REST. Registralo sul tuo kernel, imposta FunctionChoiceBehavior su Auto, e l'agente può muovere USDC su Base. Gli SDK core forniti sono Node, Python, Ruby, Go e JVM.
L'unico framework agent .NET di livello enterprise.
Se il tuo stack è di tipo Microsoft (Azure, .NET, SQL Server, Teams, Copilot Studio), Semantic Kernel è quasi certamente il framework per agenti giusto. È costruito da Microsoft, si integra con Azure OpenAI, AKS e Entra, e ha supporto di prima classe in .NET, Python e Java in un modo che nessun altro framework eguaglia. E ti fornisce già ciò di cui hai bisogno: una KernelFunction è solo un metodo, quindi collegare i pagamenti è un metodo che scrivi, non un pacchetto su cui aspetti.
Ecco perché non esiste un adattatore Semantic Kernel da installare. In Python e Java incapsuli il vero SDK blockchain0x in una KernelFunction; in C#, dove non esiste ancora un SDK .NET, la KernelFunction chiama direttamente l'API REST con HttpClient. Mantieni un'ergonomia idiomatica - metodi decorati, async, validazione dei parametri basata su attributi - e non c'è una versione dell'adattatore da tenere traccia. Gli SDK principali che esistono oggi sono Node, Python, Ruby, Go e JVM.
Installa Semantic Kernel e, in Python, il core SDK.
Non esiste un pacchetto blockchain0x Semantic Kernel da aggiungere. Python installa Semantic Kernel più il vero SDK blockchain0x; C# installa Microsoft.SemanticKernel e chiama l'API REST con l'HttpClient integrato. Java utilizza Semantic Kernel per Java più l'SDK com.blockchain0x:sdk-jvm.
pip install semantic-kernel blockchain0xdotnet add package Microsoft.SemanticKernelBLOCKCHAIN0X_API_KEY=sk_test_... # sk_test_ = Base Sepolia, sk_live_ = Base mainnet BLOCKCHAIN0X_API_KEY=sk_test_... # same key, the name the .NET REST example reads OPENAI_API_KEY=sk-...
BLOCKCHAIN0X_API_KEY (il client Python legge questo valore) è una chiave sk_test_ per testnet o sk_live_ per mainnet dalla tua dashboard; l'esempio C# REST legge lo stesso valore da BLOCKCHAIN0X_API_KEY. OPENAI_API_KEY (o AZURE_OPENAI_* per i modelli ospitati su Azure) è la tua chiave LLM. Il gestore webhook richiede inoltre BLOCKCHAIN0X_WEBHOOK_SECRET.
Una KernelFunction del wallet, in Python e C#.
Python avvolge il vero client blockchain0x in un metodo decorato con @kernel_function. C#, dove non viene fornito alcun SDK .NET, espone un [KernelFunction] che chiama direttamente POST /v1/payments con HttpClient. Entrambi si registrano nel kernel come Wallet.send_usdc; solo la cerimonia circostante differisce.
from semantic_kernel import Kernel from semantic_kernel.functions import kernel_function from blockchain0x import Client blockchain0x = Client() # reads BLOCKCHAIN0X_API_KEY from the environment class WalletPlugin: @kernel_function(description="Send a USDC payment from an agent wallet.") def send_usdc(self, agent_id: str, to: str, amount_wei: str) -> str: # amount_wei is USDC base units (6 decimals): "10000" = 0.01 USDC return str( blockchain0x.payments.create(body={"agentId": agent_id, "to": to, "amountWei": amount_wei}) ) kernel = Kernel() kernel.add_plugin(WalletPlugin(), plugin_name="Wallet") # Add your chat service, then let the model call Wallet.send_usdc.
using System.ComponentModel;
using System.Net.Http.Json;
using Microsoft.SemanticKernel;
// There is no .NET SDK, so a C# KernelFunction calls the REST API directly.
public class WalletPlugin
{
private static readonly HttpClient Http = new()
{
BaseAddress = new Uri("https://api.blockchain0x.com"),
};
[KernelFunction, Description("Send a USDC payment from an agent wallet. amountWei is USDC base units (6 decimals).")]
public async Task<string> SendUsdc(string agentId, string to, string amountWei)
{
Http.DefaultRequestHeaders.Authorization =
new("Bearer", Environment.GetEnvironmentVariable("BLOCKCHAIN0X_API_KEY"));
var res = await Http.PostAsJsonAsync("/v1/payments", new { agentId, to, amountWei });
return await res.Content.ReadAsStringAsync();
}
}
// builder.Plugins.AddFromType<WalletPlugin>("Wallet");Register the function on the kernel, set FunctionChoiceBehavior to Auto, and when the user's message implies a payment the model calls Wallet.send_usdc with the agent id, recipient, and amount. amountWei is base units, so 0.01 USDC is "10000". The Python path returns the SDK result; the C# path returns the REST response body.
API minimale ASP.NET Core per ricevere eventi di pagamento.
Quando un pagamento si stabilisce, Blockchain0x POSTa un evento firmato al tuo URL webhook. Non esiste un verificatore .NET incluso, quindi il gestore verifica manualmente contro l'HMAC documentato - che è tutto ciò che farebbe un helper. Esempio .NET qui sotto; Python e Java verificano allo stesso modo con le proprie librerie HMAC.
using System.Security.Cryptography;
using System.Text;
using Microsoft.AspNetCore.Builder;
var app = WebApplication.CreateBuilder(args).Build();
var secret = Environment.GetEnvironmentVariable("BLOCKCHAIN0X_WEBHOOK_SECRET")!;
app.MapPost("/webhooks/payment", async (HttpRequest req) =>
{
using var reader = new StreamReader(req.Body);
var raw = await reader.ReadToEndAsync(); // RAW body - verify before parsing
var sig = req.Headers["X-Blockchain0x-Signature"].ToString();
var ts = req.Headers["X-Blockchain0x-Timestamp"].ToString();
var parts = sig.Split(',').Select(p => p.Split('=', 2))
.Where(p => p.Length == 2).ToDictionary(p => p[0], p => p[1]);
var t = parts.GetValueOrDefault("t", ts);
var v1 = parts.GetValueOrDefault("v1", sig);
var want = Convert.ToHexString(new HMACSHA256(Encoding.UTF8.GetBytes(secret))
.ComputeHash(Encoding.UTF8.GetBytes($"{t}.{raw}"))).ToLowerInvariant();
var fresh = Math.Abs(DateTimeOffset.UtcNow.ToUnixTimeSeconds() - long.Parse(t)) <= 300;
if (!fresh || !CryptographicOperations.FixedTimeEquals(
Encoding.UTF8.GetBytes(want), Encoding.UTF8.GetBytes(v1)))
return Results.Unauthorized();
if (req.Headers["X-Blockchain0x-Event-Type"] == "payment.received")
await RunFollowupAsync(); // USDC landed - do the next step
return Results.Ok();
});
app.Run();L'algoritmo è HMAC-SHA256 sulla stringa t.rawBody, una finestra di replay di 300 secondi e un confronto a tempo costante. Leggi il corpo grezzo tramite StreamReader in modo che la firma rimanga intatta; non deserializzare e poi rieseguire la serializzazione. Gli eventi spediti sono payment.received, payment.sent, wallet.deployed e webhook.test. In produzione il webhook spesso funziona come un servizio ASP.NET Core separato che condivide un database con l'agente in modo che i due possano coordinarsi.
Gli SDK e la superficie REST sono aperti. Leggili.
Non esiste un starter package Semantic Kernel da clonare - le ricette sopra sono l'integrazione. I core SDK blockchain0x (Node, Python, Ruby, Go) sono open source su GitHub, e la loro superficie dei metodi insieme alle route REST chiamate dall'esempio C# sono documentate nella documentazione.
docs.blockchain0x.com/docs/overviewLa superficie dei metodi dell'SDK e le route REST sono documentate in the docs. Inizia con una chiave sk_test_ su Base Sepolia, poi passa a sk_live_ quando il KernelFunction si comporta come previsto.
Cinque trappole specifiche di Semantic Kernel da evitare.
Il modello di plugin di Semantic Kernel è pulito ma presenta insidie relative al linguaggio e ai comportamenti predefiniti. Conoscerle in anticipo fa risparmiare tempo.
Non esiste un pacchetto Semantic Kernel, in nessun linguaggio
Non esiste un adattatore NuGet, PyPI o Maven. Gli SDK core forniti sono Node, Python, Ruby, Go e JVM - non .NET. Quindi un kernel Python avvolge il client Python blockchain0x in un @kernel_function, un kernel Java utilizza l'SDK com.blockchain0x:sdk-jvm, e un kernel C# chiama direttamente l'API REST da un KernelFunction (mostrato sopra). Tutti e tre sono poche righe.
FunctionChoiceBehavior deve essere Auto
Il Semantic Kernel invoca solo le funzioni del plugin quando FunctionChoiceBehavior è impostato su Auto nelle impostazioni di esecuzione del prompt. Il valore predefinito è None, quindi il modello non chiama mai la tua funzione wallet, indipendentemente da quanto chiaramente l'utente chieda. Se l'agente ignora completamente la funzione, controlla prima questo.
Gli importi sono unità base USDC, come stringhe
The payments call takes amountWei: a string of USDC base units (6 decimals), so 0.01 USDC is "10000" and 5 USDC is "5000000". Type the function argument as a string in any language. payments.create also does not retry by default and can answer 503 until the chain adapter is wired for your network - return a clear message rather than letting the agent loop.
Ambito del plugin tra agenti
Registra la funzione wallet solo nel kernel dell'agente che dovrebbe detenere l'autorità di spesa. Il plugin non è globale - un agente il cui kernel non lo ha non può chiamarlo. Dai a un agente revisore un kernel senza la funzione wallet, o limita le funzioni consentite per agente, in modo che il denaro rimanga con un solo ruolo.
Verifica i webhook rispetto al corpo grezzo
Leggi il corpo della richiesta grezzo e verifica prima di deserializzare - l'HMAC copre i byte esatti, quindi un viaggio di andata e ritorno di analisi e successiva serializzazione lo rompe. Il gestore .NET qui sotto implementa l'algoritmo documentato: HMAC-SHA256 su t.rawBody, una finestra di 300 secondi e un confronto a tempo costante. Python e Java verificano allo stesso modo con le proprie librerie HMAC.