I am building a custom checkout with the Recurly PHP Client. Since we use our own gateway logic, we are forced to use the Create Purchase method, as opposed to Create Subscription (as Create Subscription doesn't accept gateway_code
as a parameter). Create Subscription returns the created subscription - easy!
But Create Purchase returns an Invoice Collection. It's possible to tease this apart to find the newly-created $subscription
object but this hardly seems like the intended process. Is there (hopefully) a cleaner way of going about it?
My method for purchasing is as follows - see code comments.
protected static function create_subscription( $user_id, $args ) {
$result = false;
$purchase = new Recurly_Purchase();
$purchase->currency = $args['currency'];
$purchase->collection_method = 'automatic';
$purchase->gateway_code = $args['gateway_code'];
$account = new Recurly_Account( $user_id );
$account->email = $args['email'];
$account->first_name = $args['billing_first_name'];
$account->last_name = $args['billing_last_name'];
$account->vat_number = $args['vat_number'];
$billing_info = new Recurly_BillingInfo();
$billing_info->token_id = $args['recurly_token'];
$account->billing_info = $billing_info;
$purchase->account = $account;
$subscription = new Recurly_Subscription();
$subscription->plan_code = $args['plan_code'];
$purchase->subscriptions = array( $subscription );
try {
// "invoice" is the method to transact a Recurly_Purchase.
$purchase = Recurly_Purchase::invoice( $purchase );
if( $purchase instanceof Recurly_InvoiceCollection ) {
// this seems incredibly janky and error-prone
$result = reset( $purchase->charge_invoice->line_items )->subscription->get();
}
} catch ( Exception $e ) {
$result = $e;
}
// I need this to return the $subscription object generated by the purchase
return $result;
}