Search code examples
payment-gatewaybraintreesubscription

Braintree payment gateway - Get customer's subscriptions details


I am using Braintree payment gateway in my Rails application. I am wondering if I can retrieve the customer's subscriptions details from it. According to the documentation, one of the way of doing this is subscription = Braintree::Subscription.find(id)

When creating a subscription, basic objects such as plan_id and amount was saved into the database. So, how do I retrieve subscription's information such as next_billing_date that is associated to the customer?


Solution

  • Assuming you have a subscription ID:

    # Find the subscription
    subscription = Braintree::Subscription.find(sub_id)
    
    # Access the subscription's next billing date
    subscription.next_billing_date
    

    Braintree::Subscription.find() returns a Braintree::Subscription result object.

    Assuming you have a customer ID:

    # Find the customer
    customer = Braintree::Customer.find(cust_id)
    
    # Retrieve the customer's first payment method
    pm = customer.payment_methods.first
    
    # Retrieve the subscriptions created with that payment method
    subscriptions = pm.subscriptions
    
    # Access the subscription's next billing date
    subscriptions.first.next_billing_date
    

    Braintree::Customer.find() returns a Braintree::Customer response object. The customer's payment methods can then be retrieved. Subscriptions are associated to payment methods. Once you have a payment method, you can retrieve an array of Braintree::Subscription objects.