One Time Purchases
Many cases, you'll want to provide someone with access to something when they purchase a product. This can be done through a few steps.
Store a price_id in your own plugin to reference your purchasable item.
This way, when you listen to events, you can sort out if you want to provide or revoke access to something based on the price_id.
Provide access using the order_paid event.
Since this is a one-time purchase, we'll want to use the Order Actions to listen for order events and update access accordingly.
The order_paid event is very handy for this, as it's triggered when an order is successfully paid. Here we will listen for the event and update the users meta
to provide them with access to something specific. We will use the Order Model to get the price_id and the customer_id.
use \SureCart\Models\Order;
$membership_price_id = '8ba8d60f-5277-4e6b-807c-dee8166446d5';
// Use the order_paid event to update the users meta
add_action( 'surecart/order_paid', function( $order_id ) {
// fetch order with line items so we can get the purchased price_id.
$order = Order::with( ['line_items'] )->find( $order_id );
// we only want to proceed if the order contains the membership_price_id.
if ( ! $order->hasPriceId( $membership_price_id ) ) {
return;
}
// get the order's WordPress user
$wp_user = $order->getUser();
// this order has no associated user.
if ( $wp_user ) {
// update user meta to provide access to something.
update_user_meta( $wp_user->ID, 'one_time_membership', true );
}
});
Revoke access using the refund_succeeded event.
We'll want to revoke access for the user when the order is refunded. We will use the
Refund Action refund_succeeded and query the the Refund Model and find it's
relationships to check if the order with the price_id has been fully refunded.
If you are processing a refund programatically, you will want to make sure you pass any price ids that you are refunding. To do that
you can use the forPriceIds method on the Charge refund method.
<?php
\SureCart\Models\Charge::refund()
->forPriceIds( [
// access will be revoked for these price ids.
'8ba8d60f-5277-4e6b-807c-dee8166446d5',
'8ba8d60f-5277-4e6b-dee8-807c166446d6',
] )->create( [
// 9900 is equivalent to $99.
'amount' => 9900,
] );
use \SureCart\Models\Order;
$membership_price_id = '8ba8d60f-5277-4e6b-807c-dee8166446d5';
// Use the order_paid event to update the users meta
add_action( 'surecart/refund_succeeded', function( $order_id ) {
// fetch order with line items.
$refund = Refund::find( $order_id );
// is the refund for this price id?
if( ! $refund->hasPriceId( $membership_price_id ) ) {
return;
}
// get the order's WordPress user
$wp_user = $refund->getUser();
// this order has no associated user.
if ( $wp_user ) {
// update user meta to revoke access to something.
delete_user_meta( $wp_user->ID, 'one_time_membership');
}
});