function do_process() { global $ym_sys; $mode = $this->status == 'test' ? TRUE : FALSE; $gc = new GoCardless($this->merchant_id, $this->application_id, $this->application_secret, $this->access_token, $mode, $this->magical_word); if (!$gc->valid) { echo 'An Error Occured. Please contact Site Admin: Invalid Keys'; exit; } $action = ym_request('action'); if ($action == 'go') { // redirecting to gocardless $pack = $_POST; if (isset($pack['num_cycles']) && $pack['num_cycles'] != 1) { // subscription // convert pack values to something gocardless can understand switch ($pack['duration_type']) { case 'y': // convert to month $interval_unit = 'month'; $interval_length = $pack['duration'] * 12; $expire_length = $interval_length * $pack['num_cycles']; $expire = mktime(23, 59, 59, date('n', time()) + $expire_length, date('j', time()), date('Y', time())); break; case 'm': $interval_unit = 'month'; $interval_length = $pack['duration']; $expire_length = $interval_length * $pack['num_cycles']; $expire = mktime(23, 59, 59, date('n', time()) + $expire_length, date('j', time()), date('Y', time())); break; case 'd': $interval_unit = 'day'; $interval_length = $pack['duration']; $expire_length = $interval_length * $pack['num_cycles']; $expire = mktime(23, 59, 59, date('n', time()), date('j', time()) + $expire_length, date('Y', time())); } $subscription = array('amount' => number_format($pack['cost'], 2), 'interval_length' => $interval_length, 'interval_unit' => $interval_unit, 'merchant_id' => $this->merchant_id, 'name' => get_bloginfo() . ' ' . __('Subscription', 'ym'), 'description' => isset($pack['item_name']) && $pack['item_name'] ? $pack['item_name'] : $ym_sys->item_name); if ($subscription['name'] == $subscription['description']) { unset($subscription['description']); } if ($pack['num_cycles'] > 1) { $subscription['expire'] = date('c', $expire); } } else { // single purchase // bill $bill = array('amount' => number_format($pack['cost'], 2), 'merchant_id' => $this->merchant_id, 'name' => get_bloginfo() . ' ' . __('Purchase', 'ym'), 'description' => isset($pack['item_name']) && $pack['item_name'] ? $pack['item_name'] : $ym_sys->item_name); } $data = array(); // common fields $data['redirect_uri'] = site_url('?ym_process=' . $this->code . '&action=confirm'); $data['cancel_uri'] = site_url($this->cancel_url); // state AKA custom if (isset($pack['ppp_pack_id'])) { $data['state'] = 'buy_bundle_' . $pack['ppp_pack_id'] . '_' . $pack['user_id']; } else { if (isset($pack['post_id'])) { $data['state'] = 'buy_post_' . ($pack['post_id'] ? $pack['post_id'] : get_the_ID()) . '_' . $pack['user_id']; } else { $data['state'] = 'buy_subscription_' . $pack['id'] . '_' . $pack['user_id']; } } // user fields $user = array(); if ($first = get_user_meta($pack['user_id'], 'first_name', true)) { $user['first_name'] = $first; } if ($last = get_user_meta($pack['user_id'], 'last_name', true)) { $user['last_name'] = $last; } $user['email'] = get_user_by('id', $pack['user_id']); $user['email'] = $user['email']->user_email; // generate and go to URL if (isset($bill)) { $gc->NewPayment($bill, $data, $user); } else { echo 'sub'; $gc->NewSubscription($subscription, $data, $user); } exit; } if ($action == 'confirm') { // perform confirm and redirect $state = ym_get('state'); if (!$state) { header('HTTP/1.1 400 Bad Request'); echo 'Missing State'; exit; } $r = $gc->catchReturn(); if ($r) { // update the user and set then to pending or grace // cost is 0 as no money yet // deny receipt email $this->nomore_email = TRUE; // process $this->common_process($state, '0', FALSE, FALSE); // technically true and Don't exit list($buy, $what, $id, $user_id) = explode('_', $state); // we need to store the bill/subscription ID in order to track the user // state is not returned with webhooks $key = ym_get('resource_id'); $data = array('state' => $state, 'user_id' => $user_id, 'amount' => ym_get('amount')); update_option('ym_gocardless_states_' . $key, $data); if ($what == 'post') { $pack = array('ppp' => 1, 'post_id' => $id); } else { if ($what == 'bundle') { $pack = array('ppp' => 1, 'ppp_pack_id' => $id); } else { // subscriptiom update_user_meta('ym_gocardless_active_subscription', $key, $user_id); $pack = $id; } } $this->redirectlogic($pack, TRUE); } else { echo 'An Error Occured, you should contact the Site Admin'; exit; } } // assume webhook $data = $gc->catchWebHook(); if (!$data) { header('HTTP/1.1 403 Unauthorised'); echo 'Signature Invalid'; exit; } else { // post or sub? // status // created failed paid cancelled expired withdrawn // abort cases // widthdrawn jsut means money has moved from the GC account to the merchant account. $aborts = array('created', 'withdrawn'); if (in_array($data['action'], $aborts)) { // ignore created packets header('HTTP/1.1 200 OK'); echo 'ok'; exit; } $success_states = array('paid'); $failed_states = array('failed', 'cancelled', 'expired'); foreach ($data['resources'] as $packet) { $id = $packet->id; $status = $packet->status; $uri = $packet->uri; $source_type = isset($packet->source_type) ? $packet->source_type : ''; if ($source_type == 'subscription') { $id = $packet->source_id; } $state_data = get_option('ym_gocardless_states_' . $id, FALSE); if ($state_data) { // packet found $state = $state_data['state']; $user_id = $state_data['user_id']; $amount = $state_data['amount']; // store for trans log $_POST = $state_data; $complete = FALSE; if (in_array($status, $success_states)) { $complete = TRUE; } $this->common_process($state, $amount, $complete, FALSE); } else { $admin = get_userdata(1); $admin_email = $admin->user_email; ym_email($admin_email, 'GC PAYLOAD STATE FAIL', print_r($packet, TRUE)); } } exit; } }
require_once $whmcsdir . '/includes/invoicefunctions.php'; require_once $whmcsdir . '/modules/gateways/gocardless.php'; # get gateway params $gateway = getGatewayVariables('gocardless'); # sanity check to ensure module is active if (!$gateway['type']) { die("Module Not Activated"); } # set relevant API information for GoCardless module gocardless_set_account_details($gateway); # if the resource ID and resouce type are set, confirm it using the GoCardless API if (isset($_GET['resource_id']) && isset($_GET['resource_type'])) { # if GoCardless fails to confirm the resource, an exception will be thrown # we will handle the exception gracefully try { $confirmed_resource = GoCardless::confirm_resource(array('resource_id' => $_GET['resource_id'], 'resource_type' => $_GET['resource_type'], 'resource_uri' => $_GET['resource_uri'], 'signature' => $_GET['signature'], 'state' => $_GET['state'])); } catch (Exception $e) { # failed to verify the resource with GoCardless. Log transaction and ouput error message to client logTransaction($gateway['paymentmethod'], 'GoCardless Redirect Failed (Resource not verified) : ' . print_r($_GET, true) . 'Exception: ' . print_r($e, true), 'Unsuccessful'); header('HTTP/1.1 400 Bad Request'); exit('Your request could not be completed'); } } else { # failed to get resource ID and resource type, invalid request. Log transaction and ouput error message to client logTransaction($gateway['paymentmethod'], 'GoCardless Redirect Failed (No data provided) : ' . print_r($_GET, true), 'Unsuccessful'); header('HTTP/1.1 400 Bad Request'); exit('Your request could not be completed'); } # split invoice data into invoiceID and invoiceAmount list($invoiceID) = explode(':', $_GET['state']); # check we have the invoiceID
/** ** Builds the payment link for WHMCS users to be redirected to GoCardless **/ function gocardless_link($params) { # get global config params global $CONFIG; # create GoCardless database if it hasn't already been created gocardless_createdb(); # check the invoice, to see if it has a record with a valid resource ID. If it does, the invoice is pending payment. # we will return a message on the invoice to prevent duplicate payment attempts $aGC = mysql_fetch_assoc(select_query('mod_gocardless', 'id,payment_failed', array('invoiceid' => $params['invoiceid'], 'resource_id' => array('sqltype' => 'NEQ', 'value' => '')))); if ($aGC['id']) { if ($aGC['payment_failed'] == 0) { # Pending Payment Found - Prevent Duplicate Payment with a Msg return '<strong>Your payment is currently pending and will be processed within 3-5 days.</strong>'; } else { # display a message to the user suggesting that a payment against the invoice has failed return '<strong>One or more payment attempts have failed against this invoice. Please contact our support department.</strong>'; } } # get relevant invoice data $aRecurrings = getRecurringBillingValues($params['invoiceid']); $recurringcycleunit = strtolower(substr($aRecurrings['recurringcycleunits'], 0, -1)); # check a number of conditions to see if it is possible to setup a preauth if ($params['oneoffonly'] == 'on' || $aRecurrings === false || $aRecurrings['recurringamount'] <= 0) { $noPreauth = false; #MOD } else { $noPreauth = false; } # set appropriate GoCardless API details gocardless_set_account_details($params); # set user array based on params parsed to $link $aUser = array('first_name' => $params['clientdetails']['firstname'], 'last_name' => $params['clientdetails']['lastname'], 'email' => $params['clientdetails']['email'], 'billing_address1' => $params['clientdetails']['address1'], 'billing_address2' => $params['clientdetails']['address2'], 'billing_town' => $params['clientdetails']['city'], 'billing_county' => $params['clientdetails']['state'], 'billing_postcode' => $params['clientdetails']['postcode']); $invoice_item_query = select_query('tblinvoiceitems', 'relid', array('invoiceid' => $params['invoiceid'], 'type' => 'Hosting')); while ($invoice_item = mysql_fetch_assoc($invoice_item_query)) { $package_query = select_query('tblhosting', 'subscriptionid', array('id' => $invoice_item['relid'])); $package = mysql_fetch_assoc($package_query); if (!empty($package['subscriptionid'])) { $preauthExists = true; } } if ($preauthExists) { # The customer already has a pre-auth, but it's yet to be charged so # let's not let them set up another... return (GoCardless::$environment == 'sandbox' ? '<strong style="color: #FF0000; font-size: 16px;">SANDBOX MODE</strong><br />' : null) . '<strong>Automatic payments via Direct Debit or another payment method are already configured for this invoice. You will receive an email once you have been billed.</strong>'; } elseif ($noPreauth) { # if one of the $noPreauth conditions have been met, display a one time payment button # we are making a one off payment, display the appropriate code # Button title $title = 'Pay Now with GoCardless'; # create GoCardless one off payment URL using the GoCardless library $url = GoCardless::new_bill_url(array('amount' => $params['amount'], 'name' => "Invoice #" . $params['invoiceid'], 'user' => $aUser, 'state' => $params['invoiceid'] . ':' . $params['amount'])); # return one time payment button code $sButton = (GoCardless::$environment == 'sandbox' ? '<strong style="color: #FF0000; font-size: 16px;">SANDBOX MODE</strong><br />' : null) . '<a href="' . $url . '" onclick="window.location=\'' . $url . '\';" style="text-decoration: none"><input onclick="window.location=\'' . $url . '\';" type="button" value="' . $title . '" /></a>'; } else { # we are setting up a preauth (description friendly name), display the appropriate code # get the invoice from the database because we need the invoice creation date $aInvoice = mysql_fetch_assoc(select_query('tblinvoices', 'date', array('id' => $params['invoiceid']))); # GoCardless only supports months in the billing period so # if WHMCS is sending a year value we need to address this if ($recurringcycleunit == 'year') { $recurringcycleunit = 'month'; $aRecurrings['recurringcycleperiod'] = $aRecurrings['recurringcycleperiod'] * 12; } $pre_auth_maximum = 5000; # Always create a £5000 pre-auth # Button title $title = 'Create Subscription with GoCardless'; # create GoCardless preauth URL using the GoCardless library $url = GoCardless::new_pre_authorization_url(array('max_amount' => $pre_auth_maximum, 'setup_fee' => $aRecurrings['firstpaymentamount'] > $aRecurrings['recurringamount'] ? $aRecurrings['firstpaymentamount'] - $aRecurrings['recurringamount'] : 0, 'name' => "Direct Debit payments to " . $CONFIG['CompanyName'], 'interval_length' => '1', 'interval_unit' => 'day', 'start_at' => date_format(date_create($aInvoice['date'] . ' -2 days'), 'Y-m-d\\TH:i:sO'), 'user' => $aUser, 'state' => $params['invoiceid'] . ':' . $aRecurrings['recurringamount'])); # return the recurring preauth button code $sButton = (GoCardless::$environment == 'sandbox' ? '<strong style="color: #FF0000; font-size: 16px;">SANDBOX MODE</strong><br />' : null) . 'When you get to GoCardless you will see an agreement for the <b>maximum possible amount</b> we\'ll ever need to charge you in a single invoice for this order, with a frequency of the shortest item\'s billing cycle. But rest assured we will never charge you more than the actual amount due. <br /><a onclick="window.location=\'' . $url . '\';" href="' . $url . '" style="text-decoration: none"><input type="button" onclick="window.location=\'' . $url . '\';" value="' . $title . '" /></a>'; } # return the formatted button return $sButton; }
public function gocardless_complete() { $flash_success = $this->session->flashdata(__FUNCTION__ . '_success'); if ($flash_success) { $this->session->keep_flashdata('notice'); return redirect('order'); } //get going with Go Cardless require_once APPPATH . '/third_party/GoCardless.php'; GoCardless::$environment = config_item('gocardless_environment'); GoCardless::set_account_details(config_item('gocardless_account')); //we've come back from Go Cardless //finalize the process $confirm_params = array('resource_uri' => $this->input->get('resource_uri'), 'resource_id' => $this->input->get('resource_id'), 'resource_type' => $this->input->get('resource_type'), 'signature' => $this->input->get('signature'), 'state' => $this->input->get('state')); // Returns the confirmed resource if successful, otherwise throws an exception $confirm_result = GoCardless::confirm_resource($confirm_params); if (!$confirm_result) { $this->flash->set('error', 'There was an error processing with Go Cardless.', TRUE); return redirect('bill/view/' . $this->input->get('state')); } //check what to do now //var_export($this->input->get()); die(); if ($this->input->get('resource_type') == 'bill') { //a single bill was paid, update it $this->load->model('order_model'); $result = $this->order_model->mark_bill_paid($this->input->get('state'), 'Go Cardless'); //send the user on if (!$result) { $this->flash->set('error', 'The payment was taken, but an error occured updating the bill. Please contact website staff.', TRUE); } else { $this->flash->set(__FUNCTION__ . '_success', TRUE, TRUE); $this->flash->set('notice', 'Thank you for paying with Go Cardless.', TRUE); } return redirect('order'); } else { if ($this->input->get('resource_type') == 'pre_authorization') { //Go Cardless is authorized to take payments. //make a note $this->load->model('order_model'); $this->order_model->gc_save_preauth_id($this->session->userdata('u_id'), $this->input->get('resource_id')); //Pay a bill we were on? if (is_numeric($this->input->get('state')) && $this->input->get('state') > 0) { //get the bill to pay. $this->load->model('order_model'); $bill = $this->order_model->get_bill($this->input->get('state')); if (isset($bill)) { //pay the bill we were on... $pre_auth = GoCardless_PreAuthorization::find($this->input->get('resource_id')); $gc_bill = $pre_auth->create_bill(array('name' => 'Bill #' . $bill['b_id'], 'amount' => $bill['b_price'])); } //send the user on if (!$gc_bill) { $this->flash->set('error', 'Go Cardless was authorised for futue payments, but an error occured paying this bill.', TRUE); } else { //after authorizing bill was paid, update it $this->load->model('order_model'); $result = $this->order_model->mark_bill_paid($this->input->get('state'), 'Go Cardless'); //send the user on if (!$result) { $this->flash->set('error', 'Payment was taken, but an error occured updating the bill. Please contact website staff.', TRUE); } else { $this->flash->set('notice', 'Thank you for paying with Go Cardless. Future payments will be made automatically.', TRUE); } } return redirect('order'); } else { $this->flash->set('success', 'Go Cardless has been set up for future bills.', TRUE); return redirect('order'); //send them where? } } else { $this->flash->set('error', 'Payment process not recognised.', TRUE); return redirect('order'); } } }
function gocardless_confirm() { if (isset($_GET['resource_id']) && isset($_GET['resource_type'])) { // Get vars found so confirm payment // Load GoCardless gocardless_init(); // Params for confirming the resource $confirm_params = array('resource_id' => $_GET['resource_id'], 'resource_type' => $_GET['resource_type'], 'resource_uri' => $_GET['resource_uri'], 'signature' => $_GET['signature']); // State is optional if (isset($_GET['state'])) { $confirm_params['state'] = $_GET['state']; } // Confirm the resource $confirmed_resource = GoCardless::confirm_resource($confirm_params); } }
/** * Initialization function called with account details * * @param array $account_details Array of account details */ public static function set_account_details($account_details) { GoCardless::$client = new GoCardless_Client($account_details); }
require_once $whmcsdir . '/includes/gatewayfunctions.php'; require_once $whmcsdir . '/includes/invoicefunctions.php'; require_once $whmcsdir . '/modules/gateways/gocardless.php'; # get gateway params using WHMCS getGatewayVariables method $gateway = getGatewayVariables('gocardless'); # sanity check to ensure module is active if (!$gateway['type']) { die("Module Not Activated"); } # set relevant API information for GoCardless module gocardless_set_account_details($gateway); # get the raw contents of the callback and decode JSON $webhook = file_get_contents('php://input'); $webhook_array = json_decode($webhook, true); # validate the webhook by verifying the integrity of the payload with GoCardless if (GoCardless::validate_webhook($webhook_array['payload']) !== true) { # we could not validate the web hook header('HTTP/1.1 400 Bad Request'); exit(__LINE__ . ': Payload could not be verified'); } # store various elements of the webhook array into params $val = $webhook_array['payload']; # base what we are doing depending on the resource type switch ($val['resource_type']) { case 'pre_authorization': # handle preauths (possible actions - cancelled, expired) switch ($val['action']) { # handle cancelled or expired preauths case 'cancelled': case 'expired': # delete related preauths
/** * Make a request to the API * * @param string $method The request method to use * @param string $endpoint The API endpoint to call * @param string $params The parameters to send with the request * * @return object The returned object */ public function request($method, $endpoint, $params = array()) { // If there is no http_authorization, try checking for access_token if (!isset($params['http_authorization'])) { // No http_authorization and no access_token? Fail if (!isset($this->account_details['access_token'])) { throw new GoCardless_ClientException('Access token missing'); } // access_token found so set Authorization header to contain bearer $params['http_bearer'] = $this->account_details['access_token']; } // Set application specific user agent suffix if found if (isset($this->account_details['ua_tag'])) { $params['ua_tag'] = $this->account_details['ua_tag']; } if (substr($endpoint, 0, 6) == '/oauth') { // OAuth API calls don't require /api/v1 base $url = $this->base_url . $endpoint; } else { // http://sandbox.gocardless.com | /api/v1 | /test $url = $this->base_url . self::$api_path . $endpoint; } // Call Request class (might be aliased for testing) with URL & params return call_user_func(GoCardless::getClass('Request') . '::' . $method, $url, $params); }
/** * Validate the payload of a webhook * * @param array $params The payload of the webhook * * @return boolean True if webhook signature is valid */ public static function validate_webhook($params) { return GoCardless::$client->validate_webhook($params); }
function doTransferCheckout(&$params, $component) { $paymentProcessorType = CRM_Core_PseudoConstant::paymentProcessorType(false, null, 'name'); $paymentProcessorTypeId = CRM_Utils_Array::key('Gocardless', $paymentProcessorType); $domainID = CRM_Core_Config::domainID(); $sql = " SELECT user_name "; $sql .= " , password "; $sql .= " , signature "; $sql .= " , subject "; $sql .= " FROM civicrm_payment_processor "; $sql .= " WHERE payment_processor_type_id = %1 "; $sql .= " AND is_test= %2 "; $sql .= " AND domain_id = %3 "; $isTest = 0; if ($this->_mode == 'test') { $isTest = 1; } $sql_params = array(1 => array($paymentProcessorTypeId, 'Integer'), 2 => array($isTest, 'Int'), 3 => array($domainID, 'Int')); $dao = CRM_Core_DAO::executeQuery($sql, $sql_params); if ($dao->fetch()) { $app_id = $dao->user_name; $app_secret = $dao->password; $merchant_id = $dao->signature; $access_token = $dao->subject; } $account_details = array('app_id' => $app_id, 'app_secret' => $app_secret, 'merchant_id' => $merchant_id, 'access_token' => $access_token); // Fail nicely if no account details set if (!$account_details['app_id'] && !$account_details['app_secret']) { echo '<p>First sign up to <a href="http://gocardless.com">GoCardless</a> and copy your sandbox API credentials from the \'Developer\' tab into the top of this script.</p>'; exit; } // Set $environment to 'production' if live. Default is 'sandbox' if ($this->_mode == 'live') { GoCardless::$environment = 'production'; } // Initialize GoCardless GoCardless::set_account_details($account_details); $goCardLessParams = array(); $goCardLessParams['amount'] = $params['amount']; $goCardLessParams['interval_length'] = $params['frequency_interval']; $goCardLessParams['interval_unit'] = $params['frequency_unit']; if (!empty($params['preferred_collection_day'])) { $preferredCollectionDay = $params['preferred_collection_day']; $collectionDate = UK_Direct_Debit_Form_Main::firstCollectionDate($preferredCollectionDay, null); // ISO8601 format. $goCardLessParams['start_at'] = $collectionDate->format('c'); } $url = $component == 'event' ? 'civicrm/event/register' : 'civicrm/contribute/transact'; $cancel = $component == 'event' ? '_qf_Register_display' : '_qf_Main_display'; $returnURL = CRM_Utils_System::url($url, "_qf_ThankYou_display=1&qfKey={$params['qfKey']}" . "&cid={$params['contactID']}", true, null, false); $goCardLessParams['redirect_uri'] = $returnURL; $goCardLessParams['user'] = array('email' => isset($params['email-5']) ? $params['email-5'] : NULL, 'first_name' => isset($params['first_name']) ? $params['first_name'] : NULL, 'last_name' => isset($params['last_name']) ? $params['last_name'] : NULL, 'billing_address1' => isset($params['street_address']) ? $params['street_address'] : NULL, 'billing_town' => isset($params['city']) ? $params['city'] : NULL, 'billing_postcode' => isset($params['postal_code']) ? $params['postal_code'] : NULL, 'country_code' => 'GB'); // Allow further manipulation of the arguments via custom hooks .. CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $goCardLessParams); $subscription_url = GoCardless::new_subscription_url($goCardLessParams); CRM_Utils_System::redirect($subscription_url); }
$pre_auth_url = GoCardless::new_pre_authorization_url($payment_details); echo ' · <a href="' . $pre_auth_url . '">New pre-authorized payment</a>'; // New bill $payment_details = array('amount' => '30.00', 'name' => 'Donation', 'user' => array('first_name' => 'Tom', 'last_name' => 'Blomfield', 'email' => '*****@*****.**')); $bill_url = GoCardless::new_bill_url($payment_details); echo ' · <a href="' . $bill_url . '">New bill</a></p>'; echo 'NB. The \'new bill\' link is also a demo of pre-populated user data'; echo '<h2>API calls</h2>'; echo 'GoCardless_Merchant::find(\'258584\')'; echo '<blockquote><pre>'; $merchant = GoCardless_Merchant::find('258584'); print_r($merchant); echo '</pre></blockquote>'; echo 'GoCardless_Merchant::find(\'258584\')->pre_authorizations()'; echo '<blockquote><pre>'; $preauths = GoCardless_Merchant::find('258584')->pre_authorizations(); print_r($preauths); echo '</pre></blockquote>'; echo 'GoCardless_PreAuthorization::find(\'992869\')->create_bill($bill_details)'; echo '<blockquote><pre>'; $pre_auth = GoCardless_PreAuthorization::find('013M018V0K'); $bill_details = array('amount' => '15.00'); $bill = $pre_auth->create_bill($bill_details); print_r($bill); echo '</pre></blockquote>'; echo 'validate webhook:'; echo '<blockquote><pre>'; $webhook_json = '{"payload":{"bills":[{"id":"880807"},{"status":"pending"},{"source_type":"subscription"},{"source_id":"21"},{"uri":"https:\\/\\/sandbox.gocardless.com\\/api\\/v1\\/bills\\/880807"}],"action":"created","resource_type":"bill","signature":"f25a611fb9afbc272ab369ead52109edd8a88cbb29a3a00903ffbce0ec6be5cb"}}'; $webhook = json_decode($webhook_json, true); var_dump(GoCardless::validate_webhook($webhook['payload'])); echo '</pre></blockquote>';
/** * Tries to auto pay a bill with Go Cardless, o e-mails the user, and updates the bill status as relevant * * @author GM * @param $b_id int the id of the bill * @param $u_id int the id of the user that needs to pay * @param $b_price float the price of the bill that we want to debit from them */ public function make_bill_due_and_pay($b_id, $u_id, $b_price) { //error avoidance if ($b_price <= 0) { return array('success' => FALSE, 'description' => 'Amount due must be positive, Bill #' . $b_id . ' not marked as due.'); } //have they authorised Go Cardless in the past? $pre_auth_id = $this->gc_get_preauth_id($u_id); if (!$pre_auth_id) { //set bill as due, e-mail them asking to pay $result = $this->change_bill_status($b_id, "Pending"); if ($result) { //email them about it $this->load->model('users_model'); $member = $this->users_model->get_user($u_id); $subject = config_item('site_name') . ' Payment is due. '; $message = '<p>Hello ' . $member['u_title'] . ' ' . $member['u_fname'] . ' ' . $member['u_sname'] . ',</p>'; $message .= '<p>Bill #' . $b_id . ', is now ready for you to pay.'; $message .= '<br />The amount for your recent delivery is <em>£' . $b_price . '</em>.'; $message .= '<br />You can view details of this bill and pay online at <a href="' . site_url('bill/view/' . $b_id) . '">' . site_url('bill/view/' . $b_id) . '</a>.</p>'; $message .= '<p>Thank you, <br /> ' . config_item('site_name') . '</p>'; $eq[] = array('eq_email' => $member['u_email'], 'eq_subject' => $subject, 'eq_body' => $message); // load emails queue model $this->load->model('emails_queue_model'); $this->emails_queue_model->set_queue($eq); return array('success' => TRUE, 'description' => 'The member has been notified that the bill is due.'); } else { return array('success' => FALSE, 'description' => 'The bill status could not be updated.'); } } else { //is Go Cardless working & enough? require_once APPPATH . '/third_party/GoCardless.php'; GoCardless::$environment = config_item('gocardless_environment'); GoCardless::set_account_details(config_item('gocardless_account')); $pre_auth = GoCardless_PreAuthorization::find($pre_auth_id); if (isset($pre_auth) && $pre_auth->status == 'active' && $pre_auth->remaining_amount >= $b_price) { //try paying it $bill_details = array('name' => 'Bill #' . $b_id, 'amount' => $b_price); $gc_bill = $pre_auth->create_bill($bill_details); if ($gc_bill) { //mark it as paid $result = $this->mark_bill_paid($b_id, 'Go Cardless Pre-Auth'); if (!$result) { return array('success' => FALSE, 'description' => 'Bill ' . $b_id . ' was paid, but an error caused it not to be marked as such.'); } else { return array('success' => TRUE, 'description' => 'The bill was paid through Go Cardless pre-authorisation.'); } } } //set bill as due, e-mail them asking to pay, because GC couldn't be used (or was not enough) $result = $this->change_bill_status($b_id, "Pending"); if ($result) { //email them about it $this->load->model('users_model'); $member = $this->users_model->get_user($u_id); $subject = config_item('site_name') . ' Payment is due. '; $message = '<p>Hello ' . $member['u_title'] . ' ' . $member['u_fname'] . ' ' . $member['u_sname'] . ',</p>'; $message .= '<p>Bill #' . $b_id . ', is now ready for you to pay.'; $message .= '<br />The amount for your recent delivery is <em>£' . $b_price . '</em>.'; $message .= '<br />On this occasion, we were unable to debit the amount from your bank through the Go Cardless system.'; $message .= '<br />You can view details of this bill and pay online at <a href="' . site_url('bill/view/' . $b_id) . '">' . site_url('bill/view/' . $b_id) . '</a>.</p>'; $message .= '<p>Thank you, <br /> ' . config_item('site_name') . '</p>'; $eq[] = array('eq_email' => $member['u_email'], 'eq_subject' => $subject, 'eq_body' => $message); // load emails queue model $this->load->model('emails_queue_model'); $this->emails_queue_model->set_queue($eq); return array('success' => TRUE, 'description' => 'The member has been notified that the bill is due.'); } else { return array('success' => FALSE, 'description' => 'The bill status could not be updated.'); } } }
<?php require_once $_SERVER['DOCUMENT_ROOT'] . '/../lib/init.php'; $webhook = file_get_contents('php://input'); $webhook_array = json_decode($webhook, true); $webhook_valid = GoCardless::validate_webhook($webhook_array['payload']); if ($webhook_valid == TRUE) { header('HTTP/1.1 200 OK'); } else { header('HTTP/1.1 403 Invalid signature'); }
public function newBillUrl($payment_details) { return \GoCardless::new_bill_url($payment_details); }
require_once "{$root}/user.php"; require_once "{$root}/transaction.php"; require_once "{$root}/card.php"; require_once "{$root}/usersprofile.php"; require_once "{$root}/learning.php"; require_once "{$root}/alias.php"; require_once "{$root}/interest.php"; require_once "{$root}/calendar.php"; require_once "{$root}/project.php"; require_once "{$root}/gocardless-php/lib/GoCardless.php"; $db = new fDatabase('postgresql', $DB_NAME, $DB_USER, $DB_PASSWORD); fORMDatabase::attach($db); fSession::setLength('30 minutes', '10 weeks'); fSession::setPath(dirname(__FILE__) . '/../var/session'); if (isset($GOCARDLESS_CREDENTIALS)) { GoCardless::set_account_details($GOCARDLESS_CREDENTIALS); } if ($uid = fSession::get('user')) { $user = new User($uid); } else { $user = null; } function ensureLogin() { global $user; if (!isset($user)) { fURL::redirect("/login.php?forward={$_SERVER['REQUEST_URI']}"); } } function ensureMember() {
* * This page then does the following: * * 1. Generates an authorize link * 2. Generates an access_token from the retured $_GET['code'] * 3. Instantiates a new GoCardless_Client object * 4. Fetch the current merchant's details * 5. Fetch the current merchant's pre-authorizations * 6. Create a bill under a pre-authorizations * 7. Repeat steps 4 and 5 with a new GoCardless_Client object * */ // Include library include_once '../lib/gocardless.php'; // Sandbox GoCardless::$environment = 'sandbox'; // Config vars for your PARTNER account $account_details = array('app_id' => null, 'app_secret' => null, 'access_token' => null, 'merchant_id' => null); $gocardless_client = new GoCardless_Client($account_details); if (isset($_GET['code'])) { $params = array('client_id' => $account_details['app_id'], 'code' => $_GET['code'], 'redirect_uri' => 'http://localhost/examples/demo_partner.php', 'grant_type' => 'authorization_code'); // Fetching token returns merchant_id and access_token $token = $gocardless_client->fetch_access_token($params); $account_details = array('app_id' => null, 'app_secret' => null, 'access_token' => null, 'merchant_id' => null); $gocardless_client = new GoCardless_Client($account_details); echo '<p>Authorization successful! <br />Add the following to your database for this merchant <br />Access token: ' . $token['access_token'] . ' <br />Merchant id: ' . $token['merchant_id'] . '</p>'; } if ($account_details['access_token']) {
/** * Caller Magic Method * * @param string * @param array * @return object */ public function __call($method, $params) { GoCardless::$environment = $this->_config['mode'] == 'test' ? 'sandbox' : 'production'; $account_details = array('app_id' => $this->_config['app_identifier'], 'app_secret' => $this->_config['app_secret'], 'merchant_id' => $this->_config['id'], 'access_token' => $this->_config['access_token']); GoCardless::set_account_details($account_details); $args = $params[0]; $this->_lib_method = $method; list($api, $api_method, $params_ready) = $this->_build_request($args); try { $raw = $api::$api_method($params_ready); return $this->_parse_response($raw); } catch (Exception $e) { return Payment_Response::instance()->gateway_response('failure', $method . '_gateway_failure', $e->getMessage()); } }
/** * Constructor, creates a new instance of GoCardless_Client * * @param array $account_details Parameters */ public function __construct($account_details) { // Fetch account_details foreach ($account_details as $key => $value) { $this->account_details[$key] = $value; } // Check for app_id if (!isset($this->account_details['app_id'])) { throw new GoCardless_ClientException('No app_id specified'); } // Check for app_secret if (!isset($this->account_details['app_secret'])) { throw new GoCardless_ClientException('No app_secret specfied'); } // If environment is not set then default to production if (!isset(GoCardless::$environment)) { GoCardless::$environment = 'production'; } // If base_url is not set then set it based on environment if (!isset(GoCardless_Client::$base_url)) { GoCardless_Client::$base_url = GoCardless_Client::$base_urls[GoCardless::$environment]; } }
public function processCallback() { $webhook = file_get_contents('php://input'); $webhook_array = json_decode($webhook, true); if (\GoCardless::validate_webhook($webhook_array['payload']) == true) { header('HTTP/1.1 200 OK'); foreach ($webhook_array['payload']['bills'] as $bill) { $orders = $this->orderFactory->getByTransactionReference($bill['id']); if (count($orders) == 1) { $order = $orders->pop(); if (floatval($order->getTotalCost()) === floatval($bill['amount'])) { $this->updateOrder($order, $bill['status']); } } } } }