canimus
7/4/2013 - 9:23 PM

Paymill new subscription ruby

Paymill new subscription ruby

module Paymillable

  def subscribe paymillToken    
    client = Paymill::Client.create email: self.identity.email, description: self.name
    payment = Paymill::Payment.create token: paymillToken, client: client.id
    subs = Paymill::Subscription.create offer: PricePlan.last.paymill_id, client: client.id, payment: payment.id
    self.upgrade(PricePlan.last)
    self.update(paymill_id:client.id)
  end # subscribe

  def unsubscribe
    client = Paymill::Client.find self.paymill_id
    client_subscription = client.subscription.first if client.subscription.present? and client.subscription.kind_of?(Array)    
    subscription = Paymill::Subscription.find(client_subscription["id"]) if client_subscription.has_key? "id"
    self.downgrade
    subscription.present? and subscription.update_attributes({cancel_at_period_end:true})
  end # subscribe

  def transactions
    if self.paymill_id.present?
      return Paymill::Transaction.all(client: self.paymill_id)
    else 
      return []
    end
  end

end