buyCred Gateway API

Estimated reading: 9 minutes 1271 views

buyCred Gateway API

The Gateway API is responsible for allowing your users to buy points for real money. These purchases are either done manually or using online payment processors, such as PayPal or Netbilling. To buy points, a user must select the amount of points they want to buy and the payment processor they want to use. You can select to use just one particular payment gateway or multiple and let the user decide which one they want to use.

 

myCred comes with several built-in gateways located in the mycred/add-ons/buy-creds/gateways/ folder.

The buyCred Module

The buyCred module handles your installed gateways, built-in or custom ones, manages your pending payments and logs of purchases. The module will construct and load a gateway in the front-end when:

  • A logged in user visits any front-end page *.
  • If a new purchase request is detected.
  • If a Callback from a payment processor is detected.

* If the gateway needs to detect when a buyer returns to the website in order to process a payment (not using callback), the gateway will be loaded by buyCred on each front-end page load where the website is visited by someone who is logged in.

The Request Process

In order to buy points, four pieces of information needs to be submitted to the gateway API:

  • The Amount of points to purchase
  • The point type
  • The gateway ID selected to handle the payment and
  • A security token.

If the purchase is made as a gift, the recipients ID is also needed. Once the security token is verified, the requested gateway is constructed and the gateways buy() method is called upon to handle the purchase request. If the request is made by a user that is excluded or if the security token has expired, the gateway will not be loaded and the page will simply refresh.

Step 1.

A logged in user requests to purchase points using the mycred_buy or mycred_buy_form shortcodes.

Step 2.

The user clicks on the purchase link or submits the purchase form.

Step 3.

The request is validated and minimum amount is enforced. A pending payment is saved.

Step 4.

The checkout page is loaded to manage local payments or redirect to external servers.

Supported Gateway Types

The buyCRED add-on supports three types of payment gateways:

Local

The buyers payment information is collected locally and sent to the payment processor. The buyer never leaves your website.

Example: Netbilling

Remote

The buyer is redirected to an external payment processor where they pay and are redirected back to your website.

Example: PayPal

Manual

The user makes a purchase request but no payment information is collected. Payments are manually handled.

Example: Bank Transfer

The Gateway Class

Each gateway is a class based of the myCred_Gateway abstract class. A gateway class must have a constructor and the buy class method. All other methods are optional:

Class Method Required Purpose
__construct() Yes Identifies the gateway and it's settings.
buy() Yes Handles new or returning purchase requests. Also responsible for loading the checkout page.
preferences() No In case the gateway has settings that needs to be accessed in the admin area.
sanitise_preferences() No If the gateway has settings, this method should be used to parse and sanitize the gateways settings.
process() No Optional method to handle Callbacks (if needed).
returning() No Optional method to detect and act upon returns from an external payment processor.

Create New Gateway

Creating a new gateway for buyCred is relatively easy if you feel comfortable with PHP and understand how the payment processor you want to use, works. In order for your gateway to work with myCred, your gateway must be using the myCred_Gateway abstract class. This class will provide you with a large pallet of helpful functions to make construction as easy as possible.

Basic buyCRED Gateway example.

				
					if ( ! class_exists( 'my_custom_buycred_gateway' ) ) :
	class my_custom_buycred_gateway extends myCRED_Payment_Gateway {

		function __construct( $gateway_prefs ) {

			// Add a default exchange rate for all point types
			$types            = mycred_get_types();
			$default_exchange = array();
			foreach ( $types as $type => $label )
				$default_exchange[ $type ] = 1;

			// Register settings
			parent::__construct( array(
				'id'               => 'my_custom_gateway',
				'label'            => 'My Custom Gateway',
				'defaults'         => array(
					'logo'             => '',
					'title'            => '',
					'currency'         => 'EUR',
					'exchange'         => $default_exchange
				)
			), $gateway_prefs );

		}

		public function buy() {

			// handle purchase request

		}

	}
endif;
				
			

Class Constructor

First we need to construct our gateway using the myCred_Gateway class. This will register our gateway settings and apply defaults to existing settings.

While our class constructor only uses one variable; the gateway module settings, the parent constructor uses two:

  • The Gateways arguments – This holds the gateways ID and settings.
  • The buyCred add-on settings that were passed down.

Gateway Arguments

The following arguments are available for Gateways:

Argument Type Required Description
id string Yes A unique ID for the gateway.
label string Yes Gateway label used in the admin area.
defaults array Yes Array of the default settings for this gateway. Can not be empty.
gateway_logo_url string No Image url for the logo to show on the checkout page.

The buy() class method

The buy() class method is called when a user makes a purchase request and this method is expected to parse the request, construct arguments needed for the payment processor and load the checkout page.

 

You can access your gateway settings using $this->prefs and the myCred_Gateway abstract class provides a large set of methods that you can access to help handle requests. Here are some of the most used methods:

Class Method Description
$this->get_point_type() Returns the point type the user selected to buy. This method also makes sure users can only buy point types you have set to sell.
$this->get_cost() Returns the cost of the amount on points a user wants to buy based on the exchange rate you set. Also takes into account any custom exchange rate you might have set for a particular user.
$this->get_to() Returns the user ID of the recipient of the purchase. This might be the buyers ID or if you have gifting enabled, the recipients user ID.
$this->add_pending_payment() Saved a new pending payment request and returns the unique purchase request ID. This ID is used to identify the request in the admin area or in callbacks from payment processors.
$this->get_cancelled() Returns the URL set for the cancellation page in your buyCred settings.
$this->get_thankyou() Returns the URL set for the thank you page in your buyCRED settings.
$this->callback_url() Returns the callback URL a gateway must use (if the gateway supports callbacks).

The buyCred Checkout Page

Once a purchase request has been saved, we need to either collect a users payment details, show them how to complete their payment (manual gateways) or redirect them to the payment processor.

 

This is done using the “Checkout” page which is a page override that buyCred generates before your theme’s style / page layout is loaded. This is mainly to prevent third-party conflicts and to prevent other scripts and styles from being used. In future versions of myCred, this might however change, and instead use a dedicated checkout page.

 

Structure

The checkout page is rendered using the get_page_header() and get_page_footer() class methods. The content part can either be added manually via your class or use one of the built-in content render methods:

Class Method Description
$this->get_billing_address_form() Renders a billing form with built-in support for MarketPress and WooCommerce billing details.
$this->get_order() Renders the order table showing the order name, point amount and cost.
$this->get_page_redirect() Renders a form populated with fields you provide. Will automatically submit the form once the page has loaded or if the user clicks on the continue link.
$this->get_debug() Renders debug details. Intended for testing only!

Example: The Bank Transfer gateway inserts it’s own custom checkout page content.

Example: The PayPal gateway uses the built-in redirection on the checkout page.

Example showing how the buy() method in the gateway class can be used when a user needs to be redirected to a remote payment processor.

				
					if ( ! class_exists( 'my_custom_buycred_gateway' ) ) :
	class my_custom_buycred_gateway extends myCRED_Payment_Gateway {

		function __construct( $gateway_prefs ) {

			// Add a default exchange rate for all point types
			$types            = mycred_get_types();
			$default_exchange = array();
			foreach ( $types as $type => $label )
				$default_exchange[ $type ] = 1;

			// Register settings
			parent::__construct( array(
				'id'               => 'my_custom_gateway',
				'label'            => 'My Custom Gateway',
				'defaults'         => array(
					'logo'             => '',
					'title'            => '',
					'currency'         => 'EUR',
					'exchange'         => $default_exchange
				)
			), $gateway_prefs );

		}

		public function buy() {

			// Example: Require that settings are saved before this gateway is used
			if ( empty( $this->prefs['currency'] ) ) wp_die( 'Please setup this payment gateway before trying to make a purchase.' );

			// Get the point type requested to be bought
			$type   = $this->get_point_type();

			// Load the selected point type
			$mycred = mycred( $type );

			// Format the amount requested
			$amount = $mycred->number( $_REQUEST['amount'] );
			$amount = abs( $amount );

			// Get the cost of purchasing the amount requested
			$cost  = $this->get_cost( $amount, $type );

			// Get the recipient of the purchase (in case this is a gift purchase)
			$to    = $this->get_to();

			// Get the buyers ID (always the current user)
			$from  = get_current_user_id();

			// If this is a request to pay an existing pending payment
			if ( isset( $_REQUEST['revisit'] ) )
				$this->transaction_id = strtoupper( $_REQUEST['revisit'] );

			// If this is a new request
			else {

				// Add a new pending payment
				$post_id              = $this->add_pending_payment( array( $to, $from, $amount, $cost, $this->prefs['currency'], $type ) );

				// The pending payment is a custom post type where the title is the unique purchase request ID
				$this->transaction_id = get_the_title( $post_id );

			}

			// Get the page we need to redirect users to if they select to cancel this request
			$cancel_url = $this->get_cancelled( $this->transaction_id );

			// Get the thank you page to redirect users to on successfull payments
			$thankyou_url = $this->get_thankyou();

			// Generate the checkout page

			// The page header
			$this->get_page_header( 'Redirecting you to payment processor' );

			// Arguments to pass into a form that is submitted to the remote server
			// For example, see the PayPal Payment Standard gateway
			$hidden_fields = array();

			// Location of the payment processor where we need to redirect a user
			// Example of the location PayPal uses.
			$location = 'https://www.paypal.com/cgi-bin/webscr';

			// This example requires us to redirect a user to a remote payment processor
			$this->get_page_redirect( $hidden_fields, $location );

			// The page footer
			$this->get_page_footer();

		}

	}
endif;
				
			

Callbacks

buyCred Callbacks refer to the instances when a remote payment processor contacts your website in order to inform of updates regarding a pending payment, e.g. the payment being completed / captured. Callbacks are optional of course, if your gateway does not support it, you do not have to use it.

 

All callbacks have to use the proper callback identification, and you can use the callback_url() method to get this URL  for your gateway.

 

Once a valid callback is received, the gateway in question is loaded and the process() class method is called upon to handle the call. Most payment processors offer a callback or “postback” feature and how this call is processed varies.

Helpful Class Methods

Class Method Usage
get_pending_payment() Retrieves the pending payment object.
complete_payment() Completes a pending payment by paying out the actual points to a users account.
trash_pending_payment() Trashes a pending payment. Used mainly when payment is completed.
log_call() If enabled by the user, this method is used to log events associated with a pending payment request. For example when a pending payment could not be paid out. Uses WordPress comments.
create_unique_transaction_id() Used to create a unique transaction id for a pending payment. This ID is used when the transaction is handled remotely and we need to find the pending payment on callbacks.

Registering a Gateway

All gateway must be registered using the mycred_setup_gateways filter. All installed gateways are added in an associative array where the gateways unique ID is used as key and the value being an array of gateway details.

				
					add_filter( 'mycred_setup_gateways', 'mycredpro_adjust_gateways' );
function mycredpro_adjust_gateways( $installed ) {

	// Remove a specific gateway
	unset( $installed['bitpay'] );

	// Add a custom remote gateway
	$installed['mygateway'] = array(
		'title'    => 'My Gateway',
		'callback' => array( 'my_custom_buycred_gateway' ),
		'external' => true
	);

	// Add a manual gateway
	$installed['check'] = array(
		'title'    => 'Check',
		'callback' => array( 'my_custom_check_buycred_gateway' ),
		'external' => false
	);

	// Replace an existing gateway with our own
	$installed['bitpay'] = array(
		'title'    => 'Custom bitpay Gateway',
		'callback' => array( 'my_custom_buycred_gateway' ),
		'external' => true
	);

	return $installed;

}
				
			

Loading a Gateway

Custom gateways should be loaded using the mycred_buycred_load_gateways action hook. By the time this action fires, the abstract gateway is available and it ensures that your gateway is loaded before buyCred processes any payment requests.

Previously

Next up