Skip to content

Instantly share code, notes, and snippets.

@ezekg
Last active April 19, 2021 21:06
Show Gist options
  • Save ezekg/5877b7ec41d091918cbf58543eed0fcc to your computer and use it in GitHub Desktop.
Save ezekg/5877b7ec41d091918cbf58543eed0fcc to your computer and use it in GitHub Desktop.
WooCommerce hook to generate a Keygen license key after a payment is completed
<?php
// Add these variables before running this code
$KEYGEN_PRODUCT_TOKEN = '...'
$KEYGEN_ACCOUNT_ID = '...'
$KEYGEN_POLICY_ID = '...'
// Add a hook after payment is completed
add_action('woocommerce_payment_complete', 'generate_license_key_after_payment_complete');
function generate_license_key_after_payment_complete($order_id){
$order = wc_get_order($order_id);
// Get the ID of the order
$order_id = $order->get_id();
// Get the ID of the customer
$user_id = $order->get_user_id();
// Generate a Keygen license for the user
$response = wp_remote_post("https://api.keygen.sh/v1/accounts/${KEYGEN_ACCOUNT_ID}/licenses", [
'method' => 'POST',
'data_format' => 'body',
'blocking' => true,
'headers' => [
'Authorization' => "Bearer ${KEYGEN_PRODUCT_TOKEN}",
'Content-Type' => 'application/json',
'Accept' => 'application/json'
],
'body' => wp_json_encode([
'data' => [
'type' => 'license',
'attributes' => [
'metadata' => [
'woocommerceOrderId' => $order_id,
'woocommerceUserId' => $user_id
]
],
'relationships' => [
'policy' => [
'data' = ['type' => 'policy', 'id' => $KEYGEN_POLICY_ID]
]
]
]
])
]);
// TODO: Email license key to user, etc.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment