How do I access an attribute from a background worker (Stripe charge_id)?
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
...
endJob Model
def create_with_stripe(token)
Stripe.api_key = Rails.application.secrets.stripe_secret_key
if valid?
StripePaymentJob.perform_later(token, SecureRandom.uuid)
else
...
endStripe Worker
class StripePaymentJob < ApplicationJob
queue_as :default
def perform(token, idempotent_key)
@charge = Stripe::Charge.create({
...
}, { idempotency_key: idempotent_key })
end
endPhil 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