Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.

Differences Between: [Versions 310 and 401]

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  14  // You should have received a copy of the GNU General Public License
  15  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  16  
  17  /**
  18   * Contains helper class for the payment subsystem.
  19   *
  20   * @package    core_payment
  21   * @copyright  2019 Shamim Rezaie <shamim@moodle.com>
  22   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23   */
  24  
  25  namespace core_payment;
  26  
  27  use core_payment\event\account_created;
  28  use core_payment\event\account_deleted;
  29  use core_payment\event\account_updated;
  30  
  31  /**
  32   * Helper class for the payment subsystem.
  33   *
  34   * @copyright  2019 Shamim Rezaie <shamim@moodle.com>
  35   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  36   */
  37  class helper {
  38  
  39      /**
  40       * Returns an accumulated list of supported currencies by all payment gateways.
  41       *
  42       * @return string[] An array of the currency codes in the three-character ISO-4217 format
  43       */
  44      public static function get_supported_currencies(): array {
  45          $currencies = [];
  46  
  47          $plugins = \core_plugin_manager::instance()->get_enabled_plugins('paygw');
  48          foreach ($plugins as $plugin) {
  49              /** @var \paygw_paypal\gateway $classname */
  50              $classname = '\paygw_' . $plugin . '\gateway';
  51  
  52              $currencies = array_merge($currencies, component_class_callback($classname, 'get_supported_currencies', [], []));
  53          }
  54  
  55          $currencies = array_unique($currencies);
  56  
  57          return $currencies;
  58      }
  59  
  60      /**
  61       * Returns the list of gateways that can process payments in the given currency.
  62       *
  63       * @param string $component Name of the component that the paymentarea and itemid belong to
  64       * @param string $paymentarea Payment area
  65       * @param int $itemid An identifier that is known to the component
  66       * @return string[]
  67       */
  68      public static function get_available_gateways(string $component, string $paymentarea, int $itemid): array {
  69          $gateways = [];
  70  
  71          $payable = static::get_payable($component, $paymentarea, $itemid);
  72          $account = new account($payable->get_account_id());
  73  
  74          if (!$account->get('id') || !$account->get('enabled')) {
  75              return $gateways;
  76          }
  77  
  78          $currency = $payable->get_currency();
  79          foreach ($account->get_gateways() as $plugin => $gateway) {
  80              if (!$gateway->get('enabled')) {
  81                  continue;
  82              }
  83              /** @var gateway $classname */
  84              $classname = '\paygw_' . $plugin . '\gateway';
  85  
  86              $currencies = component_class_callback($classname, 'get_supported_currencies', [], []);
  87              if (in_array($currency, $currencies)) {
  88                  $gateways[] = $plugin;
  89              }
  90          }
  91  
  92          return $gateways;
  93      }
  94  
  95      /**
  96       * Rounds the cost based on the currency fractional digits, can also apply surcharge
  97       *
  98       * @param float $amount amount in the currency units
  99       * @param string $currency currency, used for calculating the number of fractional digits
 100       * @param float $surcharge surcharge in percents
 101       * @return float
 102       */
 103      public static function get_rounded_cost(float $amount, string $currency, float $surcharge = 0): float {
 104          $amount = $amount * (100 + $surcharge) / 100;
 105  
 106          $locale = get_string('localecldr', 'langconfig');
 107          $fmt = \NumberFormatter::create($locale, \NumberFormatter::CURRENCY);
 108          $localisedcost = numfmt_format_currency($fmt, $amount, $currency);
 109  
 110          return numfmt_parse_currency($fmt, $localisedcost, $currency);
 111      }
 112  
 113      /**
 114       * Returns human-readable amount with correct number of fractional digits and currency indicator, can also apply surcharge
 115       *
 116       * @param float $amount amount in the currency units
 117       * @param string $currency The currency
 118       * @param float $surcharge surcharge in percents
 119       * @return string
 120       */
 121      public static function get_cost_as_string(float $amount, string $currency, float $surcharge = 0): string {
 122          $amount = $amount * (100 + $surcharge) / 100;
 123  
 124          $locale = get_string('localecldr', 'langconfig');
 125          $fmt = \NumberFormatter::create($locale, \NumberFormatter::CURRENCY);
 126          $localisedcost = numfmt_format_currency($fmt, $amount, $currency);
 127  
 128          return $localisedcost;
 129      }
 130  
 131      /**
 132       * Returns the percentage of surcharge that is applied when using a gateway
 133       *
 134       * @param string $gateway Name of the gateway
 135       * @return float
 136       */
 137      public static function get_gateway_surcharge(string $gateway): float {
 138          return (float)get_config('paygw_' . $gateway, 'surcharge');
 139      }
 140  
 141      /**
 142       * Returns the attributes to place on a pay button.
 143       *
 144       * @param string $component Name of the component that the paymentarea and itemid belong to
 145       * @param string $paymentarea Payment area
 146       * @param int $itemid An internal identifier that is used by the component
 147       * @param string $description Description of the payment
 148       * @return array
 149       */
 150      public static function gateways_modal_link_params(string $component, string $paymentarea, int $itemid,
 151              string $description): array {
 152  
 153          $payable = static::get_payable($component, $paymentarea, $itemid);
 154          $successurl = static::get_success_url($component, $paymentarea, $itemid);
 155  
 156          return [
 157              'id' => 'gateways-modal-trigger',
 158              'role' => 'button',
 159              'data-action' => 'core_payment/triggerPayment',
 160              'data-component' => $component,
 161              'data-paymentarea' => $paymentarea,
 162              'data-itemid' => $itemid,
 163              'data-cost' => static::get_cost_as_string($payable->get_amount(), $payable->get_currency()),
 164              'data-description' => $description,
 165              'data-successurl' => $successurl->out(false),
 166          ];
 167      }
 168  
 169      /**
 170       * Get the name of the service provider class
 171       *
 172       * @param string $component The component
 173       * @return string
 174       * @throws \coding_exception
 175       */
 176      private static function get_service_provider_classname(string $component) {
 177          $providerclass = "$component\\payment\\service_provider";
 178  
 179          if (class_exists($providerclass)) {
 180              $rc = new \ReflectionClass($providerclass);
 181              if ($rc->implementsInterface(local\callback\service_provider::class)) {
 182                  return $providerclass;
 183              }
 184          }
 185  
 186          throw new \coding_exception("$component does not have an eligible implementation of payment service_provider.");
 187      }
 188  
 189      /**
 190       * Asks the payable from the related component.
 191       *
 192       * @param string $component Name of the component that the paymentarea and itemid belong to
 193       * @param string $paymentarea Payment area
 194       * @param int $itemid An internal identifier that is used by the component
 195       * @return local\entities\payable
 196       */
 197      public static function get_payable(string $component, string $paymentarea, int $itemid): local\entities\payable {
 198          $providerclass = static::get_service_provider_classname($component);
 199  
 200          return component_class_callback($providerclass, 'get_payable', [$paymentarea, $itemid]);
 201      }
 202  
 203      /**
 204       * Fetches the URL of the page the user should be redirected to from the related component
 205       *
 206       * @param string $component Name of the component that the paymentarea and itemid belong to
 207       * @param string $paymentarea Payment area
 208       * @param int $itemid An identifier that is known to the component
 209       * @return \moodle_url
 210       */
 211      public static function get_success_url(string $component, string $paymentarea, int $itemid): \moodle_url {
 212          $providerclass = static::get_service_provider_classname($component);
 213          return component_class_callback($providerclass, 'get_success_url', [$paymentarea, $itemid]);
 214      }
 215  
 216      /**
 217       * Returns the gateway configuration for given component and gateway
 218       *
 219       * @param string $component Name of the component that the paymentarea and itemid belong to
 220       * @param string $paymentarea Payment area
 221       * @param int $itemid An identifier that is known to the component
 222       * @param string $gatewayname The gateway name
 223       * @return array
 224       * @throws \moodle_exception
 225       */
 226      public static function get_gateway_configuration(string $component, string $paymentarea, int $itemid,
 227              string $gatewayname): array {
 228          $payable = self::get_payable($component, $paymentarea, $itemid);
 229          $gateway = null;
 230          $account = new account($payable->get_account_id());
 231          if ($account && $account->get('enabled')) {
 232              $gateway = $account->get_gateways()[$gatewayname] ?? null;
 233          }
 234          if (!$gateway) {
 235              throw new \moodle_exception('gatewaynotfound', 'payment');
 236          }
 237          return $gateway->get_configuration();
 238      }
 239  
 240      /**
 241       * Delivers what the user paid for.
 242       *
 243       * @uses \core_payment\local\callback\service_provider::deliver_order()
 244       *
 245       * @param string $component Name of the component that the paymentarea and itemid belong to
 246       * @param string $paymentarea Payment area
 247       * @param int $itemid An internal identifier that is used by the component
 248       * @param int $paymentid payment id as inserted into the 'payments' table, if needed for reference
 249       * @param int $userid The userid the order is going to deliver to
 250       * @return bool Whether successful or not
 251       */
 252      public static function deliver_order(string $component, string $paymentarea, int $itemid, int $paymentid, int $userid): bool {
 253          $providerclass = static::get_service_provider_classname($component);
 254          $result = component_class_callback($providerclass, 'deliver_order', [$paymentarea, $itemid, $paymentid, $userid]);
 255  
 256          return $result;
 257      }
 258  
 259      /**
 260       * Stores essential information about the payment and returns the "id" field of the payment record in DB.
 261       * Each payment gateway may then store the additional information their way.
 262       *
 263       * @param int $accountid Account id
 264       * @param string $component Name of the component that the paymentarea and itemid belong to
 265       * @param string $paymentarea Payment area
 266       * @param int $itemid An internal identifier that is used by the component
 267       * @param int $userid Id of the user who is paying
 268       * @param float $amount Amount of payment
 269       * @param string $currency Currency of payment
 270       * @param string $gateway The gateway that is used for the payment
 271       * @return int
 272       */
 273      public static function save_payment(int $accountid, string $component, string $paymentarea, int $itemid, int $userid,
 274              float $amount, string $currency, string $gateway): int {
 275          global $DB;
 276  
 277          $record = new \stdClass();
 278          $record->component = $component;
 279          $record->paymentarea = $paymentarea;
 280          $record->itemid = $itemid;
 281          $record->userid = $userid;
 282          $record->amount = $amount;
 283          $record->currency = $currency;
 284          $record->gateway = $gateway;
 285          $record->accountid = $accountid;
 286          $record->timecreated = $record->timemodified = time();
 287  
 288          $id = $DB->insert_record('payments', $record);
 289  
 290          return $id;
 291      }
 292  
 293      /**
 294       * This functions adds the settings that are common for all payment gateways.
 295       *
 296       * @param \admin_settingpage $settings The settings object
 297       * @param string $gateway The gateway name prefixed with paygw_
 298       */
 299      public static function add_common_gateway_settings(\admin_settingpage $settings, string $gateway): void {
 300          $settings->add(new \admin_setting_configtext($gateway . '/surcharge', get_string('surcharge', 'core_payment'),
 301                  get_string('surcharge_desc', 'core_payment'), 0, PARAM_INT));
 302  
 303      }
 304  
 305      /**
 306       * Save a new or edited payment account (used in management interface)
 307       *
 308       * @param \stdClass $data
 309       * @return account
 310       */
 311      public static function save_payment_account(\stdClass $data): account {
 312  
 313          if (empty($data->id)) {
 314              $account = new account(0, $data);
 315              $account->save();
 316              account_created::create_from_account($account)->trigger();
 317          } else {
 318              $account = new account($data->id);
 319              $account->from_record($data);
 320              $account->save();
 321              account_updated::create_from_account($account)->trigger();
 322          }
 323  
 324          return $account;
 325      }
 326  
 327      /**
 328       * Delete a payment account (used in management interface)
 329       *
 330       * @param account $account
 331       */
 332      public static function delete_payment_account(account $account): void {
 333          global $DB;
 334          if ($DB->record_exists('payments', ['accountid' => $account->get('id')])) {
 335              $account->set('archived', 1);
 336              $account->save();
 337              account_updated::create_from_account($account, ['archived' => 1])->trigger();
 338              return;
 339          }
 340  
 341          foreach ($account->get_gateways(false) as $gateway) {
 342              if ($gateway->get('id')) {
 343                  $gateway->delete();
 344              }
 345          }
 346          $event = account_deleted::create_from_account($account);
 347          $account->delete();
 348          $event->trigger();
 349      }
 350  
 351      /**
 352       * Restore archived payment account (used in management interface)
 353       *
 354       * @param account $account
 355       */
 356      public static function restore_payment_account(account $account): void {
 357          $account->set('archived', 0);
 358          $account->save();
 359          account_updated::create_from_account($account, ['restored' => 1])->trigger();
 360      }
 361  
 362      /**
 363       * Save a payment gateway linked to an existing account (used in management interface)
 364       *
 365       * @param \stdClass $data
 366       * @return account_gateway
 367       */
 368      public static function save_payment_gateway(\stdClass $data): account_gateway {
 369          if (empty($data->id)) {
 370              $records = account_gateway::get_records(['accountid' => $data->accountid, 'gateway' => $data->gateway]);
 371              if ($records) {
 372                  $gateway = reset($records);
 373              } else {
 374                  $gateway = new account_gateway(0, $data);
 375              }
 376          } else {
 377              $gateway = new account_gateway($data->id);
 378          }
 379          unset($data->accountid, $data->gateway, $data->id);
 380          $gateway->from_record($data);
 381  
 382          $account = $gateway->get_account();
 383          $gateway->save();
 384          account_updated::create_from_account($account)->trigger();
 385          return $gateway;
 386      }
 387  
 388      /**
 389       * Returns the list of payment accounts in the given context (used in management interface)
 390       *
 391       * @param \context $context
 392       * @return account[]
 393       */
 394      public static function get_payment_accounts_to_manage(\context $context, bool $showarchived = false): array {
 395          $records = account::get_records(['contextid' => $context->id] + ($showarchived ? [] : ['archived' => 0]));
 396          \core_collator::asort_objects_by_method($records, 'get_formatted_name');
 397          return $records;
 398      }
 399  
 400      /**
 401       * Get list of accounts available in the given context
 402       *
 403       * @param \context $context
 404       * @return array
 405       */
 406      public static function get_payment_accounts_menu(\context $context): array {
 407          global $DB;
 408          [$sql, $params] = $DB->get_in_or_equal($context->get_parent_context_ids(true));
 409          $accounts = array_filter(account::get_records_select('contextid '.$sql, $params), function($account) {
 410              return $account->is_available() && !$account->get('archived');
 411          });
 412          return array_map(function($account) {
 413              return $account->get_formatted_name();
 414          }, $accounts);
 415      }
 416  }