Mark Ferguson
Mark Ferguson

Reputation: 33

Get the last subscription renewal order information in Woocommerce 3

We are trying to pass woocommerce subscription renewal data to a loyalty rewards program and are having all kinds of issues and have been unable to get relevant woocommerce subscription information or anything to work. Our full loyalty code for zinrelo works with manual data.

FUll code with your suggestions runs in functions file

add_action( 'woocommerce_subscription_renewal_payment_complete', 'custom_add_subscription_points', 10, 1 );
  function custom_add_subscription_points( $subscription ) {
    if ( ! $subscription )
        return;

    // Get related orders
    $orders_ids = $subscription->get_related_orders();

    // Get the last renewal related Order ID
    $order_id = reset( $order_ids );

    $order = wc_get_order($order_id);
    $order_id = $order->get_id();
    $order_email = $order->get_billing_email();
    $order_date = $order->get_date_completed();
    $order_total = $order->get_total();
    $order_subtotal = $order->get_subtotal();

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, "https://api.zinrelo.com/v1/loyalty/purchase");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, "user_email={$order_email}&activity_id=made_a_purchase&order_{id=$order_id}&total={$order_total}&subtotal={$order_subtotal}");
    curl_setopt($ch, CURLOPT_POST, 1);

    $headers = array();
    $headers[] = "Partner-Id: 000000";
    $headers[] = "Api-Key: 000000";
    $headers[] = "Content-Type: application/x-www-form-urlencoded";
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $result = curl_exec($ch);
    if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
    }
    curl_close ($ch);
}

Upvotes: 2

Views: 3848

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 254251

As WC_Subscription get_related_orders() method gives an array of order IDs, you need to use end() function, to get the last order ID and avoid an error with wc_get_order() function that expect a unique order ID as argument (but not an array).

So try:

add_action( 'woocommerce_subscription_renewal_payment_complete', 'custom_add_subscription_points', 10, 1 );
function custom_add_subscription_points( $subscription, $last_order ) {
    if ( ! $subscription )
        return;

    $order_email    = $last_order->get_billing_email();
    $order_date     = $last_order->get_date_completed();
    $order_total    = $last_order->get_total();
    $order_subtotal = $last_order->get_subtotal();
}

It should work now with:

curl_setopt($ch, CURLOPT_POSTFIELDS, "user_email={$order_email}&activity_id=made_a_purchase&order_{id=$order_id}&total={$order_total}&subtotal={$order_subtotal}");

Upvotes: 1

Related Questions