develop with

Cancel Recurly Subscription Programmatically

Different ways to cancel a recurly subscription using the ruby sdk.

Subscriptions can be cancelled via the Recurly API. To setup the recurly ruby api, you’ll need to install the recurly sdk gem. To install run gem install recurly or add gem 'recurly' to your Gemfile.

There are a couple types of ways to cancel the subscription and to issue or not issue a refund. Refunds are based on a subscription cancelled before a reoccurring period is completed. There is the option to allow the subscription to be cancelled on the next reoccurring period (:none) vs in the middle of the period (:partial). For instance, if a user cancels a monthly subscription of $10.00, you could have a policy that will only cancel the following month payment vs refunding the partial amount in the current month.

Example of cancelling subscriptions programmatically:

account = Recurly::Account.find(account_id)
# cancel all with a partial refund for the remaining subscription period
subscriptions = account.subscriptions.where(state: :active)
subscriptions.each do |subscription|
  subscription.terminate :partial
end

# to cancel without a partial return, and cancel the next periods payments pass :none
subscription = Recurly::Subscription.find(subscription_id)
subscription.terminate :none

The problem with canceling with a :partial is when the account is in a pending state. This means the account’s subscription plan has been changed. In this case the only thing to do is terminate the subscription with :none. The recurly api throws an invalid_transaction error when the account or subscription is in a pending state.

The reason is when an account is upgraded within a certain period of time the subscription amount is credited and a new amount is placed for the new subscription. The refund is not valid because there isn’t a charge they can find for the refund, since the subscription transaction has changed and will be updated in the next period.

Below is a way to failback in the case of a pending state:

 begin
   subscription.terminate refund
 rescue Recurly::API::BadRequest => r
   if r.symbol == 'invalid_transaction'
     subscription.terminate :none 
   else 
     raise r
   end
 end
 

comments powered by Disqus

Want to see a topic covered? create a suggestion

Get more developer references and books in the developwith store.