2 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
18 * Contains helper class for the payment subsystem.
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
25 namespace core_payment;
27 use core_payment\event\account_created;
28 use core_payment\event\account_deleted;
29 use core_payment\event\account_updated;
31 defined('MOODLE_INTERNAL') || die();
34 * Helper class for the payment subsystem.
36 * @copyright 2019 Shamim Rezaie <shamim@moodle.com>
37 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
42 * Returns an accumulated list of supported currencies by all payment gateways.
44 * @return string[] An array of the currency codes in the three-character ISO-4217 format
46 public static function get_supported_currencies(): array {
49 $plugins = \core_plugin_manager::instance()->get_enabled_plugins('pg');
50 foreach ($plugins as $plugin) {
51 /** @var \pg_paypal\gateway $classname */
52 $classname = '\pg_' . $plugin . '\gateway';
54 $currencies += component_class_callback($classname, 'get_supported_currencies', [], []);
57 $currencies = array_unique($currencies);
63 * Returns the list of gateways that can process payments in the given currency.
65 * @param string $component
66 * @param int $componentid
69 public static function get_gateways_for_currency(string $component, int $componentid): array {
74 'currency' => $currency,
75 'accountid' => $accountid,
76 ] = self::get_cost($component, $componentid);
77 $account = new account($accountid);
78 if (!$account->get('id') || !$account->get('enabled')) {
82 foreach ($account->get_gateways() as $plugin => $gateway) {
83 if (!$gateway->get('enabled')) {
86 /** @var gateway $classname */
87 $classname = '\pg_' . $plugin . '\gateway';
89 $currencies = component_class_callback($classname, 'get_supported_currencies', [], []);
90 if (in_array($currency, $currencies)) {
91 $gateways[] = $plugin;
99 * Calculates the cost with the surcharge
101 * @param float $amount amount in the currency units
102 * @param float $surcharge surcharge in percents
103 * @param string $currency currency, used for calculating the number of fractional digits
106 public static function get_cost_with_surcharge(float $amount, float $surcharge, string $currency): float {
107 return round($amount + $amount * $surcharge / 100, 2); // TODO number of digits depends on currency.
111 * Returns human-readable amount with fixed number of fractional digits and currency indicator
113 * @param float $amount
114 * @param string $currency
116 * @throws \coding_exception
118 public static function get_cost_as_string(float $amount, string $currency): string {
119 if (class_exists('NumberFormatter') && function_exists('numfmt_format_currency')) {
120 $locale = get_string('localecldr', 'langconfig');
121 $fmt = \NumberFormatter::create($locale, \NumberFormatter::CURRENCY);
122 $localisedcost = numfmt_format_currency($fmt, $amount, $currency);
124 $localisedcost = sprintf("%.2f %s", $amount, $currency); // TODO number of digits depends on currency.
127 return $localisedcost;
131 * Returns the percentage of surcharge that is applied when using a gateway
133 * @param string $gateway Name of the gateway
136 public static function get_gateway_surcharge(string $gateway): float {
137 return (float)get_config('pg_' . $gateway, 'surcharge');
141 * Returns the attributes to place on a pay button.
143 * @param string $component Name of the component that the componentid belongs to
144 * @param int $componentid An internal identifier that is used by the component
145 * @param string $description Description of the payment
148 public static function gateways_modal_link_params(string $component, int $componentid, string $description): array {
151 'currency' => $currency
152 ] = self::get_cost($component, $componentid);
155 'id' => 'gateways-modal-trigger',
157 'data-component' => $component,
158 'data-componentid' => $componentid,
159 'data-cost' => self::get_cost_as_string($amount, $currency),
160 'data-description' => $description,
165 * Asks the cost from the related component.
167 * @param string $component Name of the component that the componentid belongs to
168 * @param int $componentid An internal identifier that is used by the component
169 * @return array['amount' => float, 'currency' => string, 'accountid' => int]
170 * @throws \moodle_exception
172 public static function get_cost(string $component, int $componentid): array {
173 $cost = component_class_callback("$component\\payment\\provider", 'get_cost', [$componentid]);
175 if ($cost === null || !is_array($cost) || !array_key_exists('amount', $cost)
176 || !array_key_exists('currency', $cost) || !array_key_exists('accountid', $cost) ) {
177 throw new \moodle_exception('callbacknotimplemented', 'core_payment', '', $component);
184 * Returns the gateway configuration for given component and gateway
186 * @param string $component
187 * @param int $componentid
188 * @param string $gatewayname
190 * @throws \moodle_exception
192 public static function get_gateway_configuration(string $component, int $componentid, string $gatewayname): array {
193 $x = self::get_cost($component, $componentid);
195 $account = new account($x['accountid']);
196 if ($account && $account->get('enabled')) {
197 $gateway = $account->get_gateways()[$gatewayname] ?? null;
200 throw new \moodle_exception('gatewaynotfound', 'payment');
202 return $gateway->get_configuration();
206 * Delivers what the user paid for.
208 * @uses \core_payment\local\callback\provider::deliver_order()
210 * @param string $component Name of the component that the componentid belongs to
211 * @param int $componentid An internal identifier that is used by the component
212 * @param int $paymentid payment id as inserted into the 'payments' table, if needed for reference
213 * @return bool Whether successful or not
215 public static function deliver_order(string $component, int $componentid, int $paymentid): bool {
216 $result = component_class_callback("$component\\payment\\provider", 'deliver_order', [$componentid, $paymentid]);
218 if ($result === null) {
219 throw new \moodle_exception('callbacknotimplemented', 'core_payment', '', $component);
226 * Stores essential information about the payment and returns the "id" field of the payment record in DB.
227 * Each payment gateway may then store the additional information their way.
229 * @param int $accountid Account id
230 * @param string $component Name of the component that the componentid belongs to
231 * @param int $componentid An internal identifier that is used by the component
232 * @param int $userid Id of the user who is paying
233 * @param float $amount Amount of payment
234 * @param string $currency Currency of payment
235 * @param string $gateway The gateway that is used for the payment
238 public static function save_payment(int $accountid, string $component, int $componentid, int $userid, float $amount, string $currency,
239 string $gateway): int {
242 $record = new \stdClass();
243 $record->component = $component;
244 $record->componentid = $componentid;
245 $record->userid = $userid;
246 $record->amount = $amount;
247 $record->currency = $currency;
248 $record->gateway = $gateway;
249 $record->accountid = $accountid;
250 $record->timecreated = $record->timemodified = time();
252 $id = $DB->insert_record('payments', $record);
258 * This functions adds the settings that are common for all payment gateways.
260 * @param \admin_settingpage $settings The settings object
261 * @param string $gateway The gateway name prefic with pg_
263 public static function add_common_gateway_settings(\admin_settingpage $settings, string $gateway): void {
264 $settings->add(new \admin_setting_configtext($gateway . '/surcharge', get_string('surcharge', 'core_payment'),
265 get_string('surcharge_desc', 'core_payment'), 0, PARAM_INT));
270 * Save a new or edited payment account (used in management interface)
272 * @param \stdClass $data
275 public static function save_payment_account(\stdClass $data): account {
277 if (empty($data->id)) {
278 $account = new account(0, $data);
280 account_created::create_from_account($account)->trigger();
282 $account = new account($data->id);
283 $account->from_record($data);
285 account_updated::create_from_account($account)->trigger();
292 * Delete a payment account (used in management interface)
294 * @param account $account
296 public static function delete_payment_account(account $account): void {
298 if ($DB->record_exists('payments', ['accountid' => $account->get('id')])) {
299 $account->set('archived', 1);
301 account_updated::create_from_account($account, ['archived' => 1])->trigger();
305 foreach ($account->get_gateways(false) as $gateway) {
306 if ($gateway->get('id')) {
310 $event = account_deleted::create_from_account($account);
316 * Restore archived payment account (used in management interface)
318 * @param account $account
320 public static function restore_payment_account(account $account): void {
321 $account->set('archived', 0);
323 account_updated::create_from_account($account, ['restored' => 1])->trigger();
327 * Save a payment gateway linked to an existing account (used in management interface)
329 * @param \stdClass $data
330 * @return account_gateway
332 public static function save_payment_gateway(\stdClass $data): account_gateway {
333 if (empty($data->id)) {
334 $records = account_gateway::get_records(['accountid' => $data->accountid, 'gateway' => $data->gateway]);
336 $gateway = reset($records);
338 $gateway = new account_gateway(0, $data);
341 $gateway = new account_gateway($data->id);
343 unset($data->accountid, $data->gateway, $data->id);
344 $gateway->from_record($data);
346 $account = $gateway->get_account();
348 account_updated::create_from_account($account)->trigger();
353 * Returns the list of payment accounts in the given context (used in management interface)
355 * @param \context $context
358 public static function get_payment_accounts_to_manage(\context $context, bool $showarchived = false): array {
359 $records = account::get_records(['contextid' => $context->id] + ($showarchived ? [] : ['archived' => 0]));
360 \core_collator::asort_objects_by_method($records, 'get_formatted_name');
365 * Get list of accounts available in the given context
367 * @param \context $context
370 public static function get_payment_accounts_menu(\context $context): array {
372 [$sql, $params] = $DB->get_in_or_equal($context->get_parent_context_ids(true));
373 $accounts = array_filter(account::get_records_select('contextid '.$sql, $params), function($account) {
374 return $account->is_available() && !$account->get('archived');
376 return array_map(function($account) {
377 return $account->get_formatted_name();