In yesterday’s post on creating custom product types in drupal I promised a follow up on how we were adding the license generation to our checkout. I’m not going to go through all the steps in great detail as most of what I wrote is specific to our situation, and the custom PHP module (written in C) that generates our licenses, but it took me a while to work out how to hook in, so here are a few words.
In addition to our custom product type module ’licensable’, I also wrote a module called ’licenses’ which allows the site administrator to specify types of licenses to go with specific products and generate licenses, and for users to review the licenses they’ve bought through their account. It’s in that module that I connected with the transaction API to generate licenses after a purchase.
The callback in question is ‘hook_ec_transactionapi’ and we needed to intercept the ‘update’ operation:
function licenses_ec_transactionapi($txn, $op, $a3, $a4) {
switch ($op) {
case 'update':
if ($txn->payment_status == 2) {
licenses_generate_license($txn);
}
break;
}
return true;
}
A payment_status of 2 means that the payment has been completed and we can generate the license. The ’licenses_generate_license’ function can then loop through the transaction’s products and generate licenses for any that are licensable. Some rough code for that would be:
function licenses_generate_license(&$transaction) {
$user = user_load(array('uid' => $transaction->uid));
foreach($transaction->items as &$product) {
if ($product->ptype == 'licensable') {
// generate license
}
}
// send email to user with their license details
}