Can we change stripes keys in cashier dynamically in laravel 8?

Viewed 35

I am using stripe with Laravel cashier. I want to make stripe keys dynamic instead of saving keys in .env file. I saved keys in database and now want to use these keys in cashier. Cashier get these keys from .env but i want to get these from database.

enter image description here

this is laravel/cashier/config/casher.php file where it access keys and i want to set my values there. I can't use eloquent in this file.

2 Answers

You can change the config before using anything related to stripe or on your model you can create a static function to override the defaults but this way you will need to use stripe through the model

    public static function stripe(array $options = [])
    {
        return Cashier::stripe(array_merge([
            'api_key' => $this->getStripeKey(),
        ], $options));
    }

or update the config

config(['cashier.secret' => $key])

I updated the stripe keys in the env file with the a function in controller.

protected function updateDotEnv($key, $newValue, $delim='')
{

    $path = base_path('.env');
    // get old value from current env
    $oldValue = env($key);

    // was there any change?
    if ($oldValue === $newValue) {
        return;
    }

    // rewrite file content with changed data
    if (file_exists($path)) {
        // replace current value with new value 
        file_put_contents(
            $path, str_replace(
                $key.'='.$delim.$oldValue.$delim, 
                $key.'='.$delim.$newValue.$delim, 
                file_get_contents($path)
            )
        );
    }
}

$key is new name of variable in env and $newValue is the updated key.

Related