Skip to content

Instantly share code, notes, and snippets.

@Xhynk
Created July 8, 2020 20:56
Show Gist options
  • Save Xhynk/18e134a5106144a2aa49b675fe07b5a6 to your computer and use it in GitHub Desktop.
Save Xhynk/18e134a5106144a2aa49b675fe07b5a6 to your computer and use it in GitHub Desktop.
A simple method to copy live Stripe products (and their plans) to your Testing area. The `$illegal_params` array can be modified as needed, and more fields can be added to both creation methods. In my case I just needed the Product Name and Metadata, and have a lot of old plans, so figured I'd get all the data, and remove the illegal or unused p…
<?php
// Start a Stripe Client for Live and Test
$stripe_live = new \Stripe\StripeClient( 'YOUR_LIVE_SECRET' );
$stripe_test = new \Stripe\StripeClient( 'YOUR_TEST_SECRET' );
// Fetch All Products
$live_products = $stripe_live->products->all(['limit' => 100]);
// Start an array to dump our results
$dump = array();
// Loop through the products
foreach( $live_products->data as $product ){
// Create this same product in Test
$test_product = $stripe_test->products->create([
'name' => $product->name,
'metadata' => json_decode( json_encode( $product->metadata ), true )
]);
$dump[$test_product->name] = array();
// Get all the live plans for this product
$product_plans = $stripe_live->plans->all(['product'=>$product->id]);
// Loop through the plans
foreach( $product_plans->data as $plan ){
// Convert the plan object to an array
$plan_array = json_decode( json_encode( $plan ), true );
$plan_array['product'] = $test_product->id;
// Remove illegal/outdated/arguments
$illegal_params = array(
'transform_usage',
'amount_decimal',
'object',
'created',
'livemode',
'trial_period_days',
'tiers',
'tiers_mode',
'aggregate_usage',
);
foreach( $illegal_params as $param ){
unset( $plan_array[$param] );
}
// If nickname isn't set, remove it too
if( $plan_array['nickname'] == '' ){
unset( $plan_array['nickname'] );
}
// Add the test plan
$test_plan = $stripe_test->plans->create( $plan_array );
// Add it as an array item to our dump array
$dump[$test_product->name][] = $test_plan->id;
}
}
// Inspect the elements added to the Test area
print_r( $dump );
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment