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 defined('MOODLE_INTERNAL') || die();
30 * Helper class for the payment subsystem.
32 * @copyright 2019 Shamim Rezaie <shamim@moodle.com>
33 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 * Returns an accumulated list of supported currencies by all payment gateways.
40 * @return string[] An array of the currency codes in the three-character ISO-4217 format
42 public static function get_supported_currencies(): array {
45 $plugins = \core_plugin_manager::instance()->get_enabled_plugins('pg');
46 foreach ($plugins as $plugin) {
47 /** @var \pg_paypal\gateway $classname */
48 $classname = '\pg_' . $plugin . '\gateway';
50 $currencies += component_class_callback($classname, 'get_supported_currencies', [], []);
53 $currencies = array_unique($currencies);
59 * Returns the list of gateways that can process payments in the given currency.
61 * @param string $component
62 * @param int $componentid
65 public static function get_gateways_for_currency(string $component, int $componentid): array {
70 'currency' => $currency,
71 'accountid' => $accountid,
72 ] = self::get_cost($component, $componentid);
73 $account = new account($accountid);
74 if (!$account->get('id') || !$account->get('enabled')) {
78 foreach ($account->get_gateways() as $plugin => $gateway) {
79 if (!$gateway->get('enabled')) {
82 /** @var gateway $classname */
83 $classname = '\pg_' . $plugin . '\gateway';
85 $currencies = component_class_callback($classname, 'get_supported_currencies', [], []);
86 if (in_array($currency, $currencies)) {
87 $gateways[] = $plugin;
95 * Calculates the cost with the surcharge
97 * @param float $amount amount in the currency units
98 * @param float $surcharge surcharge in percents
99 * @param string $currency currency, used for calculating the number of fractional digits
102 public static function get_cost_with_surcharge(float $amount, float $surcharge, string $currency): float {
103 return round($amount + $amount * $surcharge / 100, 2); // TODO number of digits depends on currency.
107 * Returns human-readable amount with fixed number of fractional digits and currency indicator
109 * @param float $amount
110 * @param string $currency
112 * @throws \coding_exception
114 public static function get_cost_as_string(float $amount, string $currency): string {
115 if (class_exists('NumberFormatter') && function_exists('numfmt_format_currency')) {
116 $locale = get_string('localecldr', 'langconfig');
117 $fmt = \NumberFormatter::create($locale, \NumberFormatter::CURRENCY);
118 $localisedcost = numfmt_format_currency($fmt, $amount, $currency);
120 $localisedcost = sprintf("%.2f %s", $amount, $currency); // TODO number of digits depends on currency.
123 return $localisedcost;
127 * Returns the percentage of surcharge that is applied when using a gateway
129 * @param string $gateway Name of the gateway
132 public static function get_gateway_surcharge(string $gateway): float {
133 return (float)get_config('pg_' . $gateway, 'surcharge');
137 * Returns the attributes to place on a pay button.
139 * @param string $component Name of the component that the componentid belongs to
140 * @param int $componentid An internal identifier that is used by the component
141 * @param string $description Description of the payment
144 public static function gateways_modal_link_params(string $component, int $componentid, string $description): array {
147 'currency' => $currency
148 ] = self::get_cost($component, $componentid);
151 'id' => 'gateways-modal-trigger',
153 'data-component' => $component,
154 'data-componentid' => $componentid,
155 'data-cost' => self::get_cost_as_string($amount, $currency),
156 'data-description' => $description,
161 * Asks the cost from the related component.
163 * @param string $component Name of the component that the componentid belongs to
164 * @param int $componentid An internal identifier that is used by the component
165 * @return array['amount' => float, 'currency' => string, 'accountid' => int]
166 * @throws \moodle_exception
168 public static function get_cost(string $component, int $componentid): array {
169 $cost = component_class_callback("$component\\payment\\provider", 'get_cost', [$componentid]);
171 if ($cost === null || !is_array($cost) || !array_key_exists('amount', $cost)
172 || !array_key_exists('currency', $cost) || !array_key_exists('accountid', $cost) ) {
173 throw new \moodle_exception('callbacknotimplemented', 'core_payment', '', $component);
180 * Returns the gateway configuration for given component and gateway
182 * @param string $component
183 * @param int $componentid
184 * @param string $gatewayname
186 * @throws \moodle_exception
188 public static function get_gateway_configuration(string $component, int $componentid, string $gatewayname): array {
189 $x = self::get_cost($component, $componentid);
191 $account = new account($x['accountid']);
192 if ($account && $account->get('enabled')) {
193 $gateway = $account->get_gateways()[$gatewayname] ?? null;
196 throw new \moodle_exception('gatewaynotfound', 'payment');
198 return $gateway->get_configuration();
202 * Delivers what the user paid for.
204 * @uses \core_payment\local\callback\provider::deliver_order()
206 * @param string $component Name of the component that the componentid belongs to
207 * @param int $componentid An internal identifier that is used by the component
208 * @param int $paymentid payment id as inserted into the 'payments' table, if needed for reference
209 * @return bool Whether successful or not
211 public static function deliver_order(string $component, int $componentid, int $paymentid): bool {
212 $result = component_class_callback("$component\\payment\\provider", 'deliver_order', [$componentid, $paymentid]);
214 if ($result === null) {
215 throw new \moodle_exception('callbacknotimplemented', 'core_payment', '', $component);
222 * Stores essential information about the payment and returns the "id" field of the payment record in DB.
223 * Each payment gateway may then store the additional information their way.
225 * @param int $accountid Account id
226 * @param string $component Name of the component that the componentid belongs to
227 * @param int $componentid An internal identifier that is used by the component
228 * @param int $userid Id of the user who is paying
229 * @param float $amount Amount of payment
230 * @param string $currency Currency of payment
231 * @param string $gateway The gateway that is used for the payment
234 public static function save_payment(int $accountid, string $component, int $componentid, int $userid, float $amount, string $currency,
235 string $gateway): int {
238 $record = new \stdClass();
239 $record->component = $component;
240 $record->componentid = $componentid;
241 $record->userid = $userid;
242 $record->amount = $amount;
243 $record->currency = $currency;
244 $record->gateway = $gateway;
245 $record->accountid = $accountid;
246 $record->timecreated = $record->timemodified = time();
248 $id = $DB->insert_record('payments', $record);
254 * This functions adds the settings that are common for all payment gateways.
256 * @param \admin_settingpage $settings The settings object
257 * @param string $gateway The gateway name prefic with pg_
259 public static function add_common_gateway_settings(\admin_settingpage $settings, string $gateway): void {
260 $settings->add(new \admin_setting_configtext($gateway . '/surcharge', get_string('surcharge', 'core_payment'),
261 get_string('surcharge_desc', 'core_payment'), 0, PARAM_INT));
266 * Save a new or edited payment account (used in management interface)
268 * @param \stdClass $data
270 public static function save_payment_account(\stdClass $data) {
272 if (empty($data->id)) {
273 $account = new account(0, $data);
275 $account = new account($data->id);
276 $account->from_record($data);
280 // TODO trigger event.
284 * Delete a payment account (used in management interface)
286 * @param account $account
288 public static function delete_payment_account(account $account) {
289 foreach ($account->get_gateways(false) as $gateway) {
290 if ($gateway->get('id')) {
295 // TODO trigger event.
299 * Save a payment gateway linked to an existing account (used in management interface)
301 * @param \stdClass $data
303 public static function save_payment_gateway(\stdClass $data) {
304 if (empty($data->id)) {
305 $gateway = new account_gateway(0, $data);
307 $gateway = new account_gateway($data->id);
308 unset($data->accountid, $data->gateway, $data->id);
309 $gateway->from_record($data);
313 // TODO trigger event.
317 * Returns the list of payment accounts in the given context (used in management interface)
319 * @param \context $context
322 public static function get_payment_accounts_to_manage(\context $context): array {
323 return account::get_records(['contextid' => $context->id]);
327 * Get list of accounts available in the given context
329 * @param \context $context
332 public static function get_payment_accounts_menu(\context $context): array {
334 [$sql, $params] = $DB->get_in_or_equal($context->get_parent_context_ids(true));
335 $accounts = array_filter(account::get_records_select('contextid '.$sql, $params), function($account) {
336 return $account->is_available();
338 return array_map(function($account) {
339 return $account->get_formatted_name();