Merge branch 'MDL-74332-311' of https://github.com/sharidas/moodle into MOODLE_311_STABLE
[moodle.git] / payment / classes / helper.php
blobe10721ceb7dfa724f7409391cb67a07436efc1a1
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.
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/>.
17 /**
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 /**
32 * Helper class for the payment subsystem.
34 * @copyright 2019 Shamim Rezaie <shamim@moodle.com>
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37 class helper {
39 /**
40 * Returns an accumulated list of supported currencies by all payment gateways.
42 * @return string[] An array of the currency codes in the three-character ISO-4217 format
44 public static function get_supported_currencies(): array {
45 $currencies = [];
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';
52 $currencies = array_merge($currencies, component_class_callback($classname, 'get_supported_currencies', [], []));
55 $currencies = array_unique($currencies);
57 return $currencies;
60 /**
61 * Returns the list of gateways that can process payments in the given currency.
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[]
68 public static function get_available_gateways(string $component, string $paymentarea, int $itemid): array {
69 $gateways = [];
71 $payable = static::get_payable($component, $paymentarea, $itemid);
72 $account = new account($payable->get_account_id());
74 if (!$account->get('id') || !$account->get('enabled')) {
75 return $gateways;
78 $currency = $payable->get_currency();
79 foreach ($account->get_gateways() as $plugin => $gateway) {
80 if (!$gateway->get('enabled')) {
81 continue;
83 /** @var gateway $classname */
84 $classname = '\paygw_' . $plugin . '\gateway';
86 $currencies = component_class_callback($classname, 'get_supported_currencies', [], []);
87 if (in_array($currency, $currencies)) {
88 $gateways[] = $plugin;
92 return $gateways;
95 /**
96 * Rounds the cost based on the currency fractional digits, can also apply surcharge
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
103 public static function get_rounded_cost(float $amount, string $currency, float $surcharge = 0): float {
104 $amount = $amount * (100 + $surcharge) / 100;
106 $locale = get_string('localecldr', 'langconfig');
107 $fmt = \NumberFormatter::create($locale, \NumberFormatter::CURRENCY);
108 $localisedcost = numfmt_format_currency($fmt, $amount, $currency);
110 return numfmt_parse_currency($fmt, $localisedcost, $currency);
114 * Returns human-readable amount with correct number of fractional digits and currency indicator, can also apply surcharge
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
121 public static function get_cost_as_string(float $amount, string $currency, float $surcharge = 0): string {
122 $amount = $amount * (100 + $surcharge) / 100;
124 $locale = get_string('localecldr', 'langconfig');
125 $fmt = \NumberFormatter::create($locale, \NumberFormatter::CURRENCY);
126 $localisedcost = numfmt_format_currency($fmt, $amount, $currency);
128 return $localisedcost;
132 * Returns the percentage of surcharge that is applied when using a gateway
134 * @param string $gateway Name of the gateway
135 * @return float
137 public static function get_gateway_surcharge(string $gateway): float {
138 return (float)get_config('paygw_' . $gateway, 'surcharge');
142 * Returns the attributes to place on a pay button.
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
150 public static function gateways_modal_link_params(string $component, string $paymentarea, int $itemid,
151 string $description): array {
153 $payable = static::get_payable($component, $paymentarea, $itemid);
154 $successurl = static::get_success_url($component, $paymentarea, $itemid);
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),
170 * Get the name of the service provider class
172 * @param string $component The component
173 * @return string
174 * @throws \coding_exception
176 private static function get_service_provider_classname(string $component) {
177 $providerclass = "$component\\payment\\service_provider";
179 if (class_exists($providerclass)) {
180 $rc = new \ReflectionClass($providerclass);
181 if ($rc->implementsInterface(local\callback\service_provider::class)) {
182 return $providerclass;
186 throw new \coding_exception("$component does not have an eligible implementation of payment service_provider.");
190 * Asks the payable from the related component.
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
197 public static function get_payable(string $component, string $paymentarea, int $itemid): local\entities\payable {
198 $providerclass = static::get_service_provider_classname($component);
200 return component_class_callback($providerclass, 'get_payable', [$paymentarea, $itemid]);
204 * Fetches the URL of the page the user should be redirected to from the related component
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
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]);
217 * Returns the gateway configuration for given component and gateway
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
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;
234 if (!$gateway) {
235 throw new \moodle_exception('gatewaynotfound', 'payment');
237 return $gateway->get_configuration();
241 * Delivers what the user paid for.
243 * @uses \core_payment\local\callback\service_provider::deliver_order()
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
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]);
256 return $result;
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.
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
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;
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();
288 $id = $DB->insert_record('payments', $record);
290 return $id;
294 * This functions adds the settings that are common for all payment gateways.
296 * @param \admin_settingpage $settings The settings object
297 * @param string $gateway The gateway name prefixed with paygw_
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));
306 * Save a new or edited payment account (used in management interface)
308 * @param \stdClass $data
309 * @return account
311 public static function save_payment_account(\stdClass $data): account {
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();
324 return $account;
328 * Delete a payment account (used in management interface)
330 * @param account $account
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;
341 foreach ($account->get_gateways(false) as $gateway) {
342 if ($gateway->get('id')) {
343 $gateway->delete();
346 $event = account_deleted::create_from_account($account);
347 $account->delete();
348 $event->trigger();
352 * Restore archived payment account (used in management interface)
354 * @param account $account
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();
363 * Save a payment gateway linked to an existing account (used in management interface)
365 * @param \stdClass $data
366 * @return account_gateway
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);
376 } else {
377 $gateway = new account_gateway($data->id);
379 unset($data->accountid, $data->gateway, $data->id);
380 $gateway->from_record($data);
382 $account = $gateway->get_account();
383 $gateway->save();
384 account_updated::create_from_account($account)->trigger();
385 return $gateway;
389 * Returns the list of payment accounts in the given context (used in management interface)
391 * @param \context $context
392 * @return account[]
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;
401 * Get list of accounts available in the given context
403 * @param \context $context
404 * @return array
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');
412 return array_map(function($account) {
413 return $account->get_formatted_name();
414 }, $accounts);