Skip to content

Instantly share code, notes, and snippets.

@ezekg
Last active February 3, 2018 13:03
Show Gist options
  • Select an option

  • Save ezekg/516e02fe32426b76484ec579a36d10d4 to your computer and use it in GitHub Desktop.

Select an option

Save ezekg/516e02fe32426b76484ec579a36d10d4 to your computer and use it in GitHub Desktop.
Keygen user and license creation example in C# (https://keygen.sh)
using RestSharp;
using System;
using System.Collections.Generic;
using System.Text;
public class Example
{
// This is your account ID or slug.
//
// Available at: https://app.keygen.sh/settings
const string ACCOUNT_ID = "YOUR_ACCOUNT_ID_HERE";
// This is the policy ID used when creating new licenses.
//
// Available at: https://app.keygen.sh/policies
const string POLICY_ID = "YOUR_POLICY_ID_HERE";
public static void Main()
{
var client = new RestClient(string.Format("https://api.keygen.sh/v1/accounts/{0}", ACCOUNT_ID));
// You can request these from the user via a form, stdin, etc.
var userDetails = new Dictionary<string, object> {
{ "firstName", "John" },
{ "lastName", "Doe" },
{ "email", "johndoe@example.com" },
{ "password", "secret" },
{ "metadata", new {
/* … add *non-sensitive* payment details here e.g. a Stripe "token" */
stripeToken = "STRIPE_TOKEN_HERE"
}}
};
// Create the user
var userResponse = CreateUser(client, userDetails);
if (userResponse.ContainsKey("errors"))
{
Console.WriteLine("Failed to create user: {0}", userResponse["errors"]);
// … user creation failed, handle errors
return;
}
var user = (Dictionary<string, object>) userResponse["data"];
// Authenticate the new user
var tokenResponse = AuthenticateUser(client, (string) userDetails["email"], (string) userDetails["password"]);
if (tokenResponse.ContainsKey("errors"))
{
Console.WriteLine("Failed to authenticate user: {0}", tokenResponse["errors"]);
// … user authentication failed, handle errors
return;
}
var token = (Dictionary<string, object>) tokenResponse["data"];
var tokenAttrs = (Dictionary<string, object>) token["attributes"];
var tokenStr = (string) tokenAttrs["token"];
// Create a new license for the new user using the new token
// to authenticate with Keygen's API
var licenseResponse = CreateLicense(client, tokenStr, POLICY_ID, (string) user["id"]);
if (licenseResponse.ContainsKey("errors"))
{
Console.WriteLine("Failed to create license: {0}", licenseResponse["errors"]);
// … license creation failed, handle errors
return;
}
var license = (Dictionary<string, object>) licenseResponse["data"];
// Done and done! Next up, you could listen for the `license.created` webhook
// event to handle billing your new user using a payment provider like Stripe.
//
// Read more at: https://keygen.sh/docs/using-webhooks
Console.WriteLine(
"Successfully created license {0} for user {1} using token {2}",
(string) license["id"],
(string) user["id"],
tokenStr
);
}
public static Dictionary<string, object> CreateUser(RestClient client, Dictionary<string, object> userDetails)
{
var request = new RestRequest("users", Method.POST);
request.AddHeader("Content-Type", "application/vnd.api+json");
request.AddHeader("Accept", "application/vnd.api+json");
request.AddJsonBody(new {
data = new {
type = "users",
attributes = new {
firstName = (string) userDetails["firstName"],
lastName = (string) userDetails["lastName"],
email = (string) userDetails["email"],
password = (string) userDetails["password"],
metadata = userDetails["metadata"]
}
}
});
return client.Execute<Dictionary<string, object>>(request).Data;
}
public static Dictionary<string, object> AuthenticateUser(RestClient client, string userEmail, string userPassword)
{
var request = new RestRequest("tokens", Method.POST);
var credentials = Convert.ToBase64String(
Encoding.UTF8.GetBytes(string.Format("{0}:{1}", userEmail, userPassword))
);
request.AddHeader("Authorization", string.Format("Basic {0}", credentials));
request.AddHeader("Accept", "application/vnd.api+json");
return client.Execute<Dictionary<string, object>>(request).Data;
}
public static Dictionary<string, object> CreateLicense(RestClient client, string userToken, string policyId, string userId)
{
var request = new RestRequest("licenses", Method.POST);
request.AddHeader("Authorization", string.Format("Bearer {0}", userToken));
request.AddHeader("Content-Type", "application/vnd.api+json");
request.AddHeader("Accept", "application/vnd.api+json");
request.AddJsonBody(new {
data = new {
type = "licenses",
relationships = new {
policy = new {
data = new { type = "policies", id = policyId }
},
user = new {
data = new { type = "users", id = userId }
}
}
}
});
return client.Execute<Dictionary<string, object>>(request).Data;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment