Ask A Question

Notifications

You’re not receiving notifications from this thread.

How do I access an attribute from a background worker (Stripe charge_id)?

Taylor Cooney asked in Rails
I managed to get Stripe working and processing Jobs, where a user must pay a one-time charge in order to create a Job record. 

After putting the call to `Stripe::Charge.create` in a background job I can't manage to figure out how to pass the `charge.id` from `Stripe::Charge.create` to an Order object.

I planned to move the Order.create call into the sidekiq worker and access the `charge.id` directly, but I can't access the @job within the worker because a stripeToken can't be used more than once. Any idea on how I can still save the `charge.id` to an `Order`? *(separate from the main Job model)*

JobsController

    def create
        ...
    
        if @job.create_with_stripe(params[:stripeToken])
          if @job.save
            Order.create(
              # Can't figure out how to pass the charge.id from StripePaymentJob
              :charge_id    => @charge.id,
              :job_id       => @job.id
            )
          end
          ...
      end

Job Model

    def create_with_stripe(token)
        Stripe.api_key = Rails.application.secrets.stripe_secret_key
    
        if valid?
          StripePaymentJob.perform_later(token, SecureRandom.uuid)
        else
        ...
      end

Stripe Worker

    class StripePaymentJob < ApplicationJob
      queue_as :default
    
      def perform(token, idempotent_key)
        @charge = Stripe::Charge.create({
          ...
        }, { idempotency_key: idempotent_key })
      end
    end


Reply
Phil gave me a hand over on StackOverFlow. In short, he recommended I consider this approach:
  • Before requesting the job be performed, create the order record with a nil charge_id
  • After the Stripe transaction has been completed in the job, update the order with the returned charge_id



Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 78,890+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more.

    © 2023 GoRails, LLC. All rights reserved.