Skip to content

Instantly share code, notes, and snippets.

@sebastianmoran-mainwp
Forked from Nicholas-Cardot/migration.php
Created August 15, 2019 03:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebastianmoran-mainwp/34bba796729f0d37b8a02dad2e96d3ef to your computer and use it in GitHub Desktop.
Save sebastianmoran-mainwp/34bba796729f0d37b8a02dad2e96d3ef to your computer and use it in GitHub Desktop.
WooCommerce to EDD Migration Script
<?php
/*
Template Name: Migration Script
*/
error_reporting(E_ALL);
//reuire_once('/stripe/init.php');
\Stripe\Stripe::setApiKey("my_key");
function convert_to_array($object) {
$raw_array = (array)$object;
foreach ($raw_array as $k => $v) {
$k = preg_match('/^\x00(?:.*?)\x00(.+)/', $k, $matches) ? $matches[1] : $k;
$array[$k] = $v;
}
return $array;
}
function get_percentage($total, $number)
{
if ( $total > 0 ) {
return round($number / ($total / 100),2);
} else {
return 0;
}
}
function format_date($date) {
return date("Y-m-d H:i:s" , strtotime($date) );
}
$count = wp_count_posts('shop_subscription');
$count = convert_to_array($count);
$total_count = $count['wc-active'] + $count['wc-pending-cancel'] + $count['wc-pending'] + $count['wc-on-hold'] + $count['wc-cancelled'];
$offset = 0;
$original_offset = $offset;
global $woocommerce;
global $wpdb;
while($offset <= 0):
$subscriptions = $wpdb->get_results('
SELECT *
FROM wp_posts
WHERE post_type = "shop_subscription"
AND ID = "58213"
ORDER BY ID
Limit 1
Offset '.$offset.'
');
if(count($subscriptions) < 1){
die();
}
// Loop through the fetched subscriptions
foreach($subscriptions as $subscription):
++$offset;
// Fetch the woo subscription object from the Post ID
$subscription_object = wcs_get_subscription($subscription->ID);
// Convert to array to break free the protected properties
$subscription_array = convert_to_array($subscription_object);
// var_dump($subscription_array);
$woo_status = $subscription_array['data']['status'];
if($woo_status == 'wc-pending') {
$status = 'pending';
} elseif ( $woo_status == 'wc-failed') {
$status = 'failed';
} elseif ( $woo_status == 'wc-processing') {
$status = 'pending';
} elseif ( $woo_status == 'wc-completed') {
$status = 'complete';
} elseif ( $woo_status == 'wc-on_hold') {
$status = 'failed';
} elseif ( $woo_status == 'wc-cancelled') {
$status = 'complete';
} elseif ( $woo_status == 'wc-refunded') {
$status = 'refunded';
} else {
$status = 'complete';
}
// Fetch the related orders (payments)
$related_orders = $subscription_object->get_related_orders( 'all' , 'all' );
$related_orders = convert_to_array($related_orders);
// var_dump($related_orders);
// Fetch the customer's information and profile
$user = get_user_by( 'id' , $subscription_array['data']['customer_id']);
$user_info = get_userdata($user->ID);
if( !empty($user_info->first_name) && !empty($user_info->last_name) ):
$user_name = $user_info->first_name . ' ' . $user_info->last_name;
else:
$user_name = $user->data->display_name;
endif;
$edd_customer = new EDD_Customer( $user->ID , true );
if ( false == $edd_customer ):
unset($edd_customer);
$user_args = array(
'user_id' => $user->ID,
'name' => $user_name,
'email' => $user->data->user_email,
'payment_ids' => '',
'purchase_value' => '',
'purchase_count' => '',
'notes' => '',
'date_created' => format_date( $user->data->user_registered ),
);
$edd_customer = new EDD_Customer();
$edd_customer->create($user_args);
endif;
// var_dump($edd_customer);
asort($related_orders);
// Loop through the payments
foreach($related_orders as $related_order):
// Get the product that was sold
$items = $related_order->get_items();
// Fetch the quantity of the item sold
foreach($items as $item):
$item = convert_to_array($item);
$quantity = $item['data']['quantity'];
endforeach;
// Convert to an array to access protected properties
$related_order_array = convert_to_array($related_order);
// Setup the download args and options
$download_args = array(
'quantity' => $quantity,
'item_price' => ($related_order_array['data']['total'] / $quantity),
);
$download_options = array(
'is_renewal' => true,
'recurring' => array (
'period' => 'day',
'times' => 0,
'signup_fee' => 0,
'trial_period' => false,
),
);
// var_dump($related_order_array['data']);
unset($payment);
$date_array = convert_to_array( $related_order_array['data']['date_created']);
$date = format_date( $date_array['date'] );
// Initiate a new payment and fill it with our information
$payment = new EDD_Payment();
$payment->add_download( 56935 , $download_args , $download_options );
$payment->email = $user->data->user_email;
$payment->status = $status;
$payment->date = $date;
$payment->completed_date = $date;
$payment->currency = 'USD';
$payment->customer_id = $edd_customer->id;
$payment->user_id = $user->ID;
$payment->gateway = $related_order_array['data']['payment_method'];
$payment->transaction_id = $related_order_array['data']['transaction_id'];
// Save it so we have a transaction ID to use next
$payment->save();
// Setup the parent id field
if(isset($parent_id)):
$payment->parent_payment = $parent_id;
else:
$parent_id = $payment->ID;
$payment->parent_payment = $payment->ID;
endif;
update_post_meta( $payment->ID , '_edd_payment_mode', 'live');
update_post_meta( $payment->ID , '_edd_subscription_payment' , 1);
update_post_meta( $payment->ID , 'eddsr_status' , 'ignore' );
update_post_meta( $payment->ID , '_edd_payment_tax_rate' , 0 );
// Now save it again to store that parent ID information
$payment->save();
// Add this payment to our payments ID's array to pass it to the subscription later
$id_array[] = $payment->ID;
endforeach;
$payment_method = $subscription_array['data']['payment_method'];
if( $payment_method == 'paypal'):
$gateway = 'paypal';
foreach($subscription_array['meta_data'] as $field):
if($field->key == '_paypal_subscription_id'):
$gateway_sub_id = $field->value;
endif;
endforeach;
elseif( $payment_method == 'stripe'):
$gateway = 'stripe';
foreach($subscription_array['meta_data'] as $field):
if($field->key == '_stripe_customer_id'):
$stripe_customer_id = $field->value;
endif;
endforeach;
endif;
$stat = $subscription_array['data']['status'];
if( $stat == 'cancelled' ):
$subscription_status = 'cancelled';
$expire_array = convert_to_array($subscription_array['data']['schedule_end']);
$expiration = $expire_array['date'];
elseif( $stat == 'active' ):
$subscription_status = 'active';
$expire_array = convert_to_array($subscription_array['data']['schedule_next_payment']);
$expiration = $expire_array['date'];
elseif( $stat == 'pending'):
$subscription_status = 'pending';
$expire_array = convert_to_array($subscription_array['data']['schedule_next_payment']);
$expiration = $expire_array['date'];
elseif( $stat = 'on-hold' ):
$subscription_status = 'failing';
$expire_array = convert_to_array($subscription_array['data']['schedule_next_payment']);
$expiration = $expire_array['date'];
endif;
$expiration = format_date($expiration);
$created_array = convert_to_array($subscription_array['data']['date_created']);
$created = format_date( $created_array['date'] );
$initial_payment = $subscription_array['data']['total'];
$recurring_total = $subscription_object->get_total();
$parent_id = min($id_array);
/**
* STRIPE SUBSCRIPTIONS
*
* If this is a stripe subscription, we need to create a subscription over in Stripe's database.
* We'll set a trial period equal to the amount of time remaining on the current subscription.
* We'll set that trial period using the trial end.
*
*/
if( $payment_method == 'stripe' && $subscription_status == 'active'):
/**
* THE PLAN
*
* The first thing we need to do is to create a plan so that we can assign this in the subscription.
* Since we're only working with one product that has been sold at multiple prices, we'll generate
* the plan ID from the plan name combined with the plan price. So then we'll have a unique plan
* for each possible pricing set.
*
*/
$plan_id = 'social-warfare-pro-daily-'.($recurring_total*100); // So we don't have decimals in the plan name
$amount_in_cents = number_format($recurring_total * 100 , 0 , '' , '');
$amount_in_cents = (int)$amount_in_cents;
try {
$stripe_plan = \Stripe\Plan::create(array(
'name' => 'Social Warfare - Pro',
'id' => $plan_id, // (e.g social-warfare-pro-2900 for a $29 subscription)
'interval' => 'day',
'currency' => 'usd',
'amount' => $amount_in_cents,
));
} catch (Exception $e) {
if( 'Plan already exists.' != $->getMessage() ) {
echo 'Message: ' .$e->getMessage();
}
}
/**
* THE STRIPE SUBSCRIPTION
*
* Once the plan is setup, let's go ahead an create a subscription with the customer and the plan
*
*/
try {
$stripe_subscription = \Stripe\Subscription::create(array(
'customer' => $stripe_customer_id,
'items' => array(
array(
'plan' => $plan_id,
)
),
'trial_end' => strtotime($expiration),
)
);
// Once the subscription is created, let's fetch the ID so we can store it in Easy Digital Downloads
$gateway_sub_id = $stripe_subscription->ID;
} catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
endif;
$subscription_data = array(
'customer_id' => $edd_customer->id, // an integer, should be a valid customer_id
'period' => 'day', // accepts 'day', 'week', 'month', or 'year'; how often the subscription renews
'initial_amount' => $initial_payment, // accepts a float
'recurring_amount' => $recurring_total, // accepts a float
'bill_times' => 0, // accepts an integer; the number of times billing should happen, 0 means indefinite
'parent_payment_id' => $parent_id, // accepts an integer; the payment id returned by the initial payment
'product_id' => 56935, // accepts an integer; the id of the product
'created' => $created,
'expiration' => $expiration,
'status' => $subscription_status, // accepts 'Pending', 'Active', 'Cancelled', 'Expired', 'Failing', 'Completed'
'profile_id' => $gateway_sub_id , // accepts a string returned by the payment gateway as their subscription ID
'gateway' => $gateway,
);
$edd_subscription = new EDD_Subscription();
$edd_subscription->create($subscription_data);
unset($parent_id);
endforeach;
header( 'Content-type: text/html; charset=utf-8' );
echo 'Subscriptions Migrated: ' . number_format( $offset ) . ' --- ' . get_percentage( $total_count , $offset ) . '%' . PHP_EOL;
ob_flush(); flush();
@set_time_limit(300);
endwhile;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment