From df5c305011cc0fc1f300bfacdac2caf1179f8250 Mon Sep 17 00:00:00 2001
From: Jules Nsenda
Date: Wed, 18 Nov 2026 20:41:52 +0200
Subject: [PATCH 01/19] fix: confirm charge.success with Paystack before
completing a payment
The webhook payload's amount and currency are no longer trusted on their own;
the transaction is fetched from transaction/verify and its status, id, amount
and currency must match before the entry is completed.
Co-Authored-By: Claude Opus 5.5
---
class-gf-paystack.php | 28 ++++++++++++++++++++++++++--
tests/test-webhook.php | 33 +++++++++++++++++++++++++++------
2 files changed, 53 insertions(+), 8 deletions(-)
diff --git a/class-gf-paystack.php b/class-gf-paystack.php
index 9a74d63..74bb5f6 100644
--- a/class-gf-paystack.php
+++ b/class-gf-paystack.php
@@ -1304,7 +1304,31 @@ public function callback()
if ($feed['meta']['transactionType'] == 'subscription') {
gform_update_meta($entry_id, 'paystack_tx_auth_code', rgars($event, 'data/authorization/authorization_code'));
} else {
- if (!self::charge_matches_stored(rgars($event, 'data/amount'), rgars($event, 'data/currency'), gform_get_meta($entry_id, 'paystack_tx_amount'), gform_get_meta($entry_id, 'paystack_tx_currency'))) {
+ try {
+ $response = $this->paystack_api->verify_transaction($reference);
+ } catch (\Exception $e) {
+ $this->log_error(__METHOD__ . '(): Transaction could not be verified. Reason: ' . $e->getMessage());
+
+ return false;
+ }
+
+ $charge = rgar($response, 'data');
+
+ if (!is_array($charge) || rgar($charge, 'status') !== 'success') {
+ $this->log_error(__METHOD__ . '(): Transaction verification failed. Aborting.');
+
+ return false;
+ }
+
+ $verified_id = rgar($charge, 'id');
+
+ if ($verified_id && (string) $verified_id !== (string) rgars($event, 'data/id')) {
+ $this->log_error(__METHOD__ . '(): Verified transaction does not match the webhook event. Aborting.');
+
+ return false;
+ }
+
+ if (!self::charge_matches_stored(rgar($charge, 'amount'), rgar($charge, 'currency'), gform_get_meta($entry_id, 'paystack_tx_amount'), gform_get_meta($entry_id, 'paystack_tx_currency'))) {
$this->log_error(__METHOD__ . '(): Webhook could not be matched to entry. Aborting.');
return false;
@@ -1313,7 +1337,7 @@ public function callback()
$action['id'] = rgars($event, 'data/id') . '_' . $type;
$action['entry_id'] = $entry_id;
$action['transaction_id'] = rgars($event, 'data/id');
- $action['amount'] = $this->get_amount_import(rgars($event, 'data/amount'), rgars($event, 'data/currency'));
+ $action['amount'] = $this->get_amount_import(rgar($charge, 'amount'), rgar($charge, 'currency'));
$action['type'] = 'complete_payment';
$action['ready_to_fulfill'] = !$entry['is_fulfilled'] ? true : false;
$action['payment_date'] = rgars($event, 'data/paidAt');
diff --git a/tests/test-webhook.php b/tests/test-webhook.php
index 13df754..b75a53f 100644
--- a/tests/test-webhook.php
+++ b/tests/test-webhook.php
@@ -44,8 +44,15 @@
$stored = array('paystack_mode' => 'live', 'paystack_tx_amount' => '5000', 'paystack_tx_currency' => 'NGN');
-$result = gf_paystack_callback_run(gf_paystack_charge_event(), 'live', $stored);
-gf_paystack_test_check(is_array($result) && $result['type'] === 'complete_payment' && $result['entry_id'] === '7', 'callback case 1');
+$charge_api = function ($overrides = array()) {
+ $api = new GFPaystackRecordingApi();
+ $api->response = array('status' => true, 'message' => 'ok', 'data' => array_merge(array('id' => 99, 'status' => 'success', 'amount' => 5000, 'currency' => 'NGN'), $overrides));
+ return $api;
+};
+
+$verified_api = $charge_api();
+$result = gf_paystack_callback_run(gf_paystack_charge_event(), 'live', $stored, null, null, $verified_api);
+gf_paystack_test_check(is_array($result) && $result['type'] === 'complete_payment' && $result['entry_id'] === '7' && $result['amount'] == 50 && $verified_api->calls === array('transaction/verify/gf-7-abc'), 'callback case 1');
$result = gf_paystack_callback_run(gf_paystack_charge_event(array('metadata' => array('entry_id' => '8'))), 'live', $stored);
gf_paystack_test_check($result === false, 'callback case 2');
@@ -53,21 +60,35 @@
$result = gf_paystack_callback_run(gf_paystack_charge_event(), 'test', $stored);
gf_paystack_test_check($result === false, 'callback case 3');
-$result = gf_paystack_callback_run(gf_paystack_charge_event(), 'live', array('paystack_tx_amount' => '5000'));
+$result = gf_paystack_callback_run(gf_paystack_charge_event(), 'live', array('paystack_tx_amount' => '5000'), null, null, $charge_api());
gf_paystack_test_check(is_array($result) && $result['type'] === 'complete_payment', 'callback case 4');
$result = gf_paystack_callback_run(gf_paystack_charge_event(), 'test', array('paystack_tx_amount' => '5000'));
gf_paystack_test_check($result === false, 'callback case 5');
-$result = gf_paystack_callback_run(gf_paystack_charge_event(array('amount' => 100)), 'live', $stored);
+$result = gf_paystack_callback_run(gf_paystack_charge_event(), 'live', $stored, null, null, $charge_api(array('amount' => 100)));
gf_paystack_test_check($result === false, 'callback case 6');
-$result = gf_paystack_callback_run(gf_paystack_charge_event(array('currency' => 'USD')), 'live', $stored);
+$result = gf_paystack_callback_run(gf_paystack_charge_event(), 'live', $stored, null, null, $charge_api(array('currency' => 'USD')));
gf_paystack_test_check($result === false, 'callback case 7');
-$result = gf_paystack_callback_run(gf_paystack_charge_event(), 'live', array());
+$result = gf_paystack_callback_run(gf_paystack_charge_event(), 'live', array(), null, null, $charge_api());
gf_paystack_test_check(is_array($result) && $result['type'] === 'complete_payment', 'callback case 8');
+$result = gf_paystack_callback_run(gf_paystack_charge_event(array('amount' => 100, 'currency' => 'USD')), 'live', $stored, null, null, $charge_api());
+gf_paystack_test_check(is_array($result) && $result['type'] === 'complete_payment' && $result['amount'] == 50, 'callback case 29');
+
+$result = gf_paystack_callback_run(gf_paystack_charge_event(), 'live', $stored, null, null, $charge_api(array('status' => 'failed')));
+gf_paystack_test_check($result === false, 'callback case 30');
+
+$result = gf_paystack_callback_run(gf_paystack_charge_event(), 'live', $stored, null, null, $charge_api(array('id' => 100)));
+gf_paystack_test_check($result === false, 'callback case 31');
+
+$throwing_charge_api = $charge_api();
+$throwing_charge_api->throw = true;
+$result = gf_paystack_callback_run(gf_paystack_charge_event(), 'live', $stored, null, null, $throwing_charge_api);
+gf_paystack_test_check($result === false, 'callback case 32');
+
$result = gf_paystack_callback_run(gf_paystack_charge_event(array('reference' => 'gf-7-unknown')), 'live', $stored);
gf_paystack_test_check(is_wp_error($result) && $result->code === 'entry_not_found', 'callback case 9');
From f398fd44b5020a8aeed2c22642d43f92774ffc22 Mon Sep 17 00:00:00 2001
From: Jules Nsenda
Date: Wed, 18 Nov 2026 20:42:35 +0200
Subject: [PATCH 02/19] feat: add key shape, save rules and log redaction for
restricted keys
GF_Paystack_Keys classifies sk_/rk_ keys, decides what a settings save needs
(probe, wrong field, bad shape, missing or duplicated signing secret), exposes
the gform_paystack_restricted_keys_enabled switch and redacts keys and
whsec_ secrets from log text.
Co-Authored-By: Claude Opus 5.5
---
class-gf-paystack-api.php | 2 +
includes/class-gf-paystack-keys.php | 105 ++++++++++++++++++++++++++++
tests/test-keys.php | 59 ++++++++++++++++
3 files changed, 166 insertions(+)
create mode 100644 includes/class-gf-paystack-keys.php
create mode 100644 tests/test-keys.php
diff --git a/class-gf-paystack-api.php b/class-gf-paystack-api.php
index 42d1f1b..99444d6 100644
--- a/class-gf-paystack-api.php
+++ b/class-gf-paystack-api.php
@@ -3,6 +3,8 @@
die('You are not allowed to call this page directly.');
}
+require_once __DIR__ . '/includes/class-gf-paystack-keys.php';
+
class GFPaystackApi
{
public $plugin_name;
diff --git a/includes/class-gf-paystack-keys.php b/includes/class-gf-paystack-keys.php
new file mode 100644
index 0000000..a7a413f
--- /dev/null
+++ b/includes/class-gf-paystack-keys.php
@@ -0,0 +1,105 @@
+]+/';
+
+ public static function type($key)
+ {
+ if (is_string($key) && preg_match('/^(sk|rk)_(?:live|test)_/', $key, $m)) {
+ return $m[1];
+ }
+
+ return null;
+ }
+
+ public static function mode($key)
+ {
+ if (is_string($key) && preg_match('/^(?:sk|rk)_(live|test)_/', $key, $m)) {
+ return $m[1];
+ }
+
+ return null;
+ }
+
+ public static function is_whsec_shaped($value)
+ {
+ return is_string($value) && preg_match(self::WHSEC_SHAPE, $value) === 1;
+ }
+
+ public static function restricted_keys_enabled()
+ {
+ return (bool) apply_filters('gform_paystack_restricted_keys_enabled', true);
+ }
+
+ public static function resolve_save($mode, $posted_key, $stored_key, $posted_whsec, $other_mode_whsec, $rk_enabled)
+ {
+ $key = trim((string) $posted_key);
+ $stored = trim((string) $stored_key);
+ $whsec = trim((string) $posted_whsec);
+ $other_whsec = trim((string) $other_mode_whsec);
+
+ $probe = false;
+ if ($key !== '' && $key !== $stored) {
+ $key_mode = self::mode($key);
+ if ($key_mode !== null && $key_mode !== $mode) {
+ return self::result(false, 'wrong_field');
+ }
+
+ $type = self::type($key);
+ $shaped = $type === 'sk' ? preg_match(self::SK_SHAPE, $key) : ($type === 'rk' ? preg_match(self::RK_SHAPE, $key) : 0);
+ if (!$shaped) {
+ return self::result(false, 'invalid_format');
+ }
+
+ if ($type === 'rk') {
+ if (!$rk_enabled) {
+ return self::result(false, 'rk_disabled');
+ }
+ $probe = true;
+ }
+ }
+
+ // A blank key is a cleared field, so it never needs a signing secret.
+ if ($whsec !== '' && !self::is_whsec_shaped($whsec)) {
+ return self::result($probe, 'whsec_format');
+ }
+ if ($key !== '' && self::type($key) === 'rk' && $whsec === '') {
+ return self::result($probe, 'whsec_required');
+ }
+ if ($whsec !== '' && $whsec === $other_whsec) {
+ return self::result($probe, 'whsec_same');
+ }
+
+ return self::result($probe, null);
+ }
+
+ public static function redact($string)
+ {
+ if (!is_string($string)) {
+ return $string;
+ }
+
+ return preg_replace_callback(self::REDACT_PATTERN, array(__CLASS__, 'redact_match'), $string);
+ }
+
+ private static function redact_match($match)
+ {
+ preg_match('/^(?:(?:sk|rk|pk)_(?:live|test)_|whsec_)/', $match[0], $prefix);
+
+ return $prefix[0] . '[redacted]';
+ }
+
+ private static function result($probe, $error)
+ {
+ return array('probe' => $error === null ? $probe : false, 'error' => $error);
+ }
+ }
+}
diff --git a/tests/test-keys.php b/tests/test-keys.php
new file mode 100644
index 0000000..6fe1848
--- /dev/null
+++ b/tests/test-keys.php
@@ -0,0 +1,59 @@
+ array(array('live', '', $sk_live, '', '', true), false, null),
+ 'blank key, stored rk, no whsec' => array(array('live', '', $rk_live, '', '', true), false, null),
+ 'unchanged odd shape' => array(array('live', 'weird-key', 'weird-key', '', '', true), false, null),
+ 'unchanged wrong field' => array(array('live', $sk_test, $sk_test, '', '', true), false, null),
+ 'unchanged with whitespace' => array(array('live', " $sk_live ", $sk_live, '', '', true), false, null),
+ 'new sk' => array(array('live', $sk_live, '', '', '', true), false, null),
+ 'new sk other mode' => array(array('live', $sk_test, '', '', '', true), false, 'wrong_field'),
+ 'new rk other mode' => array(array('test', $rk_live, '', $whsec_a, '', true), false, 'wrong_field'),
+ 'new key bad shape' => array(array('live', 'sk_live_', '', '', '', true), false, 'invalid_format'),
+ 'new key unknown prefix' => array(array('live', 'pk_live_abc', '', '', '', true), false, 'invalid_format'),
+ 'new rk too short' => array(array('live', 'rk_live_short', '', $whsec_a, '', true), false, 'invalid_format'),
+ 'new rk with whsec' => array(array('live', $rk_live, '', $whsec_a, $whsec_b, true), true, null),
+ 'new rk gate off' => array(array('live', $rk_live, '', $whsec_a, '', false), false, 'rk_disabled'),
+ 'kept rk gate off' => array(array('live', $rk_live, $rk_live, $whsec_a, '', false), false, null),
+ 'new rk without whsec' => array(array('live', $rk_live, '', '', '', true), false, 'whsec_required'),
+ 'kept rk without whsec' => array(array('live', $rk_live, $rk_live, '', '', true), false, 'whsec_required'),
+ 'new sk without whsec' => array(array('live', $sk_live, '', '', '', true), false, null),
+ 'sk with whsec' => array(array('live', $sk_live, $sk_live, $whsec_a, '', true), false, null),
+ 'whsec same as other mode' => array(array('live', $sk_live, $sk_live, $whsec_a, $whsec_a, true), false, 'whsec_same'),
+ 'whsec bad shape' => array(array('live', $sk_live, $sk_live, 'whsec_x', '', true), false, 'whsec_format'),
+ 'whsec bad shape with blank key' => array(array('live', '', '', 'nope', '', true), false, 'whsec_format'),
+ 'key error before whsec error' => array(array('live', $sk_test, '', 'nope', '', true), false, 'wrong_field'),
+);
+foreach ($keys_cases as $label => $case) {
+ $result = call_user_func_array(array('GF_Paystack_Keys', 'resolve_save'), $case[0]);
+ gf_paystack_test_check($result === array('probe' => $case[1], 'error' => $case[2]), 'keys resolve_save ' . $label);
+}
+
+$keys_redact_cases = array(
+ 'punctuation rk' => array('key rk_live_ab-c.d~e!f_g tail', 'key rk_live_[redacted] tail'),
+ 'base64 whsec' => array('whsec_ab+/cd==ef rest', 'whsec_[redacted] rest'),
+ 'query string' => array('x=1&secret=sk_live_abc&y=2', 'x=1&secret=sk_live_[redacted]&y=2'),
+ 'json escaped' => array('{"key":"rk_live_abc123"}', '{"key":"rk_live_[redacted]"}'),
+ 'url encoded' => array('secret%3Dsk_live_abc%26y', 'secret%3Dsk_live_[redacted]'),
+ 'pk' => array('pk_test_abc123', 'pk_test_[redacted]'),
+ 'no secrets' => array('Payment verified for ref gf-9 task_live_x', 'Payment verified for ref gf-9 task_live_x'),
+);
+foreach ($keys_redact_cases as $label => $case) {
+ gf_paystack_test_check(GF_Paystack_Keys::redact($case[0]) === $case[1], 'keys redact ' . $label);
+}
+gf_paystack_test_check(GF_Paystack_Keys::redact(array('sk_live_abc')) === array('sk_live_abc') && GF_Paystack_Keys::redact(null) === null, 'keys redact non-strings');
From 6e3018a8a4e3537f746d15b86ea3ebec224b0a2c Mon Sep 17 00:00:00 2001
From: Jules Nsenda
Date: Wed, 18 Nov 2026 20:44:50 +0200
Subject: [PATCH 03/19] feat: check a restricted key's permissions with
Paystack before saving it
GF_Paystack_Restricted_Key probes the key in sequence (ported from the
BigCommerce validator, without the ident call): it must hold Transactions
read and write and none of the money-moving scopes. Anything other than an
exact scope refusal fails closed. probe_plans() checks Plans: write for
subscription feeds.
Co-Authored-By: Claude Opus 5.5
---
includes/class-gf-paystack-restricted-key.php | 242 ++++++++++++++++++
tests/test-restricted-key.php | 171 +++++++++++++
2 files changed, 413 insertions(+)
create mode 100644 includes/class-gf-paystack-restricted-key.php
create mode 100644 tests/test-restricted-key.php
diff --git a/includes/class-gf-paystack-restricted-key.php b/includes/class-gf-paystack-restricted-key.php
new file mode 100644
index 0000000..738131e
--- /dev/null
+++ b/includes/class-gf-paystack-restricted-key.php
@@ -0,0 +1,242 @@
+ 'transactions:read', 'type' => 'required', 'method' => 'GET', 'path' => 'transaction?perPage=1', 'body' => null, 'present' => '2xx'),
+ array('scope' => 'transactions:write', 'type' => 'required', 'method' => 'POST', 'path' => 'transaction/check_authorization', 'body' => array(), 'present' => '404_write'),
+ array('scope' => 'disputes_refunds', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'refund?perPage=1', 'body' => null, 'present' => '2xx_or_400'),
+ array('scope' => 'bulk_charges', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'bulkcharge', 'body' => null, 'present' => '2xx_or_400'),
+ array('scope' => 'direct_debit', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'directdebit/account', 'body' => null, 'present' => '2xx_or_400'),
+ array('scope' => 'preauthorizations', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'preauthorization', 'body' => null, 'present' => '2xx_or_400'),
+ array('scope' => 'settlements', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'settlement?perPage=1', 'body' => null, 'present' => '2xx_or_400'),
+ array('scope' => 'subaccounts', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'subaccount', 'body' => null, 'present' => '2xx_or_400'),
+ array('scope' => 'transfers', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'transfer/config', 'body' => null, 'present' => '2xx_or_400'),
+ array('scope' => 'virtual_accounts', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'pay-with-transfer/custom-accounts/status', 'body' => null, 'present' => '2xx_or_400'),
+ array('scope' => 'webhooks', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'integration/webhooks/events', 'body' => null, 'present' => '2xx_or_400'),
+ array('scope' => 'connect', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'connect/platforms', 'body' => null, 'present' => '2xx_or_400'),
+ array('scope' => 'payouts', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'settlement/instant/profile', 'body' => null, 'present' => '2xx_or_400'),
+ );
+
+ // Overridable so tests can exhaust it without sleeping.
+ protected static $budget_seconds = 15.0;
+
+ public static function validate($key, $request = null)
+ {
+ try {
+ if (!is_callable($request)) {
+ $request = array(__CLASS__, 'default_request');
+ }
+
+ $start = microtime(true);
+ $results = array();
+ $baseline = null;
+
+ foreach (self::PROBES as $index => $probe) {
+ if (microtime(true) - $start >= static::$budget_seconds) {
+ $results[] = array('probe' => $probe, 'outcome' => 'indeterminate', 'status' => 0, 'ran' => false);
+ break;
+ }
+
+ $response = self::send($request, $key, $probe['method'], $probe['path'], $probe['body']);
+ $outcome = self::classify($probe, $response, $baseline);
+ $results[] = array('probe' => $probe, 'outcome' => $outcome, 'status' => $response['status'], 'ran' => true);
+
+ if ($index === 0) {
+ $baseline = $outcome;
+ }
+ if ($outcome === 'invalid' || $outcome === 'indeterminate') {
+ break;
+ }
+ }
+
+ return self::decide($results);
+ } catch (\Throwable $e) {
+ return self::verdict('unverifiable', array(), array(), 'transient');
+ }
+ }
+
+ public static function probe_plans($key, $request = null)
+ {
+ try {
+ if (!is_callable($request)) {
+ $request = array(__CLASS__, 'default_request');
+ }
+
+ $response = self::send($request, $key, 'POST', 'plan', array());
+ if ($response['status'] === 400) {
+ return 'ok';
+ }
+ if ($response['status'] === 403) {
+ if ($response['message'] === self::SCOPE_DENIED_MESSAGE) {
+ return 'plans_missing';
+ }
+ if ($response['message'] === self::MOR_MESSAGE) {
+ return 'plans_mor';
+ }
+ }
+
+ return 'unverifiable';
+ } catch (\Throwable $e) {
+ return 'unverifiable';
+ }
+ }
+
+ public static function default_request($method, $url, $headers, $body)
+ {
+ $res = wp_remote_request($url, array(
+ 'method' => $method,
+ 'timeout' => self::REQUEST_TIMEOUT,
+ 'redirection' => 0,
+ 'headers' => $headers,
+ 'body' => $body === null ? null : json_encode($body, JSON_FORCE_OBJECT),
+ ));
+
+ if (is_wp_error($res) || !is_array($res)) {
+ return array('status' => 0, 'body' => null);
+ }
+
+ $status = isset($res['response']['code']) ? (int) $res['response']['code'] : 0;
+ $raw = isset($res['body']) ? $res['body'] : null;
+
+ return array('status' => $status, 'body' => $raw);
+ }
+
+ private static function send($request, $key, $method, $path, $body)
+ {
+ // Authorization is forced last so a filter can't swap or drop the key under test.
+ $headers = apply_filters('gf_paystack_request_headers', array('Content-Type' => 'application/json'));
+ if (!is_array($headers)) {
+ $headers = array();
+ }
+ $headers['Authorization'] = 'Bearer ' . $key;
+
+ try {
+ $response = call_user_func($request, $method, self::BASE_URL . $path, $headers, $body);
+ } catch (\Throwable $e) {
+ $response = null;
+ }
+
+ if (!is_array($response) || !isset($response['status'])) {
+ return array('status' => 0, 'message' => null);
+ }
+
+ return array('status' => (int) $response['status'], 'message' => self::message_of(isset($response['body']) ? $response['body'] : null));
+ }
+
+ private static function message_of($body)
+ {
+ if (is_string($body)) {
+ $decoded = json_decode($body, true);
+ $body = is_array($decoded) ? $decoded : $body;
+ }
+ if (is_array($body)) {
+ return isset($body['message']) && is_string($body['message']) ? $body['message'] : null;
+ }
+
+ return is_string($body) ? $body : null;
+ }
+
+ private static function is_present($probe, $response)
+ {
+ $status = $response['status'];
+ if ($probe['present'] === '404_write') {
+ return $status === 404 && $response['message'] === self::WRITE_PRESENT_MESSAGE;
+ }
+ if ($status >= 200 && $status <= 299) {
+ return true;
+ }
+
+ return $probe['present'] === '2xx_or_400' && $status === 400;
+ }
+
+ // Any 403 that isn't the exact scope message may be another gate (IP, feature), so it fails closed.
+ private static function classify($probe, $response, $baseline)
+ {
+ if ($response['status'] === 401) {
+ if ($baseline === null) {
+ return 'invalid';
+ }
+
+ return $baseline === 'present' && $probe['type'] === 'sensitive' ? 'present' : 'indeterminate';
+ }
+ if ($response['status'] === 403 && $response['message'] === self::SCOPE_DENIED_MESSAGE) {
+ return 'absent';
+ }
+
+ return self::is_present($probe, $response) ? 'present' : 'indeterminate';
+ }
+
+ private static function decide($results)
+ {
+ if ($results[0]['outcome'] === 'invalid') {
+ return self::verdict('invalid_key', array(), array(), null, $results);
+ }
+
+ $missing = array();
+ $sensitive = array();
+ $indeterminate = array();
+ foreach ($results as $r) {
+ $type = $r['probe']['type'];
+ if ($type === 'required' && $r['outcome'] === 'absent') {
+ $missing[] = $r['probe']['scope'];
+ } elseif ($type === 'sensitive' && $r['outcome'] === 'present') {
+ $sensitive[] = $r['probe']['scope'];
+ } elseif ($r['outcome'] === 'indeterminate') {
+ $indeterminate[] = $r;
+ }
+ }
+
+ if ($missing) {
+ return self::verdict('missing_scope', $missing, $sensitive, null, $results);
+ }
+ if ($sensitive) {
+ return self::verdict('sensitive_scope', array(), $sensitive, null, $results);
+ }
+ if ($indeterminate) {
+ $reason = 'transient';
+ foreach ($indeterminate as $r) {
+ if ($r['status'] === 403) {
+ $reason = 'blocked';
+ }
+ }
+
+ return self::verdict('unverifiable', array(), array(), $reason, $results);
+ }
+
+ return self::verdict('ok', array(), array(), null, $results);
+ }
+
+ private static function verdict($code, $scopes, $sensitive_scopes, $reason, $results = array())
+ {
+ $parts = array();
+ foreach ($results as $r) {
+ if ($r['ran']) {
+ $parts[] = $r['probe']['scope'] . ':' . $r['status'];
+ }
+ }
+
+ return array(
+ 'code' => $code,
+ 'scopes' => $scopes,
+ 'sensitive_scopes' => $sensitive_scopes,
+ 'reason' => $reason,
+ 'probes' => $parts ? implode(',', $parts) : '-',
+ );
+ }
+ }
+}
diff --git a/tests/test-restricted-key.php b/tests/test-restricted-key.php
new file mode 100644
index 0000000..7c25c09
--- /dev/null
+++ b/tests/test-restricted-key.php
@@ -0,0 +1,171 @@
+ status | array(status, message); unlisted scopes get $default.
+$rk_make = function ($map, $default = array(403, 'This restricted key is not permitted to perform this action'), &$log = null) {
+ $log = array();
+
+ return function ($method, $url, $headers, $body) use ($map, $default, &$log) {
+ $path = substr($url, strlen('https://api.paystack.co/'));
+ $scope = null;
+ foreach (GF_Paystack_Restricted_Key::PROBES as $p) {
+ if ($p['path'] === $path && $p['method'] === $method) {
+ $scope = $p['scope'];
+ }
+ }
+ $log[] = $scope;
+ $r = array_key_exists($scope, $map) ? $map[$scope] : $default;
+ if ($r instanceof Exception) {
+ throw $r;
+ }
+ $r = (array) $r;
+
+ return array('status' => $r[0], 'body' => isset($r[1]) ? array('status' => false, 'message' => $r[1]) : null);
+ };
+};
+
+$rk_ok_map = array('transactions:read' => 200, 'transactions:write' => array(404, $write_msg));
+$rk_expected_scopes = array('transactions:read', 'transactions:write', 'disputes_refunds', 'bulk_charges', 'direct_debit', 'preauthorizations', 'settlements', 'subaccounts', 'transfers', 'virtual_accounts', 'webhooks', 'connect', 'payouts');
+
+$scope_list = array();
+foreach (GF_Paystack_Restricted_Key::PROBES as $p) {
+ $scope_list[] = $p['scope'];
+}
+gf_paystack_test_check($scope_list === $rk_expected_scopes, 'rk probe table scope list and order pinned');
+gf_paystack_test_check(GF_Paystack_Restricted_Key::PROBES[1]['path'] === 'transaction/check_authorization' && GF_Paystack_Restricted_Key::PROBES[1]['method'] === 'POST', 'rk write probe route pinned');
+
+$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make($rk_ok_map, array(403, $scope_msg), $log));
+gf_paystack_test_check($v['code'] === 'ok' && $v['reason'] === null && $v['scopes'] === array() && $v['sensitive_scopes'] === array() && count($log) === 13, 'rk ok when baseline and write present and sensitive absent');
+gf_paystack_test_check(strpos($v['probes'], 'transactions:read:200,transactions:write:404,disputes_refunds:403') === 0 && strpos($v['probes'], $rk_key) === false, 'rk probes string has scope:status and no key');
+
+$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make(array('transactions:read' => array(401, 'Invalid key')), array(401), $log));
+gf_paystack_test_check($v['code'] === 'invalid_key' && $log === array('transactions:read'), 'rk baseline 401 is invalid_key and stops');
+
+$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make(array(), array(403, $scope_msg), $log));
+gf_paystack_test_check($v['code'] === 'missing_scope' && $v['scopes'] === array('transactions:read', 'transactions:write') && count($log) === 13, 'rk missing read and write when all absent');
+
+$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make(array('transactions:write' => array(404, $write_msg)) + array('transactions:read' => array(403, $scope_msg)), array(403, $scope_msg), $log));
+gf_paystack_test_check($v['code'] === 'missing_scope' && $v['scopes'] === array('transactions:read'), 'rk missing read only');
+
+$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make(array('transactions:read' => 200, 'transactions:write' => 404), array(403, $scope_msg), $log));
+gf_paystack_test_check($v['code'] === 'unverifiable' && $v['reason'] === 'transient' && $log === array('transactions:read', 'transactions:write'), 'rk write 404 without exact message is unverifiable and stops');
+
+$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make(array('transactions:read' => 200, 'transactions:write' => array(404, 'Not found')), array(403, $scope_msg)));
+gf_paystack_test_check($v['code'] === 'unverifiable', 'rk write 404 with other message is unverifiable');
+
+foreach (array(200, 400) as $status) {
+ $v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make($rk_ok_map + array('settlements' => $status, 'payouts' => $status), array(403, $scope_msg), $log));
+ gf_paystack_test_check($v['code'] === 'sensitive_scope' && $v['sensitive_scopes'] === array('settlements', 'payouts') && $v['scopes'] === array(), "rk sensitive present on $status");
+}
+
+$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make($rk_ok_map + array('transfers' => 401), array(403, $scope_msg)));
+gf_paystack_test_check($v['code'] === 'sensitive_scope' && $v['sensitive_scopes'] === array('transfers'), 'rk 401 on sensitive after 2xx baseline is present');
+
+$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make(array('transactions:read' => array(403, $scope_msg), 'transactions:write' => array(404, $write_msg), 'disputes_refunds' => 401), array(403, $scope_msg), $log));
+gf_paystack_test_check($v['code'] === 'missing_scope' && end($log) === 'disputes_refunds', 'rk 401 on sensitive after absent baseline is not present and stops');
+
+$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make($rk_ok_map + array('direct_debit' => array(403, 'IP not allowed')), array(403, $scope_msg), $log));
+gf_paystack_test_check($v['code'] === 'unverifiable' && $v['reason'] === 'blocked' && end($log) === 'direct_debit', 'rk other 403 is blocked and probing stops');
+
+$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make($rk_ok_map + array('bulk_charges' => 429), array(403, $scope_msg), $log));
+gf_paystack_test_check($v['code'] === 'unverifiable' && $v['reason'] === 'transient' && end($log) === 'bulk_charges', 'rk 429 is transient');
+
+$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make($rk_ok_map + array('subaccounts' => 503), array(403, $scope_msg)));
+gf_paystack_test_check($v['code'] === 'unverifiable' && $v['reason'] === 'transient', 'rk 5xx is transient');
+
+$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make($rk_ok_map + array('connect' => 302), array(403, $scope_msg)));
+gf_paystack_test_check($v['code'] === 'unverifiable', 'rk 3xx is unverifiable');
+
+$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make($rk_ok_map + array('webhooks' => 0), array(403, $scope_msg), $log));
+gf_paystack_test_check($v['code'] === 'unverifiable' && $v['reason'] === 'transient' && end($log) === 'webhooks', 'rk status 0 on sensitive probe is unverifiable');
+
+$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make($rk_ok_map + array('settlements' => 200, 'transfers' => 429), array(403, $scope_msg)));
+gf_paystack_test_check($v['code'] === 'sensitive_scope', 'rk proven sensitive scope wins over a later indeterminate');
+
+$v = GF_Paystack_Restricted_Key::validate($rk_key, function () {
+ throw new RuntimeException('boom');
+});
+gf_paystack_test_check($v['code'] === 'unverifiable' && $v['reason'] === 'transient', 'rk throwing request is unverifiable transient');
+
+$v = GF_Paystack_Restricted_Key::validate($rk_key, function () {
+ return 'garbage';
+});
+gf_paystack_test_check($v['code'] === 'unverifiable', 'rk malformed response is unverifiable');
+
+$calls = 0;
+$v = GF_Paystack_Restricted_Key_Zero::validate($rk_key, function () use (&$calls) {
+ $calls++;
+
+ return array('status' => 200, 'body' => null);
+});
+gf_paystack_test_check($v['code'] === 'unverifiable' && $v['reason'] === 'transient' && $calls === 0 && $v['probes'] === '-', 'rk exhausted budget stops before any probe');
+
+$slow = $rk_make($rk_ok_map, array(403, $scope_msg), $log);
+$v = GF_Paystack_Restricted_Key_Spent::validate($rk_key, function ($m, $u, $h, $b) use ($slow) {
+ usleep(30000);
+
+ return $slow($m, $u, $h, $b);
+});
+gf_paystack_test_check($v['code'] === 'unverifiable' && $v['reason'] === 'transient' && strpos($v['probes'], 'transactions:read:200') === 0, 'rk budget exhausted mid-run is unverifiable transient');
+
+// probe_plans
+$plan = function ($status, $message = null) {
+ return function ($method, $url, $headers, $body) use ($status, $message) {
+ return array('status' => $status, 'body' => $message === null ? null : json_encode(array('message' => $message)));
+ };
+};
+gf_paystack_test_check(GF_Paystack_Restricted_Key::probe_plans($rk_key, $plan(400, 'Plan name is required')) === 'ok', 'rk plans 400 ok');
+gf_paystack_test_check(GF_Paystack_Restricted_Key::probe_plans($rk_key, $plan(403, $scope_msg)) === 'plans_missing', 'rk plans scope 403 missing');
+gf_paystack_test_check(GF_Paystack_Restricted_Key::probe_plans($rk_key, $plan(403, $mor_msg)) === 'plans_mor', 'rk plans MoR 403');
+gf_paystack_test_check(GF_Paystack_Restricted_Key::probe_plans($rk_key, $plan(403, 'other')) === 'unverifiable', 'rk plans other 403 unverifiable');
+gf_paystack_test_check(GF_Paystack_Restricted_Key::probe_plans($rk_key, $plan(500)) === 'unverifiable', 'rk plans 500 unverifiable');
+gf_paystack_test_check(GF_Paystack_Restricted_Key::probe_plans($rk_key, function () {
+ throw new Exception('x');
+}) === 'unverifiable', 'rk plans throwing request unverifiable');
+$seen = array();
+GF_Paystack_Restricted_Key::probe_plans($rk_key, function ($m, $u, $h, $b) use (&$seen) {
+ $seen = array($m, $u, $b);
+
+ return array('status' => 400, 'body' => null);
+});
+gf_paystack_test_check($seen === array('POST', 'https://api.paystack.co/plan', array()), 'rk plans probe is POST plan with empty body');
+
+// default transport
+$GLOBALS['gf_paystack_test_remote_calls'] = array();
+$GLOBALS['gf_paystack_test_remote_response'] = array('response' => array('code' => 403), 'body' => json_encode(array('message' => $scope_msg)));
+$v = GF_Paystack_Restricted_Key::validate($rk_key);
+$call = $GLOBALS['gf_paystack_test_remote_calls'][0];
+gf_paystack_test_check($call[0] === 'https://api.paystack.co/transaction?perPage=1' && $call[1]['method'] === 'GET' && $call[1]['timeout'] === 4 && $call[1]['redirection'] === 0 && $call[1]['body'] === null, 'rk default transport request args');
+gf_paystack_test_check($call[1]['headers']['Authorization'] === 'Bearer ' . $rk_key && $call[1]['headers']['Content-Type'] === 'application/json', 'rk default transport headers');
+gf_paystack_test_check($v['code'] === 'missing_scope' && count($GLOBALS['gf_paystack_test_remote_calls']) === 13, 'rk default transport parses json message');
+
+$GLOBALS['gf_paystack_test_remote_calls'] = array();
+$GLOBALS['gf_paystack_test_remote_response'] = array('response' => array('code' => 200), 'body' => '{}');
+GF_Paystack_Restricted_Key::validate($rk_key);
+$write_call = $GLOBALS['gf_paystack_test_remote_calls'][1];
+gf_paystack_test_check($write_call[1]['method'] === 'POST' && $write_call[1]['body'] === '{}', 'rk default transport encodes empty write body');
+
+$GLOBALS['gf_paystack_test_remote_calls'] = array();
+$GLOBALS['gf_paystack_test_remote_response'] = new WP_Error('http', 'down');
+$v = GF_Paystack_Restricted_Key::validate($rk_key);
+gf_paystack_test_check($v['code'] === 'unverifiable' && $v['reason'] === 'transient' && count($GLOBALS['gf_paystack_test_remote_calls']) === 1 && strpos($v['probes'], $rk_key) === false, 'rk wp_error maps to status 0');
From b95f212eaf5e62ac7c7ca0a747ad3faaef618954 Mon Sep 17 00:00:00 2001
From: Jules Nsenda
Date: Wed, 18 Nov 2026 20:45:12 +0200
Subject: [PATCH 04/19] feat: verify webhooks with the Paystack signing secret
When a mode has a whsec_ signing secret, Paystack-Signature (HMAC-SHA512 of
".", 5-minute window, any v1 entry) decides alone, so a delivery
can't be downgraded to the untimed legacy header. Without one, the legacy
X-Paystack-Signature check runs only for a stored sk_; a restricted key is
never used as an HMAC key. Keys for verification are read straight from
settings, and an event with no data.domain is verified under each configured
mode instead of the global one.
Co-Authored-By: Claude Opus 5.5
---
class-gf-paystack-api.php | 103 +++++++++++++++++++++--
class-gf-paystack.php | 84 ++++++++++++++++---
tests/fixtures.php | 6 ++
tests/test-gateway.php | 2 +-
tests/test-webhook.php | 171 +++++++++++++++++++++++++++++++++++++-
5 files changed, 344 insertions(+), 22 deletions(-)
diff --git a/class-gf-paystack-api.php b/class-gf-paystack-api.php
index 99444d6..90a7330 100644
--- a/class-gf-paystack-api.php
+++ b/class-gf-paystack-api.php
@@ -13,11 +13,20 @@ class GFPaystackApi
protected $secret_key;
+ protected $webhook_secret;
+
+ protected $stored_secret_key;
+
+ /** @var array|null Path (`whsec`|`legacy`|`none`) and outcome of the last validate_webhook() call. */
+ public $last_webhook_check = null;
+
public function __construct($config)
{
$this->plugin_name = 'Paystack Addon for Gravity Forms';
$this->secret_key = $config->secret_key ?? '';
$this->public_key = $config->public_key ?? '';
+ $this->webhook_secret = $config->webhook_secret ?? '';
+ $this->stored_secret_key = $config->stored_secret_key ?? '';
}
/**
@@ -115,21 +124,99 @@ public function verify_transaction($reference)
/**
* Validate Webhook Signature
*
- * @param $input
- * @param string|null $signature Defaults to the request's signature header.
+ * A configured signing secret decides alone; the legacy sk HMAC is only used when none is set.
+ *
+ * @param string $input The raw body that will be decoded.
+ * @param string|null $signature Legacy X-Paystack-Signature; defaults to the request's header.
+ * @param string|null $signing_header Paystack-Signature; defaults to the request's header.
* @return boolean
*/
- public function validate_webhook($input, $signature = null)
+ public function validate_webhook($input, $signature = null, $signing_header = null)
+ {
+ if (is_string($this->webhook_secret) && trim($this->webhook_secret) !== '') {
+ if ($signing_header === null) {
+ $signing_header = isset($_SERVER['HTTP_PAYSTACK_SIGNATURE']) ? $_SERVER['HTTP_PAYSTACK_SIGNATURE'] : '';
+ }
+
+ $outcome = $this->check_signing_secret_header($input, $signing_header);
+ $this->last_webhook_check = array('sig' => 'whsec', 'result' => $outcome);
+
+ return $outcome === 'valid';
+ }
+
+ if (GF_Paystack_Keys::type($this->stored_secret_key) === 'sk') {
+ if ($signature === null) {
+ $signature = isset($_SERVER['HTTP_X_PAYSTACK_SIGNATURE']) ? $_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] : '';
+ }
+
+ $is_valid = is_string($signature) && $signature !== ''
+ && hash_equals(hash_hmac('sha512', (string) $input, $this->stored_secret_key), $signature);
+ $this->last_webhook_check = array('sig' => 'legacy', 'result' => $is_valid ? 'valid' : 'invalid');
+
+ return $is_valid;
+ }
+
+ $this->last_webhook_check = array('sig' => 'none', 'result' => 'invalid');
+
+ return false;
+ }
+
+ /**
+ * Verify a `Paystack-Signature: t=,v1=:[,v1=...]` header.
+ *
+ * @param string $input The raw body.
+ * @param mixed $header The header value.
+ * @param int|null $now Current unix time; defaults to time().
+ * @return string valid|stale|invalid|malformed
+ */
+ public function check_signing_secret_header($input, $header, $now = null)
{
- if ($signature === null) {
- $signature = isset($_SERVER['HTTP_X_PAYSTACK_SIGNATURE']) ? $_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] : '';
+ if (!is_string($this->webhook_secret) || trim($this->webhook_secret) === '' || !is_string($header)) {
+ return 'malformed';
}
- if (!is_string($signature) || $signature === '' || !is_string($this->secret_key) || trim($this->secret_key) === '') {
- return false;
+ $timestamps = array();
+ $signatures = array();
+ foreach (explode(',', $header) as $part) {
+ $pair = explode('=', $part, 2);
+ if (count($pair) !== 2) {
+ continue;
+ }
+
+ $name = trim($pair[0]);
+ $value = trim($pair[1]);
+ if ($name === 't') {
+ $timestamps[] = $value;
+ } elseif ($name === 'v1' && count($signatures) < 10) {
+ $colon = strrpos($value, ':');
+ $hex = $colon === false ? '' : substr($value, $colon + 1);
+ if ($colon > 0 && preg_match('/^[0-9a-fA-F]{128}$/', $hex)) {
+ $signatures[] = strtolower($hex);
+ }
+ }
}
- return hash_equals(hash_hmac('sha512', (string) $input, $this->secret_key), $signature);
+ if (count($timestamps) !== 1 || !ctype_digit($timestamps[0]) || empty($signatures)) {
+ return 'malformed';
+ }
+
+ $timestamp = $timestamps[0];
+ $expected = hash_hmac('sha512', $timestamp . '.' . (string) $input, $this->webhook_secret);
+
+ $matched = false;
+ foreach ($signatures as $candidate) {
+ if (hash_equals($expected, $candidate)) {
+ $matched = true;
+ }
+ }
+
+ if (!$matched) {
+ return 'invalid';
+ }
+
+ $now = $now === null ? time() : (int) $now;
+
+ return abs($now - (int) $timestamp) <= 300 ? 'valid' : 'stale';
}
/**
diff --git a/class-gf-paystack.php b/class-gf-paystack.php
index 74bb5f6..87655ab 100644
--- a/class-gf-paystack.php
+++ b/class-gf-paystack.php
@@ -1713,28 +1713,62 @@ public function get_webhook_event($body = null)
$settings = $this->get_plugin_settings();
- // Get api mode from data
- $mode = self::resolve_webhook_mode(rgars($response, 'data/domain')) ?: $this->get_api_mode($settings);
+ $domain_mode = self::resolve_webhook_mode(rgars($response, 'data/domain'));
+
+ if ($domain_mode) {
+ $candidates = array($domain_mode);
+ } else {
+ $candidates = array();
+ foreach (array('live', 'test') as $candidate_mode) {
+ if ($this->get_webhook_secret($candidate_mode, $settings) !== ''
+ || GF_Paystack_Keys::type($this->get_stored_secret_key($candidate_mode, $settings)) === 'sk') {
+ $candidates[] = $candidate_mode;
+ }
+ }
+ }
- $this->paystack_api($mode, $settings);
+ // No usable mode still runs the check once so the failure is logged like any other.
+ if (empty($candidates)) {
+ $candidates = array($this->get_api_mode($settings));
+ }
- $this->webhook_mode = $mode;
+ $check = null;
+ $mode = null;
+ foreach ($candidates as $candidate_mode) {
+ $this->paystack_api($candidate_mode, $settings);
- // Validate Webhook Request Payload
- try {
- $is_verified = $this->paystack_api->validate_webhook($body);
- } catch (\Exception $e) {
- $this->log_error(__METHOD__ . "(): Error: " . $e->getMessage());
+ // Validate Webhook Request Payload
+ try {
+ $is_verified = $this->paystack_api->validate_webhook($body);
+ } catch (\Exception $e) {
+ $this->log_error(__METHOD__ . "(): Error: " . $e->getMessage());
+
+ return new WP_Error('Webhook Validation Failed', $e->getMessage());
+ }
+
+ $check = $this->paystack_api->last_webhook_check;
+ $mode = $candidate_mode;
- return new WP_Error('Webhook Validation Failed', $e->getMessage());
+ if ($is_verified) {
+ break;
+ }
}
+ $this->webhook_mode = $mode;
+
if (!$is_verified) {
- $this->log_error(__METHOD__ . '(): Wehhook request is invalid. Aborting.');
+ $this->log_error(sprintf(
+ '%s(): Webhook request is invalid. Aborting. sig=%s result=%s',
+ __METHOD__,
+ rgar($check, 'sig'),
+ rgar($check, 'result')
+ ));
return false;
}
+ $this->log_debug(sprintf('%s(): Webhook verified. sig=%s result=%s', __METHOD__, rgar($check, 'sig'), rgar($check, 'result')));
+
$this->log_debug(__METHOD__ . "(): Processing {$this->webhook_mode} mode event.");
return $response;
@@ -1967,7 +2001,9 @@ public function paystack_api($mode = null, $settings = null)
$config = (object) array(
'secret_key' => $this->get_secret_api_key($mode, $settings),
- 'public_key' => $this->get_public_api_key($mode, $settings)
+ 'public_key' => $this->get_public_api_key($mode, $settings),
+ 'webhook_secret' => $this->get_webhook_secret($mode, $settings),
+ 'stored_secret_key' => $this->get_stored_secret_key($mode, $settings)
);
$this->log_debug(sprintf('%s(): Initializing Paystack API for %s mode.', __METHOD__, $mode));
@@ -1975,6 +2011,30 @@ public function paystack_api($mode = null, $settings = null)
return $this->paystack_api = new GFPaystackApi($config);
}
+ /**
+ * Read straight from settings so the ?secret= override can't reach webhook verification.
+ *
+ * @param string $mode
+ * @param array|null $settings
+ *
+ * @return string
+ */
+ public function get_webhook_secret($mode, $settings = null)
+ {
+ return trim((string) rgar(empty($settings) ? $this->get_plugin_settings() : $settings, "{$mode}_webhook_secret"));
+ }
+
+ /**
+ * @param string $mode
+ * @param array|null $settings
+ *
+ * @return string
+ */
+ public function get_stored_secret_key($mode, $settings = null)
+ {
+ return trim((string) rgar(empty($settings) ? $this->get_plugin_settings() : $settings, "{$mode}_secret_key"));
+ }
+
// # OTHER HELPER FUNCTIONS ----------------------------------------------------------------------------------------------
/**
diff --git a/tests/fixtures.php b/tests/fixtures.php
index 7cae16e..e8c2fd4 100644
--- a/tests/fixtures.php
+++ b/tests/fixtures.php
@@ -125,12 +125,18 @@ public function get_amount_export($amount, $currency)
class GFPaystackEventFixture extends GFPaystack
{
public $settings = array();
+ public $errors = array();
public function get_plugin_settings()
{
return $this->settings;
}
+ public function log_error($message)
+ {
+ $this->errors[] = $message;
+ }
+
public function webhook_mode_value()
{
return $this->webhook_mode;
diff --git a/tests/test-gateway.php b/tests/test-gateway.php
index 1e91272..ec144a0 100644
--- a/tests/test-gateway.php
+++ b/tests/test-gateway.php
@@ -63,7 +63,7 @@
$_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] = hash_hmac('sha512', '', 'sk_live_a');
$event_result = $event_addon->get_webhook_event();
-gf_paystack_test_check($event_addon->webhook_mode_value() === 'test' && $event_result === false, 'get_webhook_event case 2');
+gf_paystack_test_check($event_addon->webhook_mode_value() === 'live' && $event_result !== false && !is_wp_error($event_result), 'get_webhook_event case 2: no domain verifies under the mode whose key signed it');
$event_addon->settings['api_mode'] = 'live';
$event_result = $event_addon->get_webhook_event();
diff --git a/tests/test-webhook.php b/tests/test-webhook.php
index b75a53f..a61e1da 100644
--- a/tests/test-webhook.php
+++ b/tests/test-webhook.php
@@ -1,7 +1,7 @@
'sk_test_secret', 'public_key' => 'pk'));
+$webhook_api = new GFPaystackApi((object) array('secret_key' => 'sk_test_secret', 'public_key' => 'pk', 'stored_secret_key' => 'sk_test_secret'));
$webhook_sig = hash_hmac('sha512', $webhook_body, 'sk_test_secret');
unset($_SERVER['HTTP_X_PAYSTACK_SIGNATURE']);
@@ -227,3 +227,172 @@ public function send_request($endpoint, $args = array(), $method = 'post', $doma
$path_api = new GFPaystackPathRecordingApi((object) array('secret_key' => 'sk', 'public_key' => 'pk'));
$path_api->verify_transaction('a/b?c#d');
gf_paystack_test_check($path_api->paths === array('transaction/verify/a%2Fb%3Fc%23d'), 'verify_transaction case 1');
+
+// # Signing-secret (Paystack-Signature) verification
+$whsec = 'whsec_' . str_repeat('ab12', 8);
+$whsec_other = 'whsec_' . str_repeat('cd34', 8);
+$sk_live = 'sk_live_abc123';
+$rk_live = 'rk_live_' . str_repeat('x', 20);
+$reset_sig_headers = function () {
+ unset($_SERVER['HTTP_PAYSTACK_SIGNATURE'], $_SERVER['HTTP_X_PAYSTACK_SIGNATURE']);
+};
+$reset_sig_headers();
+$sign = function ($t, $body, $secret, $kid = 'k1') {
+ return "v1={$kid}:" . hash_hmac('sha512', $t . '.' . $body, $secret);
+};
+$whsec_api = function ($secret, $stored = '') {
+ return new GFPaystackApi((object) array('secret_key' => $stored, 'public_key' => 'pk', 'webhook_secret' => $secret, 'stored_secret_key' => $stored));
+};
+$now = 1800000000;
+$bad_v1 = 'v1=k0:' . str_repeat('0', 128);
+
+$api = $whsec_api($whsec);
+$t = (string) $now;
+gf_paystack_test_check($api->check_signing_secret_header($webhook_body, "t=$t," . $sign($t, $webhook_body, $whsec), $now) === 'valid', 'whsec valid header');
+gf_paystack_test_check($api->check_signing_secret_header($webhook_body, " t = $t , " . $sign($t, $webhook_body, $whsec), $now) === 'valid', 'whsec header whitespace trimmed');
+gf_paystack_test_check($api->check_signing_secret_header($webhook_body, "t=$t,$bad_v1," . $sign($t, $webhook_body, $whsec, 'k2'), $now) === 'valid', 'whsec rotated multi-v1, right one second');
+gf_paystack_test_check($api->check_signing_secret_header($webhook_body, "t=$t," . $sign($t, $webhook_body, $whsec) . ",$bad_v1", $now) === 'valid', 'whsec rotated multi-v1, right one first');
+gf_paystack_test_check($api->check_signing_secret_header($webhook_body, "t=$t,$bad_v1,$bad_v1", $now) === 'invalid', 'whsec all v1 wrong');
+
+$t_old = (string) ($now - 301);
+$t_edge = (string) ($now - 300);
+$t_future = (string) ($now + 301);
+gf_paystack_test_check($api->check_signing_secret_header($webhook_body, "t=$t_old," . $sign($t_old, $webhook_body, $whsec), $now) === 'stale', 'whsec stale t-301');
+gf_paystack_test_check($api->check_signing_secret_header($webhook_body, "t=$t_future," . $sign($t_future, $webhook_body, $whsec), $now) === 'stale', 'whsec future t+301');
+gf_paystack_test_check($api->check_signing_secret_header($webhook_body, "t=$t_edge," . $sign($t_edge, $webhook_body, $whsec), $now) === 'valid', 'whsec t-300 accepted');
+gf_paystack_test_check($api->check_signing_secret_header($webhook_body, "t=$t_old," . $bad_v1, $now) === 'invalid', 'whsec HMAC checked before window');
+
+$good_v1 = $sign($t, $webhook_body, $whsec);
+gf_paystack_test_check($api->check_signing_secret_header($webhook_body, "t=$t,t=$t,$good_v1", $now) === 'malformed', 'whsec two t values');
+gf_paystack_test_check($api->check_signing_secret_header($webhook_body, $good_v1, $now) === 'malformed', 'whsec no t');
+gf_paystack_test_check($api->check_signing_secret_header($webhook_body, "t=12ab,$good_v1", $now) === 'malformed', 'whsec non-digit t');
+gf_paystack_test_check($api->check_signing_secret_header($webhook_body, "t=-5,$good_v1", $now) === 'malformed', 'whsec negative t');
+gf_paystack_test_check($api->check_signing_secret_header($webhook_body, "t=$t", $now) === 'malformed', 'whsec no v1');
+gf_paystack_test_check($api->check_signing_secret_header($webhook_body, "t=$t,v1=" . hash_hmac('sha512', $t . '.' . $webhook_body, $whsec), $now) === 'malformed', 'whsec v1 without kid');
+gf_paystack_test_check($api->check_signing_secret_header($webhook_body, "t=$t,v1=k1:abc", $now) === 'malformed', 'whsec v1 short hex');
+gf_paystack_test_check($api->check_signing_secret_header($webhook_body, '', $now) === 'malformed', 'whsec empty header');
+gf_paystack_test_check($api->check_signing_secret_header($webhook_body, array($good_v1), $now) === 'malformed', 'whsec non-string header');
+
+$many = "t=$t," . str_repeat("$bad_v1,", 10) . $good_v1;
+gf_paystack_test_check($api->check_signing_secret_header($webhook_body, $many, $now) === 'invalid', 'whsec v1 entries beyond 10 ignored');
+$nine = "t=$t," . str_repeat("$bad_v1,", 9) . $good_v1;
+gf_paystack_test_check($api->check_signing_secret_header($webhook_body, $nine, $now) === 'valid', 'whsec 10th v1 entry counted');
+
+gf_paystack_test_check($api->check_signing_secret_header('{"event":"charge.success","x":1}', "t=$t,$good_v1", $now) === 'invalid', 'whsec tampered body');
+gf_paystack_test_check($whsec_api($whsec_other)->check_signing_secret_header($webhook_body, "t=$t,$good_v1", $now) === 'invalid', 'whsec wrong secret');
+gf_paystack_test_check($whsec_api('')->check_signing_secret_header($webhook_body, "t=$t,$good_v1", $now) === 'malformed', 'whsec blank secret never verifies');
+
+// validate_webhook(): header from $_SERVER, HMAC over the injected $input
+$live_t = (string) time();
+$live_header = "t=$live_t," . $sign($live_t, $webhook_body, $whsec);
+$_SERVER['HTTP_PAYSTACK_SIGNATURE'] = $live_header;
+gf_paystack_test_check($whsec_api($whsec)->validate_webhook($webhook_body) === true, 'validate_webhook whsec via server header');
+$checked = $whsec_api($whsec);
+$checked->validate_webhook($webhook_body);
+gf_paystack_test_check($checked->last_webhook_check === array('sig' => 'whsec', 'result' => 'valid'), 'validate_webhook records whsec/valid');
+gf_paystack_test_check($whsec_api($whsec)->validate_webhook('{"event":"charge.success","amount":1}') === false, 'validate_webhook HMAC uses injected input, not signed body');
+$reset_sig_headers();
+gf_paystack_test_check($whsec_api($whsec)->validate_webhook($webhook_body) === false, 'validate_webhook whsec set, no header');
+
+// whsec set: legacy header must not rescue a bad or missing Paystack-Signature
+$legacy = hash_hmac('sha512', $webhook_body, $sk_live);
+$_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] = $legacy;
+gf_paystack_test_check($whsec_api($whsec, $sk_live)->validate_webhook($webhook_body) === false, 'whsec set + only valid legacy header rejected');
+$_SERVER['HTTP_PAYSTACK_SIGNATURE'] = "t=$live_t,$bad_v1";
+gf_paystack_test_check($whsec_api($whsec, $sk_live)->validate_webhook($webhook_body) === false, 'whsec set + bad header + valid legacy rejected');
+gf_paystack_test_check($whsec_api($whsec, $sk_live)->validate_webhook($webhook_body, $legacy) === false, 'whsec set + legacy passed explicitly rejected');
+$reset_sig_headers();
+
+// rk stored without whsec is never an HMAC key
+$rk_sig = hash_hmac('sha512', $webhook_body, $rk_live);
+$_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] = $rk_sig;
+gf_paystack_test_check($whsec_api('', $rk_live)->validate_webhook($webhook_body) === false, 'rk without whsec rejected despite rk-signed header');
+$rk_api = new GFPaystackApi((object) array('secret_key' => $rk_live, 'public_key' => 'pk', 'webhook_secret' => '', 'stored_secret_key' => $rk_live));
+gf_paystack_test_check($rk_api->validate_webhook($webhook_body, $rk_sig) === false, 'rk without whsec rejected with explicit signature');
+$reset_sig_headers();
+
+// sk legacy path unchanged
+$_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] = $legacy;
+$sk_api = $whsec_api('', $sk_live);
+gf_paystack_test_check($sk_api->validate_webhook($webhook_body) === true && $sk_api->last_webhook_check === array('sig' => 'legacy', 'result' => 'valid'), 'sk legacy path valid');
+gf_paystack_test_check($sk_api->validate_webhook('{"tampered":1}') === false, 'sk legacy path tampered body');
+$reset_sig_headers();
+
+// get_webhook_event(): mode selection
+$event_addon = function ($settings) {
+ $addon = new GFPaystackEventFixture();
+ $addon->settings = $settings;
+ return $addon;
+};
+$header_for = function ($body, $secret) use ($sign) {
+ $ts = (string) time();
+ return "t=$ts," . $sign($ts, $body, $secret);
+};
+$live_whsec = $whsec;
+$test_whsec = $whsec_other;
+$both = array('api_mode' => 'live', 'live_secret_key' => $rk_live, 'live_webhook_secret' => $live_whsec, 'test_secret_key' => 'rk_test_' . str_repeat('y', 20), 'test_webhook_secret' => $test_whsec);
+
+$event_body = json_encode(array('event' => 'charge.success', 'data' => array('reference' => 'gf-7-abc')));
+$_SERVER['HTTP_PAYSTACK_SIGNATURE'] = $header_for($event_body, $test_whsec);
+$addon = $event_addon($both);
+$event = $addon->get_webhook_event($event_body);
+gf_paystack_test_check(is_array($event) && $addon->webhook_mode_value() === 'test', 'domain missing: verifies under the mode whose whsec matches (test)');
+
+$_SERVER['HTTP_PAYSTACK_SIGNATURE'] = $header_for($event_body, $live_whsec);
+$addon = $event_addon($both);
+$event = $addon->get_webhook_event($event_body);
+gf_paystack_test_check(is_array($event) && $addon->webhook_mode_value() === 'live', 'domain missing: verifies under the mode whose whsec matches (live)');
+
+$_SERVER['HTTP_PAYSTACK_SIGNATURE'] = $header_for($event_body, 'whsec_' . str_repeat('ef56', 8));
+$addon = $event_addon($both);
+gf_paystack_test_check($addon->get_webhook_event($event_body) === false, 'domain missing: no mode verifies');
+gf_paystack_test_check(count($addon->errors) === 1 && strpos($addon->errors[0], 'sig=whsec result=invalid') !== false && strpos($addon->errors[0], $live_whsec) === false, 'failure logged at error level with sig/result, no secret');
+
+$domain_body = json_encode(array('event' => 'charge.success', 'data' => array('domain' => 'live', 'reference' => 'gf-7-abc')));
+$_SERVER['HTTP_PAYSTACK_SIGNATURE'] = $header_for($domain_body, $test_whsec);
+$addon = $event_addon($both);
+gf_paystack_test_check($addon->get_webhook_event($domain_body) === false, 'domain=live with a test-secret signature rejected (no cross-mode retry)');
+
+$_SERVER['HTTP_PAYSTACK_SIGNATURE'] = $header_for($domain_body, $live_whsec);
+$addon = $event_addon($both);
+gf_paystack_test_check(is_array($addon->get_webhook_event($domain_body)) && $addon->webhook_mode_value() === 'live', 'domain=live verifies with live whsec');
+
+$test_event_body = json_encode(array('event' => 'charge.success', 'data' => array('reference' => 'gf-7-abc')));
+$_SERVER['HTTP_PAYSTACK_SIGNATURE'] = $header_for($test_event_body, $test_whsec);
+$addon = $event_addon($both);
+$addon->get_webhook_event($test_event_body);
+$GLOBALS['gf_paystack_test_entries'] = array('7' => array('id' => '7', 'form_id' => '1'));
+$GLOBALS['gf_paystack_test_meta'] = array('7' => array('paystack_mode' => 'live'));
+$matcher = new class extends GFPaystackEventFixture {
+ public function matches($entry)
+ {
+ return $this->webhook_mode_matches_entry($entry, array('meta' => array('mode' => 'live')));
+ }
+ public function set_mode($mode)
+ {
+ $this->webhook_mode = $mode;
+ }
+};
+$matcher->set_mode($addon->webhook_mode_value());
+gf_paystack_test_check($matcher->matches(array('id' => '7')) === false, 'test-signed event cannot match a live entry');
+
+// sk merchant without whsec: legacy path through get_webhook_event, mode from domain or sk presence
+$sk_settings = array('api_mode' => 'live', 'live_secret_key' => $sk_live);
+$_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] = hash_hmac('sha512', $event_body, $sk_live);
+$addon = $event_addon($sk_settings);
+gf_paystack_test_check(is_array($addon->get_webhook_event($event_body)) && $addon->webhook_mode_value() === 'live', 'sk legacy via get_webhook_event, domain missing');
+$reset_sig_headers();
+
+// ?secret= must not change the verifying key
+$_GET['secret'] = 'sk_live_attacker';
+$_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] = hash_hmac('sha512', $event_body, 'sk_live_attacker');
+$addon = $event_addon($sk_settings);
+gf_paystack_test_check($addon->get_webhook_event($event_body) === false, '?secret= does not reach webhook verification');
+$_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] = hash_hmac('sha512', $event_body, $sk_live);
+gf_paystack_test_check(is_array($event_addon($sk_settings)->get_webhook_event($event_body)), '?secret= present, stored sk still verifies');
+unset($_GET['secret']);
+
+// no whsec, no sk: rejected
+$_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] = hash_hmac('sha512', $event_body, $rk_live);
+gf_paystack_test_check($event_addon(array('api_mode' => 'live', 'live_secret_key' => $rk_live))->get_webhook_event($event_body) === false, 'rk only, no whsec: get_webhook_event rejects');
+$reset_sig_headers();
From cf825b45989e657b0bedbda34f3ce692c6498759 Mon Sep 17 00:00:00 2001
From: Jules Nsenda
Date: Wed, 18 Nov 2026 20:45:56 +0200
Subject: [PATCH 05/19] docs: explain restricted keys and webhook signing
secrets
Co-Authored-By: Claude Opus 5.5
---
readme.txt | 27 +++++++++++++++++++++++++++
1 file changed, 27 insertions(+)
diff --git a/readme.txt b/readme.txt
index fbec328..b1ea135 100644
--- a/readme.txt
+++ b/readme.txt
@@ -12,6 +12,26 @@ License URI: http://www.gnu.org/licenses/gpl-2.0.html
== Description ==
The Paystack Addon for Gravity Forms allows you to quickly and easily implement credit card payments with WordPress. With the Paystack Add-On you can capture one time credit card payments or setup recurring payment subscriptions.
+= Restricted keys =
+You can use a Paystack restricted key instead of your full secret key. Paste an `rk_test_...` or `rk_live_...` key into the matching Test or Live Secret key field.
+
+* The key needs Transactions: read and write permissions, plus Plans: write if you sell subscriptions.
+* Keys with permissions that can move money (transfers, refunds, settlements, payouts and similar) are rejected.
+* The key is checked with Paystack when you save it, and only then. If you change its permissions later in the Paystack Dashboard, it is not checked again.
+* A restricted key needs the Webhook signing secret for the same mode (see below).
+
+= Webhook signing secret =
+The Test and Live settings have a "Webhook signing secret" field. Copy the `whsec_...` value from Settings > API Keys & Webhooks in your Paystack Dashboard.
+
+* It is required when you use a restricted key, and optional when you use a secret key.
+* Once it is set, webhooks are only accepted with a valid Paystack-Signature header that was signed within the last 5 minutes.
+* Successful-payment webhooks are confirmed with Paystack before an entry is marked as paid.
+
+= For developers =
+Restricted keys can be turned off with the `gform_paystack_restricted_keys_enabled` filter (default `true`). Restricted keys that were already saved keep working.
+
+`add_filter( 'gform_paystack_restricted_keys_enabled', '__return_false' );`
+
== Installation ==
@@ -54,6 +74,13 @@ Yes you can! Join in on our [GitHub repository](https://github.com/PaystackHQ/pl
== Changelog ==
+= Unreleased =
+* Added support for Paystack restricted keys (`rk_test_...` / `rk_live_...`).
+* Added Test and Live webhook signing secret fields, and webhook signature verification when one is set.
+* Successful-payment (charge.success) webhooks are now confirmed with Paystack before an entry is marked as paid.
+* Keys and signing secrets are hidden in logs.
+* The key fields are now password inputs.
+
= 2.0.9 - October 28, 2026 =
* Fixed a fatal error on the confirmation page after a successful payment when the usage tracking service is unreachable.
From 98f1d927c44a8c0fb625a2cdfcac3630a8033835 Mon Sep 17 00:00:00 2001
From: Jules Nsenda
Date: Wed, 18 Nov 2026 20:46:23 +0200
Subject: [PATCH 06/19] feat: hide keys in logs and log restricted-key scope
refusals
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Every plugin log line goes through GF_Paystack_Keys::redact(), and an
API call refused for a missing restricted-key scope logs
"rk scope denied method=… path=…" so support can see which permission is
missing.
Co-Authored-By: Claude Opus 5.5
---
class-gf-paystack-api.php | 9 +++++++--
class-gf-paystack.php | 12 ++++++++++++
tests/stubs.php | 2 ++
tests/test-gateway.php | 34 ++++++++++++++++++++++++++++++++++
4 files changed, 55 insertions(+), 2 deletions(-)
diff --git a/class-gf-paystack-api.php b/class-gf-paystack-api.php
index 90a7330..18ef7ff 100644
--- a/class-gf-paystack-api.php
+++ b/class-gf-paystack-api.php
@@ -59,7 +59,7 @@ public function log_transaction_success($reference)
'https://plugin-tracker.paystackintegrations.com/'
);
} catch (\Throwable $e) {
- error_log(__METHOD__ . '(): plugin tracker request failed: ' . $e->getMessage());
+ error_log(GF_Paystack_Keys::redact(__METHOD__ . '(): plugin tracker request failed: ' . $e->getMessage()));
}
}
@@ -97,7 +97,12 @@ public function send_request(
$body = json_decode($res['body'], true);
if (is_array($body)) {
- error_log(__METHOD__ . '(): ' . strtoupper($method) . ' ' . $uri . ' status: ' . (isset($body['status']) ? var_export($body['status'], true) : 'unknown'));
+ error_log(GF_Paystack_Keys::redact(__METHOD__ . '(): ' . strtoupper($method) . ' ' . $uri . ' status: ' . (isset($body['status']) ? var_export($body['status'], true) : 'unknown')));
+
+ $code = isset($res['response']['code']) ? (int) $res['response']['code'] : 0;
+ if ($code === 403 && isset($body['message']) && $body['message'] === 'This restricted key is not permitted to perform this action') {
+ error_log(GF_Paystack_Keys::redact('rk scope denied method=' . strtoupper($method) . ' path=' . parse_url($uri, PHP_URL_PATH)));
+ }
if (isset($body['error']) || $body['status'] == false) {
throw new Exception("{$body['message']}");
diff --git a/class-gf-paystack.php b/class-gf-paystack.php
index 87655ab..2d761c2 100644
--- a/class-gf-paystack.php
+++ b/class-gf-paystack.php
@@ -2,6 +2,8 @@
defined('ABSPATH') || die();
+require_once __DIR__ . '/includes/class-gf-paystack-keys.php';
+
// Include the payment add-on framework.
GFForms::include_payment_addon_framework();
@@ -227,6 +229,16 @@ public static function get_instance()
return self::$_instance;
}
+ public function log_debug($message)
+ {
+ parent::log_debug(GF_Paystack_Keys::redact($message));
+ }
+
+ public function log_error($message)
+ {
+ parent::log_error(GF_Paystack_Keys::redact($message));
+ }
+
/**
* Load the Paystack credit card field.
*
diff --git a/tests/stubs.php b/tests/stubs.php
index f65b052..fa85f9d 100644
--- a/tests/stubs.php
+++ b/tests/stubs.php
@@ -157,10 +157,12 @@ public static function get_entry_meta_table_name()
public function log_debug($message)
{
+ $GLOBALS['gf_paystack_test_gf_logs'][] = array('debug', $message);
}
public function log_error($message)
{
+ $GLOBALS['gf_paystack_test_gf_logs'][] = array('error', $message);
}
public function get_plugin_settings()
diff --git a/tests/test-gateway.php b/tests/test-gateway.php
index ec144a0..9ad74b9 100644
--- a/tests/test-gateway.php
+++ b/tests/test-gateway.php
@@ -50,9 +50,43 @@
});
gf_paystack_test_check(strpos($log_thrown, 'Paystack Addon for Gravity Forms') !== false, 'send_request logging case 5');
+file_put_contents($log_file, '');
+$GLOBALS['gf_paystack_test_remote_response'] = array('body' => json_encode(array('status' => false, 'message' => 'bad rk_live_abc123XYZ and whsec_def456 given')));
+$log_thrown = gf_paystack_exception_message(function () use ($log_api) {
+ $log_api->send_request('transaction/verify/abc', array(), 'get');
+});
+$log_contents = (string) file_get_contents($log_file);
+gf_paystack_test_check(strpos($log_contents, 'abc123XYZ') === false && strpos($log_contents, 'def456') === false, 'send_request logging case 6');
+
+$rk_api = new GFPaystackApi((object) array('secret_key' => 'rk_live_scopedsecret99', 'public_key' => 'pk_live_public'));
+file_put_contents($log_file, '');
+$GLOBALS['gf_paystack_test_remote_response'] = array('response' => array('code' => 403), 'body' => json_encode(array('status' => false, 'message' => 'This restricted key is not permitted to perform this action')));
+$log_thrown = gf_paystack_exception_message(function () use ($rk_api) {
+ $rk_api->send_request('transaction/verify/abc?x=1', array(), 'get');
+});
+$log_contents = (string) file_get_contents($log_file);
+gf_paystack_test_check($log_thrown === 'This restricted key is not permitted to perform this action', 'rk scope denied case 1');
+gf_paystack_test_check(strpos($log_contents, 'rk scope denied method=GET path=/transaction/verify/abc') !== false && strpos($log_contents, 'x=1', strpos($log_contents, 'rk scope denied')) === false, 'rk scope denied case 2');
+gf_paystack_test_check(strpos($log_contents, 'rk_live_scopedsecret99') === false, 'rk scope denied case 3');
+
+file_put_contents($log_file, '');
+$GLOBALS['gf_paystack_test_remote_response'] = array('response' => array('code' => 403), 'body' => json_encode(array('status' => false, 'message' => 'Something else')));
+gf_paystack_exception_message(function () use ($rk_api) {
+ $rk_api->send_request('transaction/verify/abc', array(), 'get');
+});
+gf_paystack_test_check(strpos((string) file_get_contents($log_file), 'rk scope denied') === false, 'rk scope denied case 4');
+
ini_set('error_log', $previous_log === false ? '' : $previous_log);
unlink($log_file);
+$GLOBALS['gf_paystack_test_gf_logs'] = array();
+$gf_log_addon = new GFPaystackGatewayFixture();
+$gf_log_addon->log_error('bad rk_live_abc123XYZ here');
+$gf_log_addon->log_debug('got whsec_def456 and sk_test_ghi789');
+$gf_logged = json_encode($GLOBALS['gf_paystack_test_gf_logs']);
+gf_paystack_test_check(count($GLOBALS['gf_paystack_test_gf_logs']) === 2 && strpos($gf_logged, 'abc123XYZ') === false && strpos($gf_logged, 'def456') === false && strpos($gf_logged, 'ghi789') === false, 'addon log redaction case 1');
+gf_paystack_test_check(strpos($gf_logged, 'rk_live_[redacted]') !== false && strpos($gf_logged, 'whsec_[redacted]') !== false, 'addon log redaction case 2');
+
$event_settings = array('api_mode' => 'test', 'live_secret_key' => 'sk_live_a', 'test_secret_key' => 'sk_test_b');
$event_addon = new GFPaystackEventFixture();
$event_addon->settings = $event_settings;
From d707c162e73b9d083c1c7dc72dd072781e2bf943 Mon Sep 17 00:00:00 2001
From: Jules Nsenda
Date: Wed, 18 Nov 2026 20:48:51 +0200
Subject: [PATCH 07/19] feat: accept restricted keys and webhook signing
secrets in settings
The Test/Live secret key fields accept sk_ or rk_ keys and become password
inputs, with new Test/Live webhook signing secret fields beside them. Saving
a changed restricted key checks its permissions with Paystack, a restricted
key requires its mode's signing secret, and credential fields are stored
trimmed. Saving a subscription feed whose mode uses a restricted key checks
Plans: write.
Co-Authored-By: Claude Opus 5.5
---
class-gf-paystack.php | 257 +++++++++++++++++++++++++++++++++++++++-
tests/fixtures.php | 58 +++++++++
tests/stubs.php | 15 ++-
tests/test-settings.php | 139 ++++++++++++++++++++++
4 files changed, 466 insertions(+), 3 deletions(-)
create mode 100644 tests/test-settings.php
diff --git a/class-gf-paystack.php b/class-gf-paystack.php
index 2d761c2..746a477 100644
--- a/class-gf-paystack.php
+++ b/class-gf-paystack.php
@@ -3,6 +3,7 @@
defined('ABSPATH') || die();
require_once __DIR__ . '/includes/class-gf-paystack-keys.php';
+require_once __DIR__ . '/includes/class-gf-paystack-restricted-key.php';
// Include the payment add-on framework.
GFForms::include_payment_addon_framework();
@@ -324,6 +325,9 @@ public function api_settings_fields()
)
);
+ $key_help = '' . esc_html__('Secret or Restricted Key', 'gravityformspaystack') . '
' . esc_html__('A restricted key lets this plugin take payments and nothing else. Create one in your Paystack Dashboard with Transactions: read and write, plus Plans: write if you sell subscriptions.', 'gravityformspaystack');
+ $whsec_help = '' . esc_html__('Webhook Signing Secret', 'gravityformspaystack') . '
' . esc_html__('Copy it from Settings → API Keys & Webhooks in your Paystack Dashboard. Required with a restricted key.', 'gravityformspaystack');
+
$credentials_fields = array(
array(
'name' => 'test_public_key',
@@ -333,9 +337,20 @@ public function api_settings_fields()
),
array(
'name' => 'test_secret_key',
- 'label' => esc_html__('Test Secret Key', 'gravityformspaystack'),
+ 'label' => esc_html__('Test Secret or Restricted Key', 'gravityformspaystack'),
+ 'type' => 'text',
+ 'input_type' => 'password',
+ 'class' => 'medium',
+ 'tooltip' => $key_help,
+ 'validation_callback' => array($this, 'validate_test_secret_key'),
+ ),
+ array(
+ 'name' => 'test_webhook_secret',
+ 'label' => esc_html__('Test Webhook Signing Secret', 'gravityformspaystack'),
'type' => 'text',
+ 'input_type' => 'password',
'class' => 'medium',
+ 'tooltip' => $whsec_help,
),
array(
'name' => 'live_public_key',
@@ -345,9 +360,20 @@ public function api_settings_fields()
),
array(
'name' => 'live_secret_key',
- 'label' => esc_html__('Live Secret Key', 'gravityformspaystack'),
+ 'label' => esc_html__('Live Secret or Restricted Key', 'gravityformspaystack'),
'type' => 'text',
+ 'input_type' => 'password',
'class' => 'medium',
+ 'tooltip' => $key_help,
+ 'validation_callback' => array($this, 'validate_live_secret_key'),
+ ),
+ array(
+ 'name' => 'live_webhook_secret',
+ 'label' => esc_html__('Live Webhook Signing Secret', 'gravityformspaystack'),
+ 'type' => 'text',
+ 'input_type' => 'password',
+ 'class' => 'medium',
+ 'tooltip' => $whsec_help,
),
);
@@ -411,6 +437,7 @@ public function get_webhooks_section_description()
+
@@ -456,6 +483,12 @@ public function feed_settings_fields()
$default_settings = parent::add_field_after('feedName', $fields, $default_settings);
+ $transaction_type = $this->get_field('transactionType', $default_settings);
+ if (is_array($transaction_type)) {
+ $transaction_type['validation_callback'] = array($this, 'validate_subscription_plans');
+ $default_settings = $this->replace_field('transactionType', $transaction_type, $default_settings);
+ }
+
// Add donation to transaction type drop down
// $transaction_type = parent::get_field('transactionType', $default_settings);
// $choices = $transaction_type['choices'];
@@ -2047,6 +2080,226 @@ public function get_stored_secret_key($mode, $settings = null)
return trim((string) rgar(empty($settings) ? $this->get_plugin_settings() : $settings, "{$mode}_secret_key"));
}
+ // # KEY VALIDATION ------------------------------------------------------------------------------------------------
+
+ /**
+ * Validation compares trimmed values, so store them trimmed too: a pasted key with a trailing space would
+ * otherwise pass validation but break the Authorization header.
+ *
+ * @param array $settings
+ */
+ public function update_plugin_settings($settings)
+ {
+ if (is_array($settings)) {
+ foreach (array('test_secret_key', 'live_secret_key', 'test_webhook_secret', 'live_webhook_secret') as $name) {
+ if (isset($settings[$name]) && is_string($settings[$name])) {
+ $settings[$name] = trim($settings[$name]);
+ }
+ }
+ }
+
+ parent::update_plugin_settings($settings);
+ }
+
+ public function validate_test_secret_key($field)
+ {
+ $this->validate_secret_key_for_mode('test');
+ }
+
+ public function validate_live_secret_key($field)
+ {
+ $this->validate_secret_key_for_mode('live');
+ }
+
+ /**
+ * @param string $mode 'test' or 'live'.
+ *
+ * @return void
+ */
+ protected function validate_secret_key_for_mode($mode)
+ {
+ $other = $mode === 'test' ? 'live' : 'test';
+ $settings = $this->get_posted_settings();
+ $key = trim((string) rgar($settings, "{$mode}_secret_key"));
+
+ $result = GF_Paystack_Keys::resolve_save(
+ $mode,
+ $key,
+ $this->get_plugin_setting("{$mode}_secret_key"),
+ rgar($settings, "{$mode}_webhook_secret"),
+ rgar($settings, "{$other}_webhook_secret"),
+ GF_Paystack_Keys::restricted_keys_enabled()
+ );
+
+ if ($result['error'] !== null) {
+ $field_name = strpos($result['error'], 'whsec_') === 0 ? "{$mode}_webhook_secret" : "{$mode}_secret_key";
+ $this->set_field_error(array('name' => $field_name), $this->key_error_message($result['error'], $mode, $other) . $this->not_saved_suffix());
+ return;
+ }
+
+ if (!$result['probe']) {
+ return;
+ }
+
+ $verdict = $this->validate_restricted_key($key);
+ $this->log_debug("rk validate mode={$mode} code={$verdict['code']} probes={$verdict['probes']}");
+
+ if ($verdict['code'] !== 'ok') {
+ $this->set_field_error(array('name' => "{$mode}_secret_key"), $this->probe_error_message($verdict) . $this->not_saved_suffix());
+ }
+ }
+
+ /**
+ * @param string $key
+ *
+ * @return array
+ */
+ protected function validate_restricted_key($key)
+ {
+ return GF_Paystack_Restricted_Key::validate($key);
+ }
+
+ /**
+ * @param string $key
+ *
+ * @return string
+ */
+ protected function probe_restricted_key_plans($key)
+ {
+ return GF_Paystack_Restricted_Key::probe_plans($key);
+ }
+
+ /**
+ * Subscription feeds need Plans: write, which the settings probe doesn't check.
+ *
+ * @param array $field The field properties. Not used.
+ *
+ * @return void
+ */
+ public function validate_subscription_plans($field)
+ {
+ $settings = $this->get_posted_settings();
+ if (rgar($settings, 'transactionType') !== 'subscription') {
+ return;
+ }
+
+ $mode = rgar($settings, 'mode') === 'test' ? 'test' : 'live';
+ $key = $this->get_stored_secret_key($mode);
+ if (GF_Paystack_Keys::type($key) !== 'rk') {
+ return;
+ }
+
+ $result = $this->probe_restricted_key_plans($key);
+ if ($result === 'ok') {
+ return;
+ }
+
+ if ($result === 'plans_missing') {
+ $message = sprintf(esc_html__('Subscriptions need Plans: write on your %s restricted key. Add it in your Paystack Dashboard, then save this feed again.', 'gravityformspaystack'), $mode);
+ } elseif ($result === 'plans_mor') {
+ $message = esc_html__('Paystack subscriptions aren\'t available for merchant-of-record accounts.', 'gravityformspaystack');
+ } else {
+ $message = esc_html__('We couldn\'t reach Paystack to check this key. Please try again.', 'gravityformspaystack');
+ }
+
+ $this->set_field_error(array('name' => 'transactionType'), $message);
+ }
+
+ /**
+ * @return string
+ */
+ protected function not_saved_suffix()
+ {
+ return ' ' . esc_html__('No settings were saved.', 'gravityformspaystack');
+ }
+
+ /**
+ * @param string $code A GF_Paystack_Keys::resolve_save() error code.
+ * @param string $mode
+ * @param string $other
+ *
+ * @return string
+ */
+ protected function key_error_message($code, $mode, $other)
+ {
+ switch ($code) {
+ case 'wrong_field':
+ return sprintf(esc_html__('This is a %1$s key. Paste it in the %1$s secret key field.', 'gravityformspaystack'), $other);
+ case 'invalid_format':
+ return sprintf(esc_html__('Secret keys start with sk_%1$s_ and restricted keys with rk_%1$s_. Check you copied the whole key.', 'gravityformspaystack'), $mode);
+ case 'rk_disabled':
+ return esc_html__('Restricted keys are turned off on this site. Use your secret key instead.', 'gravityformspaystack');
+ case 'whsec_required':
+ return sprintf(esc_html__('A restricted key can\'t verify Paystack webhooks. Add your %s webhook signing secret from Settings → API Keys & Webhooks in your Paystack Dashboard.', 'gravityformspaystack'), $mode);
+ case 'whsec_format':
+ return esc_html__('Webhook signing secrets start with whsec_. Copy it from Settings → API Keys & Webhooks in your Paystack Dashboard.', 'gravityformspaystack');
+ case 'whsec_same':
+ return esc_html__('Your test and live webhook signing secrets are the same. Each mode has its own secret.', 'gravityformspaystack');
+ }
+
+ return esc_html__('Paystack didn\'t accept this key.', 'gravityformspaystack');
+ }
+
+ /**
+ * @param array $verdict A GF_Paystack_Restricted_Key::validate() result.
+ *
+ * @return string
+ */
+ protected function probe_error_message($verdict)
+ {
+ switch ($verdict['code']) {
+ case 'invalid_key':
+ return esc_html__('Paystack didn\'t accept this key. It may be invalid, revoked, or restricted keys may not be enabled on your Paystack account yet.', 'gravityformspaystack');
+ case 'missing_scope':
+ case 'sensitive_scope':
+ $parts = array();
+ if (!empty($verdict['scopes'])) {
+ $parts[] = sprintf(esc_html__('enable %s', 'gravityformspaystack'), $this->scope_labels($verdict['scopes']));
+ }
+ if (!empty($verdict['sensitive_scopes'])) {
+ $parts[] = sprintf(esc_html__('remove %s', 'gravityformspaystack'), $this->scope_labels($verdict['sensitive_scopes']));
+ }
+ return sprintf(esc_html__('This restricted key can\'t be used: %s. It needs Transactions: read and write. Permissions that can move money aren\'t allowed.', 'gravityformspaystack'), implode('; ', $parts));
+ }
+
+ if ($verdict['reason'] === 'blocked') {
+ return esc_html__('Paystack refused our check of this key. Try again, or contact Paystack Support if it keeps happening.', 'gravityformspaystack');
+ }
+
+ return esc_html__('We couldn\'t reach Paystack to check this key. Please try again.', 'gravityformspaystack');
+ }
+
+ /**
+ * @param array $scopes Scope ids.
+ *
+ * @return string
+ */
+ protected function scope_labels($scopes)
+ {
+ $labels = array(
+ 'transactions:read' => 'Transactions: read',
+ 'transactions:write' => 'Transactions: write',
+ 'disputes_refunds' => 'Disputes and refunds',
+ 'bulk_charges' => 'Bulk charges',
+ 'direct_debit' => 'Direct debit',
+ 'preauthorizations' => 'Preauthorizations',
+ 'settlements' => 'Settlements',
+ 'subaccounts' => 'Subaccounts',
+ 'transfers' => 'Transfers',
+ 'virtual_accounts' => 'Virtual accounts',
+ 'webhooks' => 'Webhooks',
+ 'connect' => 'Connect',
+ 'payouts' => 'Payouts',
+ );
+
+ $out = array();
+ foreach ($scopes as $scope) {
+ $out[] = isset($labels[$scope]) ? $labels[$scope] : $scope;
+ }
+
+ return implode(', ', $out);
+ }
+
// # OTHER HELPER FUNCTIONS ----------------------------------------------------------------------------------------------
/**
diff --git a/tests/fixtures.php b/tests/fixtures.php
index e8c2fd4..5930eec 100644
--- a/tests/fixtures.php
+++ b/tests/fixtures.php
@@ -183,3 +183,61 @@ function gf_paystack_exception_message($callback)
return '';
}
+
+class GFPaystackSettingsFixture extends GFPaystack
+{
+ public $posted = array();
+ public $stored = array();
+ public $field_errors = array();
+ public $verdict = array('code' => 'ok', 'scopes' => array(), 'sensitive_scopes' => array(), 'reason' => null, 'probes' => 'transactions:read:200');
+ public $plans_result = 'ok';
+ public $validate_calls = array();
+ public $plans_calls = array();
+
+ public function get_posted_settings()
+ {
+ return $this->posted;
+ }
+
+ public function get_plugin_setting($name)
+ {
+ return rgar($this->stored, $name);
+ }
+
+ public function get_plugin_settings()
+ {
+ return $this->stored;
+ }
+
+ public function set_field_error($field, $message = '')
+ {
+ $this->field_errors[$field['name']] = $message;
+ }
+
+ public function is_detail_page()
+ {
+ return false;
+ }
+
+ public function get_current_feed_id()
+ {
+ return 0;
+ }
+
+ public function get_webhook_url($feed_id = null)
+ {
+ return 'https://example.test/?callback=gravityformspaystack';
+ }
+
+ protected function validate_restricted_key($key)
+ {
+ $this->validate_calls[] = $key;
+ return $this->verdict;
+ }
+
+ protected function probe_restricted_key_plans($key)
+ {
+ $this->plans_calls[] = $key;
+ return $this->plans_result;
+ }
+}
diff --git a/tests/stubs.php b/tests/stubs.php
index fa85f9d..532d74d 100644
--- a/tests/stubs.php
+++ b/tests/stubs.php
@@ -15,7 +15,8 @@ function add_filter()
if (!function_exists('apply_filters')) {
function apply_filters($tag, $value)
{
- return $value;
+ $overrides = isset($GLOBALS['gf_paystack_test_filters']) ? $GLOBALS['gf_paystack_test_filters'] : array();
+ return array_key_exists($tag, $overrides) ? $overrides[$tag] : $value;
}
}
@@ -33,6 +34,13 @@ function esc_html__($text, $domain = '')
}
}
+if (!function_exists('esc_html_e')) {
+ function esc_html_e($text, $domain = '')
+ {
+ echo $text;
+ }
+}
+
if (!function_exists('esc_html')) {
function esc_html($text)
{
@@ -165,6 +173,11 @@ public function log_error($message)
$GLOBALS['gf_paystack_test_gf_logs'][] = array('error', $message);
}
+ public function update_plugin_settings($settings)
+ {
+ $GLOBALS['gf_paystack_test_saved_settings'] = $settings;
+ }
+
public function get_plugin_settings()
{
return array();
diff --git a/tests/test-settings.php b/tests/test-settings.php
new file mode 100644
index 0000000..2b5b7b4
--- /dev/null
+++ b/tests/test-settings.php
@@ -0,0 +1,139 @@
+posted = $posted;
+ $addon->stored = $stored;
+ if ($configure) {
+ $configure($addon);
+ }
+ if ($mode === 'test') {
+ $addon->validate_test_secret_key(array());
+ } else {
+ $addon->validate_live_secret_key(array());
+ }
+
+ return $addon;
+};
+
+$a = $st_run('test', array('test_secret_key' => $st_sk_test), array('test_secret_key' => $st_sk_test));
+gf_paystack_test_check($a->field_errors === array() && $a->validate_calls === array(), 'settings unchanged sk saves');
+
+$a = $st_run('live', array('live_secret_key' => $st_sk_live), array());
+gf_paystack_test_check($a->field_errors === array() && $a->validate_calls === array(), 'settings new sk saves without probe');
+
+$a = $st_run('test', array('test_secret_key' => ' ' . $st_rk_test . ' ', 'test_webhook_secret' => $st_ws_test));
+gf_paystack_test_check($a->field_errors === array() && $a->validate_calls === array($st_rk_test), 'settings new rk with whsec probes trimmed key and saves');
+$logged = json_encode($GLOBALS['gf_paystack_test_gf_logs']);
+gf_paystack_test_check(strpos($logged, 'rk validate mode=test code=ok probes=transactions:read:200') !== false && strpos($logged, $st_rk_test) === false, 'settings probe log line never contains the key');
+
+$rk_posted = array('live_secret_key' => $st_rk_live, 'live_webhook_secret' => $st_ws_live);
+$verdict = function ($v) {
+ return function ($addon) use ($v) {
+ $addon->verdict = array_merge($addon->verdict, $v);
+ };
+};
+
+$a = $st_run('live', $rk_posted, array(), $verdict(array('code' => 'invalid_key')));
+gf_paystack_test_check(isset($a->field_errors['live_secret_key']) && strpos($a->field_errors['live_secret_key'], 'Paystack didn\'t accept this key.') === 0 && substr($a->field_errors['live_secret_key'], -strlen($st_suffix)) === $st_suffix, 'settings probe invalid_key error');
+
+$a = $st_run('live', $rk_posted, array(), $verdict(array('code' => 'missing_scope', 'scopes' => array('transactions:write'))));
+gf_paystack_test_check($a->field_errors['live_secret_key'] === 'This restricted key can\'t be used: enable Transactions: write. It needs Transactions: read and write. Permissions that can move money aren\'t allowed.' . $st_suffix, 'settings probe missing_scope copy');
+
+$a = $st_run('live', $rk_posted, array(), $verdict(array('code' => 'sensitive_scope', 'sensitive_scopes' => array('transfers', 'disputes_refunds'))));
+gf_paystack_test_check(strpos($a->field_errors['live_secret_key'], 'remove Transfers, Disputes and refunds.') !== false && strpos($a->field_errors['live_secret_key'], 'enable') === false, 'settings probe sensitive_scope copy');
+
+$a = $st_run('live', $rk_posted, array(), $verdict(array('code' => 'missing_scope', 'scopes' => array('transactions:read'), 'sensitive_scopes' => array('payouts'))));
+gf_paystack_test_check(strpos($a->field_errors['live_secret_key'], 'enable Transactions: read; remove Payouts.') !== false, 'settings probe missing and sensitive scope copy');
+
+$a = $st_run('live', $rk_posted, array(), $verdict(array('code' => 'unverifiable', 'reason' => 'blocked')));
+gf_paystack_test_check(strpos($a->field_errors['live_secret_key'], 'Paystack refused our check of this key.') === 0 && substr($a->field_errors['live_secret_key'], -strlen($st_suffix)) === $st_suffix, 'settings probe unverifiable blocked copy');
+
+$a = $st_run('live', $rk_posted, array(), $verdict(array('code' => 'unverifiable', 'reason' => 'transient')));
+gf_paystack_test_check(strpos($a->field_errors['live_secret_key'], 'We couldn\'t reach Paystack to check this key.') === 0 && substr($a->field_errors['live_secret_key'], -strlen($st_suffix)) === $st_suffix, 'settings probe unverifiable transient copy');
+
+$a = $st_run('test', array('test_secret_key' => $st_rk_test, 'test_webhook_secret' => ''));
+gf_paystack_test_check(isset($a->field_errors['test_webhook_secret']) && !isset($a->field_errors['test_secret_key']) && strpos($a->field_errors['test_webhook_secret'], 'Add your test webhook signing secret') !== false && substr($a->field_errors['test_webhook_secret'], -strlen($st_suffix)) === $st_suffix && $a->validate_calls === array(), 'settings rk without whsec errors on whsec field without probing');
+
+$a = $st_run('test', array('test_secret_key' => $st_rk_test, 'test_webhook_secret' => ''), array('test_secret_key' => $st_rk_test));
+gf_paystack_test_check(isset($a->field_errors['test_webhook_secret']), 'settings whsec cleared with unchanged rk errors');
+
+$a = $st_run('test', array('test_secret_key' => $st_rk_test, 'test_webhook_secret' => 'nope'), array('test_secret_key' => $st_rk_test));
+gf_paystack_test_check(strpos($a->field_errors['test_webhook_secret'], 'Webhook signing secrets start with whsec_.') === 0, 'settings bad whsec shape errors');
+
+$a = $st_run('live', array('live_secret_key' => $st_sk_live, 'live_webhook_secret' => $st_ws_live, 'test_webhook_secret' => $st_ws_live));
+gf_paystack_test_check(isset($a->field_errors['live_webhook_secret']) && strpos($a->field_errors['live_webhook_secret'], 'are the same') !== false, 'settings test==live whsec errors');
+
+$a = $st_run('live', array('live_secret_key' => $st_sk_test));
+gf_paystack_test_check($a->field_errors['live_secret_key'] === 'This is a test key. Paste it in the test secret key field.' . $st_suffix, 'settings wrong_field copy');
+
+$a = $st_run('test', array('test_secret_key' => 'garbage'));
+gf_paystack_test_check($a->field_errors['test_secret_key'] === 'Secret keys start with sk_test_ and restricted keys with rk_test_. Check you copied the whole key.' . $st_suffix, 'settings invalid_format copy');
+
+$GLOBALS['gf_paystack_test_filters'] = array('gform_paystack_restricted_keys_enabled' => false);
+$a = $st_run('live', $rk_posted);
+gf_paystack_test_check(isset($a->field_errors['live_secret_key']) && strpos($a->field_errors['live_secret_key'], 'Restricted keys are turned off on this site.') === 0 && $a->validate_calls === array(), 'settings gate off new rk rejected');
+
+$a = $st_run('live', $rk_posted, array('live_secret_key' => $st_rk_live));
+gf_paystack_test_check($a->field_errors === array() && $a->validate_calls === array(), 'settings gate off kept rk ok');
+unset($GLOBALS['gf_paystack_test_filters']);
+
+// Fields.
+$fa = new GFPaystackSettingsFixture();
+$by_name = array();
+foreach ($fa->api_settings_fields() as $f) {
+ $by_name[$f['name']] = $f;
+}
+$pw_ok = true;
+foreach (array('test_secret_key', 'live_secret_key', 'test_webhook_secret', 'live_webhook_secret') as $n) {
+ $pw_ok = $pw_ok && isset($by_name[$n]) && $by_name[$n]['input_type'] === 'password';
+}
+gf_paystack_test_check($pw_ok, 'settings secret and whsec fields are password inputs');
+$order = array_keys($by_name);
+gf_paystack_test_check(array_search('test_webhook_secret', $order) === array_search('test_secret_key', $order) + 1 && array_search('live_webhook_secret', $order) === array_search('live_secret_key', $order) + 1, 'settings whsec fields follow their secret key');
+gf_paystack_test_check($by_name['test_secret_key']['label'] === 'Test Secret or Restricted Key' && $by_name['live_webhook_secret']['label'] === 'Live Webhook Signing Secret' && strpos($by_name['live_secret_key']['tooltip'], 'A restricted key lets this plugin take payments and nothing else.') !== false, 'settings labels and help text');
+
+// Feed.
+$feed = function ($posted, $stored, $plans = 'ok') {
+ $addon = new GFPaystackSettingsFixture();
+ $addon->posted = $posted;
+ $addon->stored = $stored;
+ $addon->plans_result = $plans;
+ $addon->validate_subscription_plans(array());
+
+ return $addon;
+};
+
+$sub_test = array('transactionType' => 'subscription', 'mode' => 'test');
+$a = $feed($sub_test, array('test_secret_key' => $st_rk_test));
+gf_paystack_test_check($a->field_errors === array() && $a->plans_calls === array($st_rk_test), 'feed subscription rk plans ok');
+
+$a = $feed($sub_test, array('test_secret_key' => $st_rk_test), 'plans_missing');
+gf_paystack_test_check($a->field_errors['transactionType'] === 'Subscriptions need Plans: write on your test restricted key. Add it in your Paystack Dashboard, then save this feed again.', 'feed plans_missing copy');
+
+$a = $feed(array('transactionType' => 'subscription', 'mode' => 'live'), array('live_secret_key' => $st_rk_live), 'plans_mor');
+gf_paystack_test_check($a->field_errors['transactionType'] === 'Paystack subscriptions aren\'t available for merchant-of-record accounts.', 'feed plans_mor copy');
+
+$a = $feed($sub_test, array('test_secret_key' => $st_rk_test), 'unverifiable');
+gf_paystack_test_check(strpos($a->field_errors['transactionType'], 'We couldn\'t reach Paystack') === 0, 'feed plans unverifiable copy');
+
+$a = $feed($sub_test, array('test_secret_key' => $st_sk_test, 'live_secret_key' => $st_rk_live), 'plans_missing');
+gf_paystack_test_check($a->field_errors === array() && $a->plans_calls === array(), 'feed subscription sk no probe, other mode rk ignored');
+
+$a = $feed(array('transactionType' => 'product', 'mode' => 'test'), array('test_secret_key' => $st_rk_test), 'plans_missing');
+gf_paystack_test_check($a->field_errors === array() && $a->plans_calls === array(), 'feed product rk no probe');
+
+$GLOBALS['gf_paystack_test_saved_settings'] = null;
+$st_saver = new GFPaystackSettingsFixture();
+$st_saver->update_plugin_settings(array('test_secret_key' => " $st_rk_test\n", 'live_webhook_secret' => " $st_ws_live ", 'api_mode' => ' test '));
+$st_saved = $GLOBALS['gf_paystack_test_saved_settings'];
+gf_paystack_test_check($st_saved['test_secret_key'] === $st_rk_test && $st_saved['live_webhook_secret'] === $st_ws_live && $st_saved['api_mode'] === ' test ', 'settings save trims only credential fields');
From 053f673370de4e9f1c2c6aadb711a84e53ec2c9b Mon Sep 17 00:00:00 2001
From: Jules Nsenda
Date: Wed, 18 Nov 2026 21:01:45 +0200
Subject: [PATCH 08/19] fix: tighten restricted-key probe transport, budget and
redaction
Redaction no longer stops at characters a restricted key may contain, a
filter can't smuggle a second Authorization header into a probe, test and
live probes share one time budget per request, and scope labels live in the
probe table.
Co-Authored-By: Claude Opus 5.5
---
class-gf-paystack-api.php | 3 +-
includes/class-gf-paystack-keys.php | 2 +-
includes/class-gf-paystack-restricted-key.php | 70 ++++++++++++++-----
tests/test-keys.php | 3 +-
tests/test-restricted-key.php | 44 ++++++++++++
5 files changed, 101 insertions(+), 21 deletions(-)
diff --git a/class-gf-paystack-api.php b/class-gf-paystack-api.php
index 18ef7ff..a828cca 100644
--- a/class-gf-paystack-api.php
+++ b/class-gf-paystack-api.php
@@ -4,6 +4,7 @@
}
require_once __DIR__ . '/includes/class-gf-paystack-keys.php';
+require_once __DIR__ . '/includes/class-gf-paystack-restricted-key.php';
class GFPaystackApi
{
@@ -100,7 +101,7 @@ public function send_request(
error_log(GF_Paystack_Keys::redact(__METHOD__ . '(): ' . strtoupper($method) . ' ' . $uri . ' status: ' . (isset($body['status']) ? var_export($body['status'], true) : 'unknown')));
$code = isset($res['response']['code']) ? (int) $res['response']['code'] : 0;
- if ($code === 403 && isset($body['message']) && $body['message'] === 'This restricted key is not permitted to perform this action') {
+ if ($code === 403 && isset($body['message']) && $body['message'] === GF_Paystack_Restricted_Key::SCOPE_DENIED_MESSAGE) {
error_log(GF_Paystack_Keys::redact('rk scope denied method=' . strtoupper($method) . ' path=' . parse_url($uri, PHP_URL_PATH)));
}
diff --git a/includes/class-gf-paystack-keys.php b/includes/class-gf-paystack-keys.php
index a7a413f..c7e8857 100644
--- a/includes/class-gf-paystack-keys.php
+++ b/includes/class-gf-paystack-keys.php
@@ -9,7 +9,7 @@ final class GF_Paystack_Keys
const RK_SHAPE = '/^rk_(?:test|live)_[\x21-\x7e]{16,256}$/';
const WHSEC_SHAPE = '/^whsec_[A-Za-z0-9_]{16,}$/';
// A prefix glued to a word (`task_live_`) isn't a key, but one after a %XX escape (`secret%3Dsk_live_`) is.
- const REDACT_PATTERN = '/(?]+/';
+ const REDACT_PATTERN = '/(?\\\\]+/';
public static function type($key)
{
diff --git a/includes/class-gf-paystack-restricted-key.php b/includes/class-gf-paystack-restricted-key.php
index 738131e..87be077 100644
--- a/includes/class-gf-paystack-restricted-key.php
+++ b/includes/class-gf-paystack-restricted-key.php
@@ -17,23 +17,49 @@ class GF_Paystack_Restricted_Key
// Order matters: offending scopes are reported in it, and the baseline must stay first. Never add a write-capable route.
// present: '2xx' | '2xx_or_400' | '404_write'
const PROBES = array(
- array('scope' => 'transactions:read', 'type' => 'required', 'method' => 'GET', 'path' => 'transaction?perPage=1', 'body' => null, 'present' => '2xx'),
- array('scope' => 'transactions:write', 'type' => 'required', 'method' => 'POST', 'path' => 'transaction/check_authorization', 'body' => array(), 'present' => '404_write'),
- array('scope' => 'disputes_refunds', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'refund?perPage=1', 'body' => null, 'present' => '2xx_or_400'),
- array('scope' => 'bulk_charges', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'bulkcharge', 'body' => null, 'present' => '2xx_or_400'),
- array('scope' => 'direct_debit', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'directdebit/account', 'body' => null, 'present' => '2xx_or_400'),
- array('scope' => 'preauthorizations', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'preauthorization', 'body' => null, 'present' => '2xx_or_400'),
- array('scope' => 'settlements', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'settlement?perPage=1', 'body' => null, 'present' => '2xx_or_400'),
- array('scope' => 'subaccounts', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'subaccount', 'body' => null, 'present' => '2xx_or_400'),
- array('scope' => 'transfers', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'transfer/config', 'body' => null, 'present' => '2xx_or_400'),
- array('scope' => 'virtual_accounts', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'pay-with-transfer/custom-accounts/status', 'body' => null, 'present' => '2xx_or_400'),
- array('scope' => 'webhooks', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'integration/webhooks/events', 'body' => null, 'present' => '2xx_or_400'),
- array('scope' => 'connect', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'connect/platforms', 'body' => null, 'present' => '2xx_or_400'),
- array('scope' => 'payouts', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'settlement/instant/profile', 'body' => null, 'present' => '2xx_or_400'),
+ array('scope' => 'transactions:read', 'label' => 'Transactions: read', 'type' => 'required', 'method' => 'GET', 'path' => 'transaction?perPage=1', 'body' => null, 'present' => '2xx'),
+ array('scope' => 'transactions:write', 'label' => 'Transactions: write', 'type' => 'required', 'method' => 'POST', 'path' => 'transaction/check_authorization', 'body' => array(), 'present' => '404_write'),
+ array('scope' => 'disputes_refunds', 'label' => 'Disputes and refunds', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'refund?perPage=1', 'body' => null, 'present' => '2xx_or_400'),
+ array('scope' => 'bulk_charges', 'label' => 'Bulk charges', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'bulkcharge', 'body' => null, 'present' => '2xx_or_400'),
+ array('scope' => 'direct_debit', 'label' => 'Direct debit', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'directdebit/account', 'body' => null, 'present' => '2xx_or_400'),
+ array('scope' => 'preauthorizations', 'label' => 'Preauthorizations', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'preauthorization', 'body' => null, 'present' => '2xx_or_400'),
+ array('scope' => 'settlements', 'label' => 'Settlements', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'settlement?perPage=1', 'body' => null, 'present' => '2xx_or_400'),
+ array('scope' => 'subaccounts', 'label' => 'Subaccounts', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'subaccount', 'body' => null, 'present' => '2xx_or_400'),
+ array('scope' => 'transfers', 'label' => 'Transfers', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'transfer/config', 'body' => null, 'present' => '2xx_or_400'),
+ array('scope' => 'virtual_accounts', 'label' => 'Virtual accounts', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'pay-with-transfer/custom-accounts/status', 'body' => null, 'present' => '2xx_or_400'),
+ array('scope' => 'webhooks', 'label' => 'Webhooks', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'integration/webhooks/events', 'body' => null, 'present' => '2xx_or_400'),
+ array('scope' => 'connect', 'label' => 'Connect', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'connect/platforms', 'body' => null, 'present' => '2xx_or_400'),
+ array('scope' => 'payouts', 'label' => 'Payouts', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'settlement/instant/profile', 'body' => null, 'present' => '2xx_or_400'),
);
- // Overridable so tests can exhaust it without sleeping.
+ // Total across every validate()/probe_plans() call in a request; overridable so tests can exhaust it without sleeping.
protected static $budget_seconds = 15.0;
+ protected static $deadline = null;
+
+ public static function reset_budget()
+ {
+ self::$deadline = null;
+ }
+
+ public static function scope_label($scope)
+ {
+ foreach (self::PROBES as $probe) {
+ if ($probe['scope'] === $scope) {
+ return $probe['label'];
+ }
+ }
+
+ return $scope;
+ }
+
+ private static function budget_left()
+ {
+ if (self::$deadline === null) {
+ self::$deadline = microtime(true) + static::$budget_seconds;
+ }
+
+ return microtime(true) < self::$deadline;
+ }
public static function validate($key, $request = null)
{
@@ -42,12 +68,11 @@ public static function validate($key, $request = null)
$request = array(__CLASS__, 'default_request');
}
- $start = microtime(true);
$results = array();
$baseline = null;
foreach (self::PROBES as $index => $probe) {
- if (microtime(true) - $start >= static::$budget_seconds) {
+ if (!self::budget_left()) {
$results[] = array('probe' => $probe, 'outcome' => 'indeterminate', 'status' => 0, 'ran' => false);
break;
}
@@ -77,6 +102,10 @@ public static function probe_plans($key, $request = null)
$request = array(__CLASS__, 'default_request');
}
+ if (!self::budget_left()) {
+ return 'unverifiable';
+ }
+
$response = self::send($request, $key, 'POST', 'plan', array());
if ($response['status'] === 400) {
return 'ok';
@@ -118,11 +147,16 @@ public static function default_request($method, $url, $headers, $body)
private static function send($request, $key, $method, $path, $body)
{
- // Authorization is forced last so a filter can't swap or drop the key under test.
- $headers = apply_filters('gf_paystack_request_headers', array('Content-Type' => 'application/json'));
+ $headers = apply_filters('gf_paystack_request_headers', array('Authorization' => 'Bearer ' . $key, 'Content-Type' => 'application/json'));
if (!is_array($headers)) {
$headers = array();
}
+ // Header names are case-insensitive, so a filter's differently-cased Authorization must not survive alongside ours.
+ foreach (array_keys($headers) as $name) {
+ if (preg_match('/^authorization$/i', (string) $name)) {
+ unset($headers[$name]);
+ }
+ }
$headers['Authorization'] = 'Bearer ' . $key;
try {
diff --git a/tests/test-keys.php b/tests/test-keys.php
index 6fe1848..e240dc1 100644
--- a/tests/test-keys.php
+++ b/tests/test-keys.php
@@ -47,7 +47,8 @@
$keys_redact_cases = array(
'punctuation rk' => array('key rk_live_ab-c.d~e!f_g tail', 'key rk_live_[redacted] tail'),
'base64 whsec' => array('whsec_ab+/cd==ef rest', 'whsec_[redacted] rest'),
- 'query string' => array('x=1&secret=sk_live_abc&y=2', 'x=1&secret=sk_live_[redacted]&y=2'),
+ 'query string' => array('x=1&secret=sk_live_abc&y=2', 'x=1&secret=sk_live_[redacted]'),
+ 'rk with &,; chars' => array('k=rk_live_ab&cd,ef;gh_ijklmnop tail', 'k=rk_live_[redacted] tail'),
'json escaped' => array('{"key":"rk_live_abc123"}', '{"key":"rk_live_[redacted]"}'),
'url encoded' => array('secret%3Dsk_live_abc%26y', 'secret%3Dsk_live_[redacted]'),
'pk' => array('pk_test_abc123', 'pk_test_[redacted]'),
diff --git a/tests/test-restricted-key.php b/tests/test-restricted-key.php
index 7c25c09..e99e02a 100644
--- a/tests/test-restricted-key.php
+++ b/tests/test-restricted-key.php
@@ -16,6 +16,7 @@ class GF_Paystack_Restricted_Key_Zero extends GF_Paystack_Restricted_Key
}
}
+GF_Paystack_Restricted_Key::reset_budget();
$rk_key = 'rk_live_' . str_repeat('Zq9', 10);
$scope_msg = 'This restricted key is not permitted to perform this action';
$write_msg = 'Sorry, this feature is no longer available.';
@@ -52,6 +53,11 @@ class GF_Paystack_Restricted_Key_Zero extends GF_Paystack_Restricted_Key
$scope_list[] = $p['scope'];
}
gf_paystack_test_check($scope_list === $rk_expected_scopes, 'rk probe table scope list and order pinned');
+$labels_ok = true;
+foreach (GF_Paystack_Restricted_Key::PROBES as $p) {
+ $labels_ok = $labels_ok && isset($p['label']) && is_string($p['label']) && $p['label'] !== '' && GF_Paystack_Restricted_Key::scope_label($p['scope']) === $p['label'];
+}
+gf_paystack_test_check($labels_ok && GF_Paystack_Restricted_Key::scope_label('payouts') === 'Payouts' && GF_Paystack_Restricted_Key::scope_label('unknown') === 'unknown', 'rk every probe has a label and scope_label falls back to the raw scope');
gf_paystack_test_check(GF_Paystack_Restricted_Key::PROBES[1]['path'] === 'transaction/check_authorization' && GF_Paystack_Restricted_Key::PROBES[1]['method'] === 'POST', 'rk write probe route pinned');
$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make($rk_ok_map, array(403, $scope_msg), $log));
@@ -112,6 +118,7 @@ class GF_Paystack_Restricted_Key_Zero extends GF_Paystack_Restricted_Key
});
gf_paystack_test_check($v['code'] === 'unverifiable', 'rk malformed response is unverifiable');
+GF_Paystack_Restricted_Key::reset_budget();
$calls = 0;
$v = GF_Paystack_Restricted_Key_Zero::validate($rk_key, function () use (&$calls) {
$calls++;
@@ -120,6 +127,14 @@ class GF_Paystack_Restricted_Key_Zero extends GF_Paystack_Restricted_Key
});
gf_paystack_test_check($v['code'] === 'unverifiable' && $v['reason'] === 'transient' && $calls === 0 && $v['probes'] === '-', 'rk exhausted budget stops before any probe');
+GF_Paystack_Restricted_Key::reset_budget();
+gf_paystack_test_check(GF_Paystack_Restricted_Key_Zero::probe_plans($rk_key, function () use (&$calls) {
+ $calls++;
+
+ return array('status' => 400, 'body' => null);
+}) === 'unverifiable' && $calls === 0, 'rk probe_plans after exhausted budget is unverifiable without a request');
+
+GF_Paystack_Restricted_Key::reset_budget();
$slow = $rk_make($rk_ok_map, array(403, $scope_msg), $log);
$v = GF_Paystack_Restricted_Key_Spent::validate($rk_key, function ($m, $u, $h, $b) use ($slow) {
usleep(30000);
@@ -128,6 +143,24 @@ class GF_Paystack_Restricted_Key_Zero extends GF_Paystack_Restricted_Key
});
gf_paystack_test_check($v['code'] === 'unverifiable' && $v['reason'] === 'transient' && strpos($v['probes'], 'transactions:read:200') === 0, 'rk budget exhausted mid-run is unverifiable transient');
+// Budget is shared across calls: a second validate() in the same request gets what the first left.
+GF_Paystack_Restricted_Key::reset_budget();
+$slow_ok = function ($m, $u, $h, $b) use ($rk_make, $rk_ok_map, $scope_msg) {
+ usleep(30000);
+ $f = $rk_make($rk_ok_map, array(403, $scope_msg));
+
+ return $f($m, $u, $h, $b);
+};
+GF_Paystack_Restricted_Key_Spent::validate($rk_key, $slow_ok);
+$calls = 0;
+$v = GF_Paystack_Restricted_Key_Spent::validate($rk_key, function () use (&$calls) {
+ $calls++;
+
+ return array('status' => 200, 'body' => null);
+});
+gf_paystack_test_check($v['code'] === 'unverifiable' && $v['reason'] === 'transient' && $calls === 0, 'rk second validate shares the exhausted budget');
+GF_Paystack_Restricted_Key::reset_budget();
+
// probe_plans
$plan = function ($status, $message = null) {
return function ($method, $url, $headers, $body) use ($status, $message) {
@@ -169,3 +202,14 @@ class GF_Paystack_Restricted_Key_Zero extends GF_Paystack_Restricted_Key
$GLOBALS['gf_paystack_test_remote_response'] = new WP_Error('http', 'down');
$v = GF_Paystack_Restricted_Key::validate($rk_key);
gf_paystack_test_check($v['code'] === 'unverifiable' && $v['reason'] === 'transient' && count($GLOBALS['gf_paystack_test_remote_calls']) === 1 && strpos($v['probes'], $rk_key) === false, 'rk wp_error maps to status 0');
+
+$GLOBALS['gf_paystack_test_remote_calls'] = array();
+$GLOBALS['gf_paystack_test_remote_response'] = array('response' => array('code' => 403), 'body' => json_encode(array('message' => $scope_msg)));
+$GLOBALS['gf_paystack_test_filters']['gf_paystack_request_headers'] = array('Authorization' => 'Bearer other', 'authorization' => 'Bearer other', 'X-Extra' => '1');
+GF_Paystack_Restricted_Key::validate($rk_key);
+$sent_headers = $GLOBALS['gf_paystack_test_remote_calls'][0][1]['headers'];
+unset($GLOBALS['gf_paystack_test_filters']['gf_paystack_request_headers']);
+$auth_keys = array_filter(array_keys($sent_headers), function ($k) {
+ return strtolower($k) === 'authorization';
+});
+gf_paystack_test_check(count($auth_keys) === 1 && $sent_headers['Authorization'] === 'Bearer ' . $rk_key && $sent_headers['X-Extra'] === '1', 'rk probe headers keep a single Authorization with the saved key');
From c9a94c880442505f0d5ffc57109f32ac551ccd43 Mon Sep 17 00:00:00 2001
From: Jules Nsenda
Date: Wed, 18 Nov 2026 21:01:45 +0200
Subject: [PATCH 09/19] fix: harden payment re-verify, webhook mode fallback
and settings checks
- A verify call that throws during charge.success answers 500 so Paystack
retries; both branches now require the verified id and reference to match.
- An event without data.domain only tries modes with a signing secret, and
otherwise keeps the original api_mode fallback; failures log every attempt.
- The admin ?secret=/?public= URL override no longer reaches Paystack calls.
- Signing-secret fields validate themselves; switching a mode to a restricted
key also checks Plans: write when that mode has active subscription feeds;
subscription feeds are only re-probed when their type or mode changes, and
keep Gravity Forms' own transaction type check.
Co-Authored-By: Claude Opus 5.5
---
class-gf-paystack.php | 245 +++++++++++++++++++++++++---------------
tests/fixtures.php | 14 +++
tests/run.php | 8 ++
tests/stubs.php | 102 ++++++++++++++++-
tests/test-gateway.php | 2 +-
tests/test-settings.php | 161 ++++++++++++++++++++++++--
tests/test-webhook.php | 59 +++++++++-
7 files changed, 490 insertions(+), 101 deletions(-)
diff --git a/class-gf-paystack.php b/class-gf-paystack.php
index 746a477..70c3921 100644
--- a/class-gf-paystack.php
+++ b/class-gf-paystack.php
@@ -34,6 +34,8 @@ class GFPaystack extends GFPaymentAddOn
/** @var string|null */
protected $webhook_mode = null;
+ protected $transaction_type_callback = null;
+
/**
* Defines the version of the Paystack Add-On.
*
@@ -325,7 +327,7 @@ public function api_settings_fields()
)
);
- $key_help = '' . esc_html__('Secret or Restricted Key', 'gravityformspaystack') . '
' . esc_html__('A restricted key lets this plugin take payments and nothing else. Create one in your Paystack Dashboard with Transactions: read and write, plus Plans: write if you sell subscriptions.', 'gravityformspaystack');
+ $key_help = '' . esc_html__('Secret or Restricted Key', 'gravityformspaystack') . '
' . esc_html__('A restricted key limits what this plugin can do with your Paystack account. Create one in your Paystack Dashboard with Transactions: read and write, plus Plans: write if you sell subscriptions.', 'gravityformspaystack');
$whsec_help = '' . esc_html__('Webhook Signing Secret', 'gravityformspaystack') . '
' . esc_html__('Copy it from Settings → API Keys & Webhooks in your Paystack Dashboard. Required with a restricted key.', 'gravityformspaystack');
$credentials_fields = array(
@@ -351,6 +353,7 @@ public function api_settings_fields()
'input_type' => 'password',
'class' => 'medium',
'tooltip' => $whsec_help,
+ 'validation_callback' => array($this, 'validate_test_webhook_secret'),
),
array(
'name' => 'live_public_key',
@@ -374,6 +377,7 @@ public function api_settings_fields()
'input_type' => 'password',
'class' => 'medium',
'tooltip' => $whsec_help,
+ 'validation_callback' => array($this, 'validate_live_webhook_secret'),
),
);
@@ -485,6 +489,7 @@ public function feed_settings_fields()
$transaction_type = $this->get_field('transactionType', $default_settings);
if (is_array($transaction_type)) {
+ $this->transaction_type_callback = rgar($transaction_type, 'validation_callback', null);
$transaction_type['validation_callback'] = array($this, 'validate_subscription_plans');
$default_settings = $this->replace_field('transactionType', $transaction_type, $default_settings);
}
@@ -1346,42 +1351,40 @@ public function callback()
return false;
}
- if ($feed['meta']['transactionType'] == 'subscription') {
- gform_update_meta($entry_id, 'paystack_tx_auth_code', rgars($event, 'data/authorization/authorization_code'));
- } else {
- try {
- $response = $this->paystack_api->verify_transaction($reference);
- } catch (\Exception $e) {
- $this->log_error(__METHOD__ . '(): Transaction could not be verified. Reason: ' . $e->getMessage());
-
- return false;
- }
+ try {
+ $response = $this->paystack_api->verify_transaction($reference);
+ } catch (\Exception $e) {
+ $this->log_error(__METHOD__ . '(): Transaction could not be verified. Reason: ' . $e->getMessage());
- $charge = rgar($response, 'data');
+ return new WP_Error('transaction_verification', $e->getMessage(), array('status_header' => 500));
+ }
- if (!is_array($charge) || rgar($charge, 'status') !== 'success') {
- $this->log_error(__METHOD__ . '(): Transaction verification failed. Aborting.');
+ $charge = rgar($response, 'data');
- return false;
- }
+ if (!is_array($charge) || rgar($charge, 'status') !== 'success') {
+ $this->log_error(__METHOD__ . '(): Transaction verification failed. Aborting.');
- $verified_id = rgar($charge, 'id');
+ return false;
+ }
- if ($verified_id && (string) $verified_id !== (string) rgars($event, 'data/id')) {
- $this->log_error(__METHOD__ . '(): Verified transaction does not match the webhook event. Aborting.');
+ if ((string) rgar($charge, 'id') !== (string) rgars($event, 'data/id') || rgar($charge, 'reference') !== $reference) {
+ $this->log_error(__METHOD__ . '(): Verified transaction does not match the webhook event. Aborting.');
- return false;
- }
+ return false;
+ }
+ if ($feed['meta']['transactionType'] == 'subscription') {
+ gform_update_meta($entry_id, 'paystack_tx_auth_code', rgars($charge, 'authorization/authorization_code'));
+ } else {
if (!self::charge_matches_stored(rgar($charge, 'amount'), rgar($charge, 'currency'), gform_get_meta($entry_id, 'paystack_tx_amount'), gform_get_meta($entry_id, 'paystack_tx_currency'))) {
$this->log_error(__METHOD__ . '(): Webhook could not be matched to entry. Aborting.');
return false;
}
- $action['id'] = rgars($event, 'data/id') . '_' . $type;
+ $action['id'] = rgar($charge, 'id') . '_' . $type;
$action['entry_id'] = $entry_id;
- $action['transaction_id'] = rgars($event, 'data/id');
+ $action['transaction_id'] = rgar($charge, 'id');
$action['amount'] = $this->get_amount_import(rgar($charge, 'amount'), rgar($charge, 'currency'));
$action['type'] = 'complete_payment';
$action['ready_to_fulfill'] = !$entry['is_fulfilled'] ? true : false;
@@ -1765,20 +1768,19 @@ public function get_webhook_event($body = null)
} else {
$candidates = array();
foreach (array('live', 'test') as $candidate_mode) {
- if ($this->get_webhook_secret($candidate_mode, $settings) !== ''
- || GF_Paystack_Keys::type($this->get_stored_secret_key($candidate_mode, $settings)) === 'sk') {
+ if ($this->get_webhook_secret($candidate_mode, $settings) !== '') {
$candidates[] = $candidate_mode;
}
}
}
- // No usable mode still runs the check once so the failure is logged like any other.
if (empty($candidates)) {
$candidates = array($this->get_api_mode($settings));
}
$check = null;
$mode = null;
+ $attempts = array();
foreach ($candidates as $candidate_mode) {
$this->paystack_api($candidate_mode, $settings);
@@ -1793,6 +1795,7 @@ public function get_webhook_event($body = null)
$check = $this->paystack_api->last_webhook_check;
$mode = $candidate_mode;
+ $attempts[] = $candidate_mode . ':' . rgar($check, 'sig') . ':' . rgar($check, 'result');
if ($is_verified) {
break;
@@ -1803,10 +1806,9 @@ public function get_webhook_event($body = null)
if (!$is_verified) {
$this->log_error(sprintf(
- '%s(): Webhook request is invalid. Aborting. sig=%s result=%s',
+ '%s(): Webhook request is invalid. Aborting. checks=%s',
__METHOD__,
- rgar($check, 'sig'),
- rgar($check, 'result')
+ implode(',', $attempts)
));
return false;
@@ -2111,29 +2113,66 @@ public function validate_live_secret_key($field)
$this->validate_secret_key_for_mode('live');
}
+ public function validate_test_webhook_secret($field)
+ {
+ $this->validate_webhook_secret_for_mode('test');
+ }
+
+ public function validate_live_webhook_secret($field)
+ {
+ $this->validate_webhook_secret_for_mode('live');
+ }
+
/**
* @param string $mode 'test' or 'live'.
*
- * @return void
+ * @return array A GF_Paystack_Keys::resolve_save() result.
*/
- protected function validate_secret_key_for_mode($mode)
+ protected function resolve_posted_key($mode)
{
$other = $mode === 'test' ? 'live' : 'test';
$settings = $this->get_posted_settings();
- $key = trim((string) rgar($settings, "{$mode}_secret_key"));
- $result = GF_Paystack_Keys::resolve_save(
+ return GF_Paystack_Keys::resolve_save(
$mode,
- $key,
+ trim((string) rgar($settings, "{$mode}_secret_key")),
$this->get_plugin_setting("{$mode}_secret_key"),
rgar($settings, "{$mode}_webhook_secret"),
rgar($settings, "{$other}_webhook_secret"),
GF_Paystack_Keys::restricted_keys_enabled()
);
+ }
+
+ /**
+ * @param string $mode 'test' or 'live'.
+ *
+ * @return void
+ */
+ protected function validate_webhook_secret_for_mode($mode)
+ {
+ $result = $this->resolve_posted_key($mode);
+
+ if ($result['error'] !== null && strpos($result['error'], 'whsec_') === 0) {
+ $other = $mode === 'test' ? 'live' : 'test';
+ $this->set_field_error(array('name' => "{$mode}_webhook_secret"), $this->key_error_message($result['error'], $mode, $other) . $this->not_saved_suffix());
+ }
+ }
+
+ /**
+ * @param string $mode 'test' or 'live'.
+ *
+ * @return void
+ */
+ protected function validate_secret_key_for_mode($mode)
+ {
+ $other = $mode === 'test' ? 'live' : 'test';
+ $key = trim((string) rgar($this->get_posted_settings(), "{$mode}_secret_key"));
+ $result = $this->resolve_posted_key($mode);
if ($result['error'] !== null) {
- $field_name = strpos($result['error'], 'whsec_') === 0 ? "{$mode}_webhook_secret" : "{$mode}_secret_key";
- $this->set_field_error(array('name' => $field_name), $this->key_error_message($result['error'], $mode, $other) . $this->not_saved_suffix());
+ if (strpos($result['error'], 'whsec_') !== 0) {
+ $this->set_field_error(array('name' => "{$mode}_secret_key"), $this->key_error_message($result['error'], $mode, $other) . $this->not_saved_suffix());
+ }
return;
}
@@ -2146,9 +2185,43 @@ protected function validate_secret_key_for_mode($mode)
if ($verdict['code'] !== 'ok') {
$this->set_field_error(array('name' => "{$mode}_secret_key"), $this->probe_error_message($verdict) . $this->not_saved_suffix());
+ return;
+ }
+
+ if ($this->has_active_subscription_feed($mode)) {
+ $plans = $this->probe_restricted_key_plans($key);
+ if ($plans !== 'ok') {
+ $this->set_field_error(array('name' => "{$mode}_secret_key"), $this->plans_error_message($plans, $mode) . $this->not_saved_suffix());
+ }
}
}
+ /**
+ * @param string $mode 'test' or 'live'.
+ *
+ * @return bool
+ */
+ protected function has_active_subscription_feed($mode)
+ {
+ foreach ((array) $this->get_feeds() as $feed) {
+ if (rgar($feed, 'is_active') && rgars($feed, 'meta/transactionType') === 'subscription' && $this->feed_mode($feed) === $mode) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * @param array|false $feed
+ *
+ * @return string 'test' or 'live'; feeds default to live.
+ */
+ protected function feed_mode($feed)
+ {
+ return rgars($feed, 'meta/mode') === 'test' ? 'test' : 'live';
+ }
+
/**
* @param string $key
*
@@ -2172,37 +2245,70 @@ protected function probe_restricted_key_plans($key)
/**
* Subscription feeds need Plans: write, which the settings probe doesn't check.
*
- * @param array $field The field properties. Not used.
+ * @param array $field The transactionType field properties.
*
* @return void
*/
public function validate_subscription_plans($field)
{
+ if (is_callable($this->transaction_type_callback)) {
+ call_user_func($this->transaction_type_callback, $field);
+ }
+
$settings = $this->get_posted_settings();
- if (rgar($settings, 'transactionType') !== 'subscription') {
+ $type = rgar($settings, 'transactionType');
+
+ $allowed = array('product', 'subscription');
+ if (is_array(rgar($field, 'choices'))) {
+ $allowed = array();
+ foreach ($field['choices'] as $choice) {
+ $allowed[] = isset($choice['value']) ? $choice['value'] : rgar($choice, 'name');
+ }
+ }
+
+ if (!is_string($type) || $type === '' || !in_array($type, $allowed, true)) {
+ $this->set_field_error(array('name' => 'transactionType'), esc_html__('This field is required.', 'gravityformspaystack'));
return;
}
- $mode = rgar($settings, 'mode') === 'test' ? 'test' : 'live';
- $key = $this->get_stored_secret_key($mode);
+ if ($type !== 'subscription') {
+ return;
+ }
+
+ $mode = $this->feed_mode(array('meta' => $settings));
+ $current = $this->get_current_feed();
+ if (is_array($current) && rgars($current, 'meta/transactionType') === $type && $this->feed_mode($current) === $mode) {
+ return;
+ }
+
+ $key = $this->get_stored_secret_key($mode);
if (GF_Paystack_Keys::type($key) !== 'rk') {
return;
}
$result = $this->probe_restricted_key_plans($key);
- if ($result === 'ok') {
- return;
+ if ($result !== 'ok') {
+ $this->set_field_error(array('name' => 'transactionType'), $this->plans_error_message($result, $mode));
}
+ }
+ /**
+ * @param string $result A probe_plans() code other than 'ok'.
+ * @param string $mode 'test' or 'live'.
+ *
+ * @return string
+ */
+ protected function plans_error_message($result, $mode)
+ {
if ($result === 'plans_missing') {
- $message = sprintf(esc_html__('Subscriptions need Plans: write on your %s restricted key. Add it in your Paystack Dashboard, then save this feed again.', 'gravityformspaystack'), $mode);
- } elseif ($result === 'plans_mor') {
- $message = esc_html__('Paystack subscriptions aren\'t available for merchant-of-record accounts.', 'gravityformspaystack');
- } else {
- $message = esc_html__('We couldn\'t reach Paystack to check this key. Please try again.', 'gravityformspaystack');
+ return sprintf(esc_html__('Subscriptions need Plans: write on your %s restricted key. Add it in your Paystack Dashboard, then save this feed again.', 'gravityformspaystack'), $mode);
+ }
+
+ if ($result === 'plans_mor') {
+ return esc_html__('Paystack subscriptions aren\'t available for merchant-of-record accounts.', 'gravityformspaystack');
}
- $this->set_field_error(array('name' => 'transactionType'), $message);
+ return esc_html__('We couldn\'t reach Paystack to check this key. Please try again.', 'gravityformspaystack');
}
/**
@@ -2259,7 +2365,7 @@ protected function probe_error_message($verdict)
if (!empty($verdict['sensitive_scopes'])) {
$parts[] = sprintf(esc_html__('remove %s', 'gravityformspaystack'), $this->scope_labels($verdict['sensitive_scopes']));
}
- return sprintf(esc_html__('This restricted key can\'t be used: %s. It needs Transactions: read and write. Permissions that can move money aren\'t allowed.', 'gravityformspaystack'), implode('; ', $parts));
+ return sprintf(esc_html__('This restricted key can\'t be used: %s. It needs Transactions: read and write. Permissions such as transfers, refunds, settlements and payouts aren\'t allowed.', 'gravityformspaystack'), implode('; ', $parts));
}
if ($verdict['reason'] === 'blocked') {
@@ -2276,25 +2382,9 @@ protected function probe_error_message($verdict)
*/
protected function scope_labels($scopes)
{
- $labels = array(
- 'transactions:read' => 'Transactions: read',
- 'transactions:write' => 'Transactions: write',
- 'disputes_refunds' => 'Disputes and refunds',
- 'bulk_charges' => 'Bulk charges',
- 'direct_debit' => 'Direct debit',
- 'preauthorizations' => 'Preauthorizations',
- 'settlements' => 'Settlements',
- 'subaccounts' => 'Subaccounts',
- 'transfers' => 'Transfers',
- 'virtual_accounts' => 'Virtual accounts',
- 'webhooks' => 'Webhooks',
- 'connect' => 'Connect',
- 'payouts' => 'Payouts',
- );
-
$out = array();
foreach ($scopes as $scope) {
- $out[] = isset($labels[$scope]) ? $labels[$scope] : $scope;
+ $out[] = GF_Paystack_Restricted_Key::scope_label($scope);
}
return implode(', ', $out);
@@ -2309,7 +2399,6 @@ protected function scope_labels($scopes)
*
* @used-by GFPaystack::get_public_api_key()
* @used-by GFPaystack::get_secret_api_key()
- * @uses GFPaystack::get_query_string_api_key()
* @uses GFAddOn::get_plugin_settings()
* @uses GFPaystack::get_api_mode()
* @uses GFAddOn::get_setting()
@@ -2322,12 +2411,6 @@ protected function scope_labels($scopes)
*/
public function get_api_key($type = 'secret', $mode = null, $settings = null)
{
- // Check for api key in query first; user must be an administrator to use this feature.
- $api_key = $this->get_query_string_api_key($type);
- if ($api_key && current_user_can('update_core')) {
- return $api_key;
- }
-
if (!isset($settings)) {
$settings = $this->get_plugin_settings();
@@ -2372,22 +2455,6 @@ public function get_api_mode($settings, $feed_id = null)
return apply_filters('gform_paystack_api_mode', $api_mode, $feed_id);
}
- /**
- * Retrieve the specified api key from the query string.
- *
- * @access public
- *
- * @used-by GFPaystack::get_api_key()
- *
- * @param string $type The type of key to retrieve. Defaults to 'secret'.
- *
- * @return string The result of the query string.
- */
- public function get_query_string_api_key($type)
- {
- return rgget($type);
- }
-
/**
* Retrieve the public api key.
*
diff --git a/tests/fixtures.php b/tests/fixtures.php
index 5930eec..bf06d19 100644
--- a/tests/fixtures.php
+++ b/tests/fixtures.php
@@ -193,6 +193,19 @@ class GFPaystackSettingsFixture extends GFPaystack
public $plans_result = 'ok';
public $validate_calls = array();
public $plans_calls = array();
+ public $feeds = array();
+ public $current_feed = false;
+ public $error_log = array();
+
+ public function get_feeds($form_id = null)
+ {
+ return $this->feeds;
+ }
+
+ public function get_current_feed()
+ {
+ return $this->current_feed;
+ }
public function get_posted_settings()
{
@@ -212,6 +225,7 @@ public function get_plugin_settings()
public function set_field_error($field, $message = '')
{
$this->field_errors[$field['name']] = $message;
+ $this->error_log[] = $field['name'];
}
public function is_detail_page()
diff --git a/tests/run.php b/tests/run.php
index aa3a5ec..2b62826 100644
--- a/tests/run.php
+++ b/tests/run.php
@@ -25,6 +25,14 @@ function gf_paystack_test_check($condition, $label)
$test_files = glob(__DIR__ . '/test-*.php');
sort($test_files);
foreach ($test_files as $test_file) {
+ $GLOBALS['gf_paystack_test_filters'] = array();
+ if (class_exists('GF_Paystack_Restricted_Key')) {
+ GF_Paystack_Restricted_Key::reset_budget();
+ }
+ $GLOBALS['gf_paystack_test_gf_logs'] = array();
+ $GLOBALS['gf_paystack_test_saved_settings'] = null;
+ $_GET = array();
+ unset($_SERVER['HTTP_PAYSTACK_SIGNATURE'], $_SERVER['HTTP_X_PAYSTACK_SIGNATURE']);
require $test_file;
}
diff --git a/tests/stubs.php b/tests/stubs.php
index 532d74d..d5c6cea 100644
--- a/tests/stubs.php
+++ b/tests/stubs.php
@@ -187,6 +187,99 @@ public function get_setting($setting_name, $default_value = '', $settings = null
{
return rgar($settings, $setting_name, $default_value);
}
+
+ public function get_feeds($form_id = null)
+ {
+ return array();
+ }
+
+ public function get_current_feed()
+ {
+ return false;
+ }
+
+ public function feed_settings_fields()
+ {
+ return array(
+ array(
+ 'title' => 'Feed Settings',
+ 'fields' => array(
+ array('name' => 'feedName', 'type' => 'text'),
+ array(
+ 'name' => 'transactionType',
+ 'type' => 'select',
+ 'choices' => array(
+ array('label' => 'Products and Services', 'value' => 'product'),
+ array('label' => 'Subscription', 'value' => 'subscription'),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ public function get_field($name, $fields)
+ {
+ foreach ($fields as $section) {
+ foreach (rgar($section, 'fields', array()) as $field) {
+ if (rgar($field, 'name') === $name) {
+ return $field;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ public function replace_field($name, $new_field, $fields)
+ {
+ foreach ($fields as $i => $section) {
+ foreach (rgar($section, 'fields', array()) as $j => $field) {
+ if (rgar($field, 'name') === $name) {
+ $fields[$i]['fields'][$j] = $new_field;
+ }
+ }
+ }
+
+ return $fields;
+ }
+
+ public function add_field_after($name, $new_fields, $fields)
+ {
+ return $this->insert_fields($name, $new_fields, $fields, 1);
+ }
+
+ public function add_field_before($name, $new_fields, $fields)
+ {
+ return $this->insert_fields($name, $new_fields, $fields, 0);
+ }
+
+ public function remove_field($name, $fields)
+ {
+ foreach ($fields as $i => $section) {
+ foreach (rgar($section, 'fields', array()) as $j => $field) {
+ if (rgar($field, 'name') === $name) {
+ array_splice($fields[$i]['fields'], $j, 1);
+ }
+ }
+ }
+
+ return $fields;
+ }
+
+ private function insert_fields($name, $new_fields, $fields, $offset)
+ {
+ foreach ($fields as $i => $section) {
+ foreach (rgar($section, 'fields', array()) as $j => $field) {
+ if (rgar($field, 'name') === $name) {
+ array_splice($fields[$i]['fields'], $j + $offset, 0, isset($new_fields['name']) ? array($new_fields) : $new_fields);
+ return $fields;
+ }
+ }
+ }
+
+ return $fields;
+ }
}
}
@@ -195,11 +288,18 @@ class WP_Error
{
public $code;
public $message;
+ public $data;
- public function __construct($code = '', $message = '')
+ public function __construct($code = '', $message = '', $data = '')
{
$this->code = $code;
$this->message = $message;
+ $this->data = $data;
+ }
+
+ public function get_error_data()
+ {
+ return $this->data;
}
public function get_error_message()
diff --git a/tests/test-gateway.php b/tests/test-gateway.php
index 9ad74b9..5a1c346 100644
--- a/tests/test-gateway.php
+++ b/tests/test-gateway.php
@@ -97,7 +97,7 @@
$_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] = hash_hmac('sha512', '', 'sk_live_a');
$event_result = $event_addon->get_webhook_event();
-gf_paystack_test_check($event_addon->webhook_mode_value() === 'live' && $event_result !== false && !is_wp_error($event_result), 'get_webhook_event case 2: no domain verifies under the mode whose key signed it');
+gf_paystack_test_check($event_addon->webhook_mode_value() === 'test' && $event_result === false, 'get_webhook_event case 2');
$event_addon->settings['api_mode'] = 'live';
$event_result = $event_addon->get_webhook_event();
diff --git a/tests/test-settings.php b/tests/test-settings.php
index 2b5b7b4..3113d3c 100644
--- a/tests/test-settings.php
+++ b/tests/test-settings.php
@@ -8,7 +8,7 @@
$st_ws_live = 'whsec_' . str_repeat('b2', 16);
$st_suffix = ' No settings were saved.';
-$st_run = function ($mode, $posted, $stored = array(), $configure = null) {
+$st_run = function ($mode, $posted, $stored = array(), $configure = null, $which = 'both') {
$GLOBALS['gf_paystack_test_gf_logs'] = array();
$addon = new GFPaystackSettingsFixture();
$addon->posted = $posted;
@@ -16,10 +16,11 @@
if ($configure) {
$configure($addon);
}
- if ($mode === 'test') {
- $addon->validate_test_secret_key(array());
- } else {
- $addon->validate_live_secret_key(array());
+ if ($which !== 'whsec') {
+ $addon->{"validate_{$mode}_secret_key"}(array());
+ }
+ if ($which !== 'key') {
+ $addon->{"validate_{$mode}_webhook_secret"}(array());
}
return $addon;
@@ -47,7 +48,7 @@
gf_paystack_test_check(isset($a->field_errors['live_secret_key']) && strpos($a->field_errors['live_secret_key'], 'Paystack didn\'t accept this key.') === 0 && substr($a->field_errors['live_secret_key'], -strlen($st_suffix)) === $st_suffix, 'settings probe invalid_key error');
$a = $st_run('live', $rk_posted, array(), $verdict(array('code' => 'missing_scope', 'scopes' => array('transactions:write'))));
-gf_paystack_test_check($a->field_errors['live_secret_key'] === 'This restricted key can\'t be used: enable Transactions: write. It needs Transactions: read and write. Permissions that can move money aren\'t allowed.' . $st_suffix, 'settings probe missing_scope copy');
+gf_paystack_test_check($a->field_errors['live_secret_key'] === 'This restricted key can\'t be used: enable Transactions: write. It needs Transactions: read and write. Permissions such as transfers, refunds, settlements and payouts aren\'t allowed.' . $st_suffix, 'settings probe missing_scope copy');
$a = $st_run('live', $rk_posted, array(), $verdict(array('code' => 'sensitive_scope', 'sensitive_scopes' => array('transfers', 'disputes_refunds'))));
gf_paystack_test_check(strpos($a->field_errors['live_secret_key'], 'remove Transfers, Disputes and refunds.') !== false && strpos($a->field_errors['live_secret_key'], 'enable') === false, 'settings probe sensitive_scope copy');
@@ -79,6 +80,59 @@
$a = $st_run('test', array('test_secret_key' => 'garbage'));
gf_paystack_test_check($a->field_errors['test_secret_key'] === 'Secret keys start with sk_test_ and restricted keys with rk_test_. Check you copied the whole key.' . $st_suffix, 'settings invalid_format copy');
+// Each callback reports only its own codes.
+$a = $st_run('test', array('test_secret_key' => $st_rk_test, 'test_webhook_secret' => ''), array(), null, 'key');
+gf_paystack_test_check($a->error_log === array() && $a->validate_calls === array(), 'settings key callback ignores whsec codes');
+$a = $st_run('test', array('test_secret_key' => $st_rk_test, 'test_webhook_secret' => ''), array(), null, 'whsec');
+gf_paystack_test_check($a->error_log === array('test_webhook_secret'), 'settings whsec callback reports whsec codes once');
+$a = $st_run('live', array('live_secret_key' => $st_sk_test), array(), null, 'whsec');
+gf_paystack_test_check($a->error_log === array(), 'settings whsec callback ignores key codes');
+$a = $st_run('live', array('live_secret_key' => $st_sk_test));
+gf_paystack_test_check($a->error_log === array('live_secret_key'), 'settings key code is reported once across both callbacks');
+$a = $st_run('live', $rk_posted, array(), $verdict(array('code' => 'invalid_key')));
+gf_paystack_test_check($a->error_log === array('live_secret_key'), 'settings probe result is reported once across both callbacks');
+$a = $st_run('live', array('live_secret_key' => $st_sk_live, 'live_webhook_secret' => 'nope'), array(), null, 'key');
+gf_paystack_test_check($a->error_log === array(), 'settings key callback silent on bad whsec shape');
+
+// Plans check on save.
+$sub_feed = function ($mode, $active = '1', $type = 'subscription') {
+ return array('is_active' => $active, 'meta' => array('transactionType' => $type) + ($mode === null ? array() : array('mode' => $mode)));
+};
+$with_feeds = function ($feeds, $plans = 'ok') use ($verdict) {
+ return function ($addon) use ($feeds, $plans) {
+ $addon->feeds = $feeds;
+ $addon->plans_result = $plans;
+ };
+};
+
+$a = $st_run('live', $rk_posted, array(), $with_feeds(array($sub_feed('live'))), 'key');
+gf_paystack_test_check($a->field_errors === array() && $a->plans_calls === array($st_rk_live), 'settings save probes plans for an active subscription feed in that mode');
+
+$a = $st_run('live', $rk_posted, array(), $with_feeds(array($sub_feed(null))), 'key');
+gf_paystack_test_check($a->plans_calls === array($st_rk_live), 'settings save treats a feed without a mode as live');
+
+$a = $st_run('live', $rk_posted, array(), $with_feeds(array($sub_feed('live')), 'plans_missing'), 'key');
+gf_paystack_test_check($a->field_errors['live_secret_key'] === 'Subscriptions need Plans: write on your live restricted key. Add it in your Paystack Dashboard, then save this feed again.' . $st_suffix, 'settings save plans_missing error on the key field');
+
+$a = $st_run('live', $rk_posted, array(), $with_feeds(array($sub_feed('live')), 'plans_mor'), 'key');
+gf_paystack_test_check($a->field_errors['live_secret_key'] === 'Paystack subscriptions aren\'t available for merchant-of-record accounts.' . $st_suffix, 'settings save plans_mor error on the key field');
+
+$a = $st_run('live', $rk_posted, array(), $with_feeds(array($sub_feed('live')), 'unverifiable'), 'key');
+gf_paystack_test_check(strpos($a->field_errors['live_secret_key'], 'We couldn\'t reach Paystack') === 0, 'settings save plans unverifiable error on the key field');
+
+$a = $st_run('live', $rk_posted, array(), $with_feeds(array($sub_feed('test'), $sub_feed('live', '0'), $sub_feed('live', '1', 'product')), 'plans_missing'), 'key');
+gf_paystack_test_check($a->field_errors === array() && $a->plans_calls === array(), 'settings save skips plans when no active subscription feed uses that mode');
+
+$a2 = $st_run('live', $rk_posted, array(), function ($addon) use ($sub_feed, $verdict) {
+ $addon->feeds = array($sub_feed('live'));
+ $addon->verdict = array_merge($addon->verdict, array('code' => 'invalid_key'));
+ $addon->plans_result = 'plans_missing';
+}, 'key');
+gf_paystack_test_check($a2->plans_calls === array() && strpos($a2->field_errors['live_secret_key'], 'Paystack didn\'t accept this key.') === 0, 'settings save skips plans when the settings probe fails');
+
+$a = $st_run('live', array('live_secret_key' => $st_rk_live, 'live_webhook_secret' => $st_ws_live), array('live_secret_key' => $st_rk_live), $with_feeds(array($sub_feed('live')), 'plans_missing'), 'key');
+gf_paystack_test_check($a->plans_calls === array() && $a->field_errors === array(), 'settings save skips plans for an unchanged key');
+
$GLOBALS['gf_paystack_test_filters'] = array('gform_paystack_restricted_keys_enabled' => false);
$a = $st_run('live', $rk_posted);
gf_paystack_test_check(isset($a->field_errors['live_secret_key']) && strpos($a->field_errors['live_secret_key'], 'Restricted keys are turned off on this site.') === 0 && $a->validate_calls === array(), 'settings gate off new rk rejected');
@@ -100,7 +154,7 @@
gf_paystack_test_check($pw_ok, 'settings secret and whsec fields are password inputs');
$order = array_keys($by_name);
gf_paystack_test_check(array_search('test_webhook_secret', $order) === array_search('test_secret_key', $order) + 1 && array_search('live_webhook_secret', $order) === array_search('live_secret_key', $order) + 1, 'settings whsec fields follow their secret key');
-gf_paystack_test_check($by_name['test_secret_key']['label'] === 'Test Secret or Restricted Key' && $by_name['live_webhook_secret']['label'] === 'Live Webhook Signing Secret' && strpos($by_name['live_secret_key']['tooltip'], 'A restricted key lets this plugin take payments and nothing else.') !== false, 'settings labels and help text');
+gf_paystack_test_check($by_name['test_secret_key']['label'] === 'Test Secret or Restricted Key' && $by_name['live_webhook_secret']['label'] === 'Live Webhook Signing Secret' && strpos($by_name['live_secret_key']['tooltip'], 'A restricted key limits what this plugin can do with your Paystack account.') !== false, 'settings labels and help text');
// Feed.
$feed = function ($posted, $stored, $plans = 'ok') {
@@ -132,6 +186,99 @@
$a = $feed(array('transactionType' => 'product', 'mode' => 'test'), array('test_secret_key' => $st_rk_test), 'plans_missing');
gf_paystack_test_check($a->field_errors === array() && $a->plans_calls === array(), 'feed product rk no probe');
+
+// Feed: own validity of the transactionType field.
+$feed_field = array('name' => 'transactionType', 'choices' => array(array('label' => 'Products', 'value' => 'product'), array('label' => 'Subscription', 'value' => 'subscription')));
+$feed_run = function ($posted, $stored, $plans = 'ok', $configure = null, $field = null) use ($feed_field) {
+ $addon = new GFPaystackSettingsFixture();
+ $addon->posted = $posted;
+ $addon->stored = $stored;
+ $addon->plans_result = $plans;
+ if ($configure) {
+ $configure($addon);
+ }
+ $addon->validate_subscription_plans($field === null ? $feed_field : $field);
+
+ return $addon;
+};
+
+foreach (array('empty' => '', 'missing' => null, 'unknown' => 'donation', 'array' => array('subscription')) as $label => $bad) {
+ $posted = $bad === null ? array('mode' => 'test') : array('transactionType' => $bad, 'mode' => 'test');
+ $a = $feed_run($posted, array('test_secret_key' => $st_rk_test));
+ gf_paystack_test_check($a->field_errors === array('transactionType' => 'This field is required.') && $a->plans_calls === array(), "feed $label transactionType is a required error");
+}
+
+$a = $feed_run(array('transactionType' => 'donation'), array(), 'ok', null, array('name' => 'transactionType'));
+gf_paystack_test_check($a->field_errors === array('transactionType' => 'This field is required.'), 'feed without choices accepts only product or subscription');
+$a = $feed_run(array('transactionType' => 'product'), array(), 'ok', null, array('name' => 'transactionType'));
+gf_paystack_test_check($a->field_errors === array(), 'feed without choices accepts product');
+
+// Feed: probe only when something changed.
+$stored_feed = function ($type, $mode) {
+ return array('id' => 4, 'meta' => array('transactionType' => $type, 'mode' => $mode));
+};
+$with_current = function ($current) {
+ return function ($addon) use ($current) {
+ $addon->current_feed = $current;
+ };
+};
+
+$a = $feed_run($sub_test, array('test_secret_key' => $st_rk_test), 'plans_missing', $with_current($stored_feed('subscription', 'test')));
+gf_paystack_test_check($a->field_errors === array() && $a->plans_calls === array(), 'feed unchanged subscription feed is not probed');
+
+$a = $feed_run($sub_test, array('test_secret_key' => $st_rk_test, 'live_secret_key' => $st_rk_live), 'plans_missing', $with_current($stored_feed('subscription', 'live')));
+gf_paystack_test_check(isset($a->field_errors['transactionType']) && $a->plans_calls === array($st_rk_test), 'feed changed mode is probed');
+
+$a = $feed_run($sub_test, array('test_secret_key' => $st_rk_test), 'ok', $with_current($stored_feed('product', 'test')));
+gf_paystack_test_check($a->plans_calls === array($st_rk_test), 'feed changed to subscription is probed');
+
+$a = $feed_run(array('transactionType' => 'subscription'), array('live_secret_key' => $st_rk_live), 'ok', $with_current($stored_feed('subscription', 'test')));
+gf_paystack_test_check($a->plans_calls === array($st_rk_live), 'feed posted without mode compares as live');
+
+$a = $feed_run(array('transactionType' => 'subscription'), array('live_secret_key' => $st_rk_live), 'plans_missing', $with_current($stored_feed('subscription', 'live')));
+gf_paystack_test_check($a->plans_calls === array(), 'feed unchanged live default is not probed');
+
+// Feed: wiring and chaining.
+class GFPaystackFeedWiringFixture extends GFPaystackSettingsFixture
+{
+ public $parent_calls = 0;
+
+ public function parent_callback($field)
+ {
+ $this->parent_calls++;
+ }
+
+ public function feed_settings_fields()
+ {
+ return parent::feed_settings_fields();
+ }
+}
+
+$wired = new GFPaystackFeedWiringFixture();
+$wired_fields = $wired->feed_settings_fields();
+$wired_type = $wired->get_field('transactionType', $wired_fields);
+gf_paystack_test_check(is_array($wired_type) && $wired_type['validation_callback'] === array($wired, 'validate_subscription_plans'), 'feed_settings_fields wires validate_subscription_plans onto transactionType');
+
+class GFPaystackFeedChainFixture extends GFPaystackFeedWiringFixture
+{
+ public function get_field($name, $fields)
+ {
+ $field = parent::get_field($name, $fields);
+ if ($name === 'transactionType' && is_array($field) && !isset($field['validation_callback'])) {
+ $field['validation_callback'] = array($this, 'parent_callback');
+ }
+
+ return $field;
+ }
+}
+
+$chained = new GFPaystackFeedChainFixture();
+$chained->posted = array('transactionType' => 'product');
+$chained_fields = $chained->feed_settings_fields();
+$chained_type = $chained->get_field('transactionType', $chained_fields);
+$chained->validate_subscription_plans($chained_type);
+gf_paystack_test_check($chained->parent_calls === 1 && $chained->field_errors === array(), 'feed existing transactionType callback is still called');
+
$GLOBALS['gf_paystack_test_saved_settings'] = null;
$st_saver = new GFPaystackSettingsFixture();
$st_saver->update_plugin_settings(array('test_secret_key' => " $st_rk_test\n", 'live_webhook_secret' => " $st_ws_live ", 'api_mode' => ' test '));
diff --git a/tests/test-webhook.php b/tests/test-webhook.php
index a61e1da..3ddbac0 100644
--- a/tests/test-webhook.php
+++ b/tests/test-webhook.php
@@ -46,7 +46,7 @@
$charge_api = function ($overrides = array()) {
$api = new GFPaystackRecordingApi();
- $api->response = array('status' => true, 'message' => 'ok', 'data' => array_merge(array('id' => 99, 'status' => 'success', 'amount' => 5000, 'currency' => 'NGN'), $overrides));
+ $api->response = array('status' => true, 'message' => 'ok', 'data' => array_merge(array('id' => 99, 'reference' => 'gf-7-abc', 'status' => 'success', 'amount' => 5000, 'currency' => 'NGN'), $overrides));
return $api;
};
@@ -87,7 +87,32 @@
$throwing_charge_api = $charge_api();
$throwing_charge_api->throw = true;
$result = gf_paystack_callback_run(gf_paystack_charge_event(), 'live', $stored, null, null, $throwing_charge_api);
-gf_paystack_test_check($result === false, 'callback case 32');
+gf_paystack_test_check(is_wp_error($result) && $result->code === 'transaction_verification' && rgar($result->get_error_data(), 'status_header') === 500, 'callback case 32: verify throws asks Paystack to retry');
+
+$result = gf_paystack_callback_run(gf_paystack_charge_event(), 'live', $stored, null, null, $charge_api(array('id' => null)));
+gf_paystack_test_check($result === false, 'callback case 33: verified charge without an id is not completed');
+
+$result = gf_paystack_callback_run(gf_paystack_charge_event(), 'live', $stored, null, null, $charge_api(array('reference' => 'gf-7-other')));
+gf_paystack_test_check($result === false, 'callback case 34: verified reference mismatch is not completed');
+
+$result = gf_paystack_callback_run(gf_paystack_charge_event(), 'live', $stored, null, null, $charge_api(array('reference' => null)));
+gf_paystack_test_check($result === false, 'callback case 35: verified charge without a reference is not completed');
+
+$sub_feed = array('is_active' => '1', 'meta' => array('mode' => 'live', 'transactionType' => 'subscription'));
+$sub_charge = $charge_api(array('authorization' => array('authorization_code' => 'AUTH_verified')));
+$sub_event = gf_paystack_charge_event();
+$sub_event['data']['authorization'] = array('authorization_code' => 'AUTH_forged');
+$result = gf_paystack_callback_run($sub_event, 'live', $stored, $sub_feed, null, $sub_charge);
+gf_paystack_test_check($sub_charge->calls === array('transaction/verify/gf-7-abc') && gform_get_meta('7', 'paystack_tx_auth_code') === 'AUTH_verified', 'callback case 36: subscription branch stores the verified authorization code');
+
+$sub_forged = $charge_api(array('id' => 100, 'authorization' => array('authorization_code' => 'AUTH_verified')));
+gf_paystack_callback_run($sub_event, 'live', $stored, $sub_feed, null, $sub_forged);
+gf_paystack_test_check(gform_get_meta('7', 'paystack_tx_auth_code') === false, 'callback case 37: subscription branch stores nothing when the verified id differs');
+
+$sub_throwing = $charge_api();
+$sub_throwing->throw = true;
+$result = gf_paystack_callback_run($sub_event, 'live', $stored, $sub_feed, null, $sub_throwing);
+gf_paystack_test_check(is_wp_error($result) && rgar($result->get_error_data(), 'status_header') === 500 && gform_get_meta('7', 'paystack_tx_auth_code') === false, 'callback case 38: subscription verify throws asks Paystack to retry');
$result = gf_paystack_callback_run(gf_paystack_charge_event(array('reference' => 'gf-7-unknown')), 'live', $stored);
gf_paystack_test_check(is_wp_error($result) && $result->code === 'entry_not_found', 'callback case 9');
@@ -346,7 +371,7 @@ public function send_request($endpoint, $args = array(), $method = 'post', $doma
$_SERVER['HTTP_PAYSTACK_SIGNATURE'] = $header_for($event_body, 'whsec_' . str_repeat('ef56', 8));
$addon = $event_addon($both);
gf_paystack_test_check($addon->get_webhook_event($event_body) === false, 'domain missing: no mode verifies');
-gf_paystack_test_check(count($addon->errors) === 1 && strpos($addon->errors[0], 'sig=whsec result=invalid') !== false && strpos($addon->errors[0], $live_whsec) === false, 'failure logged at error level with sig/result, no secret');
+gf_paystack_test_check(count($addon->errors) === 1 && strpos($addon->errors[0], 'checks=live:whsec:invalid,test:whsec:invalid') !== false && strpos($addon->errors[0], $live_whsec) === false, 'failure logged at error level listing every attempt, no secret');
$domain_body = json_encode(array('event' => 'charge.success', 'data' => array('domain' => 'live', 'reference' => 'gf-7-abc')));
$_SERVER['HTTP_PAYSTACK_SIGNATURE'] = $header_for($domain_body, $test_whsec);
@@ -383,6 +408,20 @@ public function set_mode($mode)
gf_paystack_test_check(is_array($addon->get_webhook_event($event_body)) && $addon->webhook_mode_value() === 'live', 'sk legacy via get_webhook_event, domain missing');
$reset_sig_headers();
+// domain missing, no whsec: the configured api mode decides, as before
+$both_sk = array('api_mode' => 'test', 'live_secret_key' => $sk_live, 'test_secret_key' => 'sk_test_abc123');
+$_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] = hash_hmac('sha512', $event_body, $sk_live);
+$addon = $event_addon($both_sk);
+gf_paystack_test_check($addon->get_webhook_event($event_body) === false && $addon->webhook_mode_value() === 'test' && strpos($addon->errors[0], 'checks=test:legacy:invalid') !== false, 'domain missing, no whsec: api mode only, no sk try-both');
+$_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] = hash_hmac('sha512', $event_body, 'sk_test_abc123');
+gf_paystack_test_check(is_array($event_addon($both_sk)->get_webhook_event($event_body)), 'domain missing, no whsec: api mode key verifies');
+
+$one_whsec = array('api_mode' => 'live', 'live_secret_key' => $sk_live, 'test_secret_key' => 'sk_test_abc123', 'test_webhook_secret' => $test_whsec);
+$_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] = hash_hmac('sha512', $event_body, $sk_live);
+$addon = $event_addon($one_whsec);
+gf_paystack_test_check($addon->get_webhook_event($event_body) === false && $addon->webhook_mode_value() === 'test' && strpos($addon->errors[0], 'checks=test:whsec:malformed') !== false, 'domain missing: only modes with a whsec are candidates');
+$reset_sig_headers();
+
// ?secret= must not change the verifying key
$_GET['secret'] = 'sk_live_attacker';
$_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] = hash_hmac('sha512', $event_body, 'sk_live_attacker');
@@ -396,3 +435,17 @@ public function set_mode($mode)
$_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] = hash_hmac('sha512', $event_body, $rk_live);
gf_paystack_test_check($event_addon(array('api_mode' => 'live', 'live_secret_key' => $rk_live))->get_webhook_event($event_body) === false, 'rk only, no whsec: get_webhook_event rejects');
$reset_sig_headers();
+
+// ?secret= must not reach Paystack calls
+$_GET['secret'] = 'sk_live_attacker';
+$_GET['public'] = 'pk_live_attacker';
+$GLOBALS['gf_paystack_test_caps'] = array('update_core');
+$read_prop = function ($api, $prop) {
+ return (function () use ($prop) {
+ return $this->$prop;
+ })->call($api);
+};
+$qs_addon = $event_addon(array('api_mode' => 'live', 'live_secret_key' => $sk_live, 'live_public_key' => 'pk_live_stored'));
+$qs_api = $qs_addon->paystack_api();
+gf_paystack_test_check($read_prop($qs_api, 'secret_key') === $sk_live && $read_prop($qs_api, 'public_key') === 'pk_live_stored', '?secret= and ?public= ignored when building the API client');
+unset($_GET['secret'], $_GET['public'], $GLOBALS['gf_paystack_test_caps']);
From cff3a1620134e6a475a3918946928ed1ef0fdea2 Mon Sep 17 00:00:00 2001
From: Jules Nsenda
Date: Wed, 18 Nov 2026 21:09:34 +0200
Subject: [PATCH 10/19] test: cover the restricted-key change surface and its
fixes
Pins the full probe table, every classifier status, transport failures,
redaction of every error_log line, per-field validation callbacks and the
regressions fixed in the diff review.
Co-Authored-By: Claude Opus 5.5
---
tests/stubs.php | 4 ++
tests/test-gateway.php | 42 ++++++++++++++++
tests/test-keys.php | 26 ++++++++++
tests/test-restricted-key.php | 91 +++++++++++++++++++++++++++++++++++
tests/test-settings.php | 49 +++++++++++++++++++
tests/test-webhook.php | 61 +++++++++++++++++++++++
6 files changed, 273 insertions(+)
diff --git a/tests/stubs.php b/tests/stubs.php
index d5c6cea..753fe1b 100644
--- a/tests/stubs.php
+++ b/tests/stubs.php
@@ -16,6 +16,10 @@ function add_filter()
function apply_filters($tag, $value)
{
$overrides = isset($GLOBALS['gf_paystack_test_filters']) ? $GLOBALS['gf_paystack_test_filters'] : array();
+ if (array_key_exists($tag, $overrides) && $overrides[$tag] instanceof Closure) {
+ return call_user_func($overrides[$tag], $value);
+ }
+
return array_key_exists($tag, $overrides) ? $overrides[$tag] : $value;
}
}
diff --git a/tests/test-gateway.php b/tests/test-gateway.php
index 5a1c346..d83b449 100644
--- a/tests/test-gateway.php
+++ b/tests/test-gateway.php
@@ -175,3 +175,45 @@
});
gf_paystack_test_check(strpos($scalar_thrown, 'issue connecting') !== false, 'send_request case: JSON scalar response throws the generic Exception');
$GLOBALS['gf_paystack_test_remote_response'] = array('body' => json_encode(array('status' => true)));
+
+// # Coverage additions (dedicated test pass): every GFPaystackApi error_log line is redacted.
+$redact_log = tempnam(sys_get_temp_dir(), 'gfpstk');
+$redact_prev = ini_get('error_log');
+ini_set('error_log', $redact_log);
+$redact_api = new GFPaystackApi((object) array('secret_key' => 'sk_live_callkey', 'public_key' => 'pk_live_public'));
+$GLOBALS['gf_paystack_test_remote_response'] = array('response' => array('code' => 200), 'body' => json_encode(array('status' => true, 'message' => 'ok', 'data' => array())));
+$redact_api->send_request('transaction/verify/sk_live_leakinguri99', array(), 'get');
+$redact_contents = (string) file_get_contents($redact_log);
+gf_paystack_test_check(strpos($redact_contents, 'transaction/verify/sk_live_[redacted]') !== false && strpos($redact_contents, 'leakinguri99') === false, 'send_request status log line is redacted');
+
+file_put_contents($redact_log, '');
+$GLOBALS['gf_paystack_test_remote_response'] = array('response' => array('code' => 403), 'body' => json_encode(array('status' => false, 'message' => 'This restricted key is not permitted to perform this action')));
+gf_paystack_exception_message(function () use ($redact_api) {
+ $redact_api->send_request('transaction/verify/rk_live_leakingscope77', array(), 'get');
+});
+$redact_contents = (string) file_get_contents($redact_log);
+gf_paystack_test_check(strpos($redact_contents, 'rk scope denied') !== false && strpos($redact_contents, 'leakingscope77') === false && strpos($redact_contents, 'rk_live_[redacted]') !== false, 'rk scope denied log line is redacted');
+
+class GFPaystackLeakyTrackerApi extends GFPaystackApi
+{
+ public function send_request($endpoint, $args = array(), $method = 'post', $domain = 'https://api.paystack.co/')
+ {
+ throw new Exception('tracker said Bearer sk_live_leakingtracker55');
+ }
+}
+file_put_contents($redact_log, '');
+$leaky = new GFPaystackLeakyTrackerApi((object) array('secret_key' => 'sk', 'public_key' => 'pk'));
+$leaky->log_transaction_success('ref');
+$redact_contents = (string) file_get_contents($redact_log);
+gf_paystack_test_check(strpos($redact_contents, 'plugin tracker request failed') !== false && strpos($redact_contents, 'leakingtracker55') === false, 'plugin tracker failure log line is redacted');
+
+ini_set('error_log', $redact_prev === false ? '' : $redact_prev);
+unlink($redact_log);
+
+// GFPaystack log helpers redact too (including debug lines).
+$GLOBALS['gf_paystack_test_gf_logs'] = array();
+$log_addon = new GFPaystackSettingsFixture();
+$log_addon->log_debug('d rk_live_leakdebug11 whsec_leakdebug22');
+$log_addon->log_error('e sk_test_leakerror33');
+$logged_all = json_encode($GLOBALS['gf_paystack_test_gf_logs']);
+gf_paystack_test_check(count($GLOBALS['gf_paystack_test_gf_logs']) === 2 && strpos($logged_all, 'leakdebug') === false && strpos($logged_all, 'leakerror') === false && strpos($logged_all, 'rk_live_[redacted]') !== false, 'GFPaystack log_debug and log_error redact secrets');
diff --git a/tests/test-keys.php b/tests/test-keys.php
index e240dc1..dfb0181 100644
--- a/tests/test-keys.php
+++ b/tests/test-keys.php
@@ -58,3 +58,29 @@
gf_paystack_test_check(GF_Paystack_Keys::redact($case[0]) === $case[1], 'keys redact ' . $label);
}
gf_paystack_test_check(GF_Paystack_Keys::redact(array('sk_live_abc')) === array('sk_live_abc') && GF_Paystack_Keys::redact(null) === null, 'keys redact non-strings');
+
+// # Coverage additions (dedicated test pass)
+gf_paystack_test_check(GF_Paystack_Keys::mode('sk_livefoo') === null && GF_Paystack_Keys::type('sk_livefoo') === null, 'keys prefix needs the trailing underscore');
+$keys_extra = array(
+ 'prefix without trailing underscore' => array(array('test', 'sk_livefoo', '', '', '', true), false, 'invalid_format'),
+ 'rk body at 256 chars' => array(array('live', 'rk_live_' . str_repeat('a', 256), '', $whsec_a, '', true), true, null),
+ 'rk body over 256 chars' => array(array('live', 'rk_live_' . str_repeat('a', 257), '', $whsec_a, '', true), false, 'invalid_format'),
+ 'rk at 16 chars' => array(array('live', 'rk_live_' . str_repeat('a', 16), '', $whsec_a, '', true), true, null),
+ 'rk at 15 chars' => array(array('live', 'rk_live_' . str_repeat('a', 15), '', $whsec_a, '', true), false, 'invalid_format'),
+ 'blank whsec on both sides is not a duplicate' => array(array('live', $sk_live, $sk_live, '', '', true), false, null),
+ 'whsec at 16 chars' => array(array('live', $sk_live, $sk_live, 'whsec_' . str_repeat('a', 16), '', true), false, null),
+ 'whsec at 15 chars' => array(array('live', $sk_live, $sk_live, 'whsec_' . str_repeat('a', 15), '', true), false, 'whsec_format'),
+ 'whitespace-only other whsec is blank' => array(array('live', $sk_live, $sk_live, $whsec_a, ' ', true), false, null),
+ 'rk error reports no probe' => array(array('live', $rk_live, '', '', '', true), false, 'whsec_required'),
+);
+foreach ($keys_extra as $label => $case) {
+ $result = call_user_func_array(array('GF_Paystack_Keys', 'resolve_save'), $case[0]);
+ gf_paystack_test_check($result === array('probe' => $case[1], 'error' => $case[2]), 'keys resolve_save ' . $label);
+}
+
+$GLOBALS['gf_paystack_test_filters']['gform_paystack_restricted_keys_enabled'] = false;
+gf_paystack_test_check(GF_Paystack_Keys::restricted_keys_enabled() === false, 'keys gate filter can turn restricted keys off');
+unset($GLOBALS['gf_paystack_test_filters']['gform_paystack_restricted_keys_enabled']);
+
+gf_paystack_test_check(GF_Paystack_Keys::redact('a sk_live_abc and rk_test_def and whsec_ghi') === 'a sk_live_[redacted] and rk_test_[redacted] and whsec_[redacted]', 'keys redact several secrets in one string');
+gf_paystack_test_check(GF_Paystack_Keys::redact('sk_live_abc"') === 'sk_live_[redacted]"', 'keys redact stops at a closing quote');
diff --git a/tests/test-restricted-key.php b/tests/test-restricted-key.php
index e99e02a..bdef3ca 100644
--- a/tests/test-restricted-key.php
+++ b/tests/test-restricted-key.php
@@ -213,3 +213,94 @@ class GF_Paystack_Restricted_Key_Zero extends GF_Paystack_Restricted_Key
return strtolower($k) === 'authorization';
});
gf_paystack_test_check(count($auth_keys) === 1 && $sent_headers['Authorization'] === 'Bearer ' . $rk_key && $sent_headers['X-Extra'] === '1', 'rk probe headers keep a single Authorization with the saved key');
+
+// # Coverage additions (dedicated test pass)
+
+$rk_pinned = array(
+ 'transactions:read|required|GET|transaction?perPage=1|2xx',
+ 'transactions:write|required|POST|transaction/check_authorization|404_write',
+ 'disputes_refunds|sensitive|GET|refund?perPage=1|2xx_or_400',
+ 'bulk_charges|sensitive|GET|bulkcharge|2xx_or_400',
+ 'direct_debit|sensitive|GET|directdebit/account|2xx_or_400',
+ 'preauthorizations|sensitive|GET|preauthorization|2xx_or_400',
+ 'settlements|sensitive|GET|settlement?perPage=1|2xx_or_400',
+ 'subaccounts|sensitive|GET|subaccount|2xx_or_400',
+ 'transfers|sensitive|GET|transfer/config|2xx_or_400',
+ 'virtual_accounts|sensitive|GET|pay-with-transfer/custom-accounts/status|2xx_or_400',
+ 'webhooks|sensitive|GET|integration/webhooks/events|2xx_or_400',
+ 'connect|sensitive|GET|connect/platforms|2xx_or_400',
+ 'payouts|sensitive|GET|settlement/instant/profile|2xx_or_400',
+);
+$rk_actual = array();
+$rk_only_safe = true;
+foreach (GF_Paystack_Restricted_Key::PROBES as $p) {
+ $rk_actual[] = $p['scope'] . '|' . $p['type'] . '|' . $p['method'] . '|' . $p['path'] . '|' . $p['present'];
+ $rk_only_safe = $rk_only_safe && ($p['method'] === 'GET' || $p['scope'] === 'transactions:write');
+}
+gf_paystack_test_check($rk_actual === $rk_pinned, 'rk full probe table (scope, type, method, path, presence rule) pinned');
+gf_paystack_test_check($rk_only_safe, 'rk only the transactions:write probe is a non-GET');
+
+$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make(array('transactions:read' => 201, 'transactions:write' => array(404, $write_msg)), array(403, $scope_msg)));
+gf_paystack_test_check($v['code'] === 'ok', 'rk baseline 201 counts as present');
+
+$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make($rk_ok_map + array('settlements' => 204), array(403, $scope_msg)));
+gf_paystack_test_check($v['code'] === 'sensitive_scope' && $v['sensitive_scopes'] === array('settlements'), 'rk sensitive probe 204 is present');
+
+$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make(array('transactions:read' => 400), array(403, $scope_msg), $log));
+gf_paystack_test_check($v['code'] === 'unverifiable' && $log === array('transactions:read'), 'rk 400 on the required baseline is not presence');
+
+$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make(array('transactions:read' => 200, 'transactions:write' => 401), array(403, $scope_msg), $log));
+gf_paystack_test_check($v['code'] === 'unverifiable' && end($log) === 'transactions:write', 'rk 401 on the required write probe after a 2xx baseline is not proof');
+
+$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make(array('transactions:read' => array(403, $scope_msg), 'transactions:write' => array(404, $write_msg), 'disputes_refunds' => 401), array(403, $scope_msg)));
+gf_paystack_test_check($v['sensitive_scopes'] === array(), 'rk 401 on sensitive after absent baseline reports no sensitive scope');
+
+// A failing transport still records the probe that ran.
+$notices = array();
+set_error_handler(function ($no, $str) use (&$notices) {
+ $notices[] = $str;
+
+ return true;
+});
+$v_throw = GF_Paystack_Restricted_Key::validate($rk_key, function () {
+ throw new RuntimeException('boom');
+});
+$v_nostatus = GF_Paystack_Restricted_Key::validate($rk_key, function () {
+ return array('body' => null);
+});
+restore_error_handler();
+gf_paystack_test_check($v_throw['probes'] === 'transactions:read:0' && $v_nostatus['probes'] === 'transactions:read:0' && $v_nostatus['code'] === 'unverifiable' && $notices === array(), 'rk throwing or status-less transport maps to status 0 without notices');
+
+// Anything thrown outside the transport is still contained.
+$GLOBALS['gf_paystack_test_filters']['gf_paystack_request_headers'] = function () {
+ throw new RuntimeException('filter exploded');
+};
+$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make($rk_ok_map));
+gf_paystack_test_check($v['code'] === 'unverifiable' && $v['reason'] === 'transient' && $v['probes'] === '-', 'rk validate contains a Throwable raised outside the transport');
+gf_paystack_test_check(GF_Paystack_Restricted_Key::probe_plans($rk_key, $plan(400)) === 'unverifiable', 'rk probe_plans contains a Throwable raised outside the transport');
+unset($GLOBALS['gf_paystack_test_filters']['gf_paystack_request_headers']);
+
+// A filter returning a non-array must not break the probe.
+$GLOBALS['gf_paystack_test_filters']['gf_paystack_request_headers'] = 'junk';
+$seen_headers = null;
+$v = GF_Paystack_Restricted_Key::validate($rk_key, function ($m, $u, $h, $b) use (&$seen_headers, $rk_make, $rk_ok_map, $scope_msg) {
+ $seen_headers = $h;
+ $f = $rk_make($rk_ok_map, array(403, $scope_msg));
+
+ return $f($m, $u, $h, $b);
+});
+unset($GLOBALS['gf_paystack_test_filters']['gf_paystack_request_headers']);
+gf_paystack_test_check($v['code'] === 'ok' && $seen_headers === array('Authorization' => 'Bearer ' . $rk_key), 'rk non-array header filter falls back to the forced Authorization header');
+
+// probe_plans: only 400 is a pass
+gf_paystack_test_check(GF_Paystack_Restricted_Key::probe_plans($rk_key, $plan(422, 'x')) === 'unverifiable', 'rk plans 422 unverifiable');
+gf_paystack_test_check(GF_Paystack_Restricted_Key::probe_plans($rk_key, $plan(200)) === 'unverifiable', 'rk plans 200 unverifiable');
+gf_paystack_test_check(GF_Paystack_Restricted_Key::probe_plans($rk_key, $plan(401, $scope_msg)) === 'unverifiable', 'rk plans 401 unverifiable');
+gf_paystack_test_check(GF_Paystack_Restricted_Key::probe_plans($rk_key, $plan(403)) === 'unverifiable', 'rk plans 403 without a message unverifiable');
+$plan_headers = null;
+GF_Paystack_Restricted_Key::probe_plans($rk_key, function ($m, $u, $h, $b) use (&$plan_headers) {
+ $plan_headers = $h;
+
+ return array('status' => 400, 'body' => null);
+});
+gf_paystack_test_check($plan_headers['Authorization'] === 'Bearer ' . $rk_key, 'rk plans probe sends the key as Bearer');
diff --git a/tests/test-settings.php b/tests/test-settings.php
index 3113d3c..f41e0cb 100644
--- a/tests/test-settings.php
+++ b/tests/test-settings.php
@@ -284,3 +284,52 @@ public function get_field($name, $fields)
$st_saver->update_plugin_settings(array('test_secret_key' => " $st_rk_test\n", 'live_webhook_secret' => " $st_ws_live ", 'api_mode' => ' test '));
$st_saved = $GLOBALS['gf_paystack_test_saved_settings'];
gf_paystack_test_check($st_saved['test_secret_key'] === $st_rk_test && $st_saved['live_webhook_secret'] === $st_ws_live && $st_saved['api_mode'] === ' test ', 'settings save trims only credential fields');
+
+// # Coverage additions (dedicated test pass)
+
+// Each credential field is wired to its own callback.
+$wiring_ok = true;
+foreach (array('test_secret_key' => 'validate_test_secret_key', 'live_secret_key' => 'validate_live_secret_key', 'test_webhook_secret' => 'validate_test_webhook_secret', 'live_webhook_secret' => 'validate_live_webhook_secret') as $field_name => $callback) {
+ $wiring_ok = $wiring_ok && isset($by_name[$field_name]['validation_callback']) && $by_name[$field_name]['validation_callback'] === array($fa, $callback);
+}
+gf_paystack_test_check($wiring_ok, 'settings each key and whsec field carries its own validation callback');
+
+// Each callback validates its own mode.
+$a = $st_run('test', array('test_secret_key' => $st_sk_live, 'live_secret_key' => $st_sk_test));
+gf_paystack_test_check($a->error_log === array('test_secret_key'), 'settings test key callback only reports the test field');
+$a = $st_run('live', array('test_secret_key' => $st_sk_live, 'live_secret_key' => $st_sk_test));
+gf_paystack_test_check($a->error_log === array('live_secret_key'), 'settings live key callback only reports the live field');
+$a = $st_run('test', array('test_webhook_secret' => 'nope', 'live_webhook_secret' => 'nope'), array(), null, 'whsec');
+gf_paystack_test_check($a->error_log === array('test_webhook_secret'), 'settings test whsec callback only reports the test field');
+$a = $st_run('live', array('test_webhook_secret' => 'nope', 'live_webhook_secret' => 'nope'), array(), null, 'whsec');
+gf_paystack_test_check($a->error_log === array('live_webhook_secret'), 'settings live whsec callback only reports the live field');
+
+// The mirror image: each mode's rk probe uses its own mode's whsec and stored key.
+$a = $st_run('live', array('live_secret_key' => $st_rk_live, 'live_webhook_secret' => $st_ws_live, 'test_webhook_secret' => $st_ws_live));
+gf_paystack_test_check(isset($a->field_errors['live_webhook_secret']) && $a->validate_calls === array(), 'settings whsec_same is judged against the other mode and blocks the probe');
+$a = $st_run('live', array('live_secret_key' => $st_rk_live, 'live_webhook_secret' => $st_ws_live, 'test_webhook_secret' => $st_ws_test), array('live_secret_key' => $st_rk_test));
+gf_paystack_test_check($a->validate_calls === array($st_rk_live), 'settings a changed key is compared against this mode stored key');
+$a = $st_run('live', array('live_secret_key' => $st_rk_live, 'live_webhook_secret' => $st_ws_live), array('test_secret_key' => $st_rk_live));
+gf_paystack_test_check($a->validate_calls === array($st_rk_live), 'settings stored key of the other mode does not make this key unchanged');
+
+// Feed choices drive the allowed transaction types.
+$custom_field = array('name' => 'transactionType', 'choices' => array(array('label' => 'Donation', 'value' => 'donation'), array('label' => 'Sub', 'value' => 'subscription')));
+$a = $feed_run(array('transactionType' => 'donation'), array(), 'ok', null, $custom_field);
+gf_paystack_test_check($a->field_errors === array(), 'feed accepts a type that is only in the field choices');
+$a = $feed_run(array('transactionType' => 'product'), array(), 'ok', null, $custom_field);
+gf_paystack_test_check($a->field_errors === array('transactionType' => 'This field is required.'), 'feed rejects product when the field choices do not offer it');
+$name_field = array('name' => 'transactionType', 'choices' => array(array('label' => 'Donation', 'name' => 'donation')));
+$a = $feed_run(array('transactionType' => 'donation'), array(), 'ok', null, $name_field);
+gf_paystack_test_check($a->field_errors === array(), 'feed choice without a value falls back to its name');
+
+// Non-array settings pass through untouched.
+$GLOBALS['gf_paystack_test_saved_settings'] = 'unset';
+$st_saver->update_plugin_settings(null);
+gf_paystack_test_check($GLOBALS['gf_paystack_test_saved_settings'] === null, 'settings save passes non-array settings through');
+
+// get_webhook_secret / get_stored_secret_key read per-mode settings and trim.
+$st_reader = new GFPaystackSettingsFixture();
+$st_reader->stored = array('test_webhook_secret' => " $st_ws_test ", 'live_webhook_secret' => $st_ws_live, 'test_secret_key' => " $st_sk_test\n", 'live_secret_key' => $st_rk_live);
+gf_paystack_test_check($st_reader->get_webhook_secret('test') === $st_ws_test && $st_reader->get_webhook_secret('live') === $st_ws_live && $st_reader->get_webhook_secret('live', array()) === $st_ws_live, 'settings get_webhook_secret is per mode, trimmed, and falls back to plugin settings');
+gf_paystack_test_check($st_reader->get_stored_secret_key('test') === $st_sk_test && $st_reader->get_stored_secret_key('live', array('live_secret_key' => 'x')) === 'x', 'settings get_stored_secret_key is per mode, trimmed, and prefers passed settings');
+gf_paystack_test_check($st_reader->get_webhook_secret('test', array('test_webhook_secret' => $st_ws_live)) === $st_ws_live && (new GFPaystackSettingsFixture())->get_webhook_secret('test') === '', 'settings get_webhook_secret prefers passed settings and defaults to blank');
diff --git a/tests/test-webhook.php b/tests/test-webhook.php
index 3ddbac0..b55ca67 100644
--- a/tests/test-webhook.php
+++ b/tests/test-webhook.php
@@ -449,3 +449,64 @@ public function set_mode($mode)
$qs_api = $qs_addon->paystack_api();
gf_paystack_test_check($read_prop($qs_api, 'secret_key') === $sk_live && $read_prop($qs_api, 'public_key') === 'pk_live_stored', '?secret= and ?public= ignored when building the API client');
unset($_GET['secret'], $_GET['public'], $GLOBALS['gf_paystack_test_caps']);
+
+// # Coverage additions (dedicated test pass)
+
+// Legacy HMAC key is the stored sk, never the (possibly overridden) API-call key.
+$legacy_cfg = new GFPaystackApi((object) array('secret_key' => 'sk_live_callkey', 'public_key' => 'pk', 'stored_secret_key' => $sk_live));
+gf_paystack_test_check($legacy_cfg->validate_webhook($webhook_body, hash_hmac('sha512', $webhook_body, $sk_live)) === true, 'legacy HMAC verifies with the stored sk');
+gf_paystack_test_check($legacy_cfg->validate_webhook($webhook_body, hash_hmac('sha512', $webhook_body, 'sk_live_callkey')) === false, 'legacy HMAC does not verify with the API-call key');
+
+// The fallthrough path records why it rejected.
+$none_api = $whsec_api('', $rk_live);
+$none_api->validate_webhook($webhook_body, 'x');
+gf_paystack_test_check($none_api->last_webhook_check === array('sig' => 'none', 'result' => 'invalid'), 'validate_webhook records none/invalid when neither whsec nor sk is configured');
+$legacy_bad = $whsec_api('', $sk_live);
+$legacy_bad->validate_webhook($webhook_body, 'deadbeef');
+gf_paystack_test_check($legacy_bad->last_webhook_check === array('sig' => 'legacy', 'result' => 'invalid'), 'validate_webhook records legacy/invalid');
+$whsec_bad = $whsec_api($whsec);
+$whsec_bad->validate_webhook($webhook_body, null, "t=$t,$bad_v1");
+gf_paystack_test_check($whsec_bad->last_webhook_check['sig'] === 'whsec' && $whsec_bad->last_webhook_check['result'] === 'invalid', 'validate_webhook records whsec result for an explicit signing header');
+
+// Header parsing details
+$hdr_notices = array();
+set_error_handler(function ($no, $str) use (&$hdr_notices) {
+ $hdr_notices[] = $str;
+
+ return true;
+});
+$junk_result = $api->check_signing_secret_header($webhook_body, "junk,t=$t,$good_v1", $now);
+restore_error_handler();
+gf_paystack_test_check($junk_result === 'valid' && $hdr_notices === array(), 'whsec header part without = is ignored silently');
+gf_paystack_test_check($api->check_signing_secret_header($webhook_body, "t=$t,v1=:" . hash_hmac('sha512', $t . '.' . $webhook_body, $whsec), $now) === 'malformed', 'whsec v1 with empty kid is malformed');
+gf_paystack_test_check($api->check_signing_secret_header($webhook_body, "t=$t,v1=k1:" . str_repeat('a', 64), $now) === 'malformed', 'whsec v1 with 64 hex chars is malformed');
+gf_paystack_test_check($api->check_signing_secret_header($webhook_body, "t=$t,v1=k1:" . strtoupper(hash_hmac('sha512', $t . '.' . $webhook_body, $whsec)), $now) === 'valid', 'whsec uppercase hex signature is accepted');
+
+// Settings values are trimmed before they become secrets
+$ws_padded = array('api_mode' => 'live', 'live_secret_key' => $rk_live, 'live_webhook_secret' => " $whsec \n");
+$_SERVER['HTTP_PAYSTACK_SIGNATURE'] = $header_for($event_body, $whsec);
+gf_paystack_test_check(is_array($event_addon($ws_padded)->get_webhook_event($event_body)), 'whsec read from settings is trimmed');
+$reset_sig_headers();
+$_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] = hash_hmac('sha512', $event_body, $sk_live);
+gf_paystack_test_check(is_array($event_addon(array('api_mode' => 'live', 'live_secret_key' => "$sk_live \n"))->get_webhook_event($event_body)), 'stored sk read from settings is trimmed for the legacy HMAC');
+$reset_sig_headers();
+
+// A validator that throws becomes a WP_Error
+class GFPaystackThrowingValidatorApi extends GFPaystackApi
+{
+ public function validate_webhook($input, $signature = null, $signing_header = null)
+ {
+ throw new Exception('validator down');
+ }
+}
+class GFPaystackThrowingValidatorAddon extends GFPaystackEventFixture
+{
+ public function paystack_api($mode = null, $settings = null)
+ {
+ return $this->paystack_api = new GFPaystackThrowingValidatorApi((object) array());
+ }
+}
+$throwing_addon = new GFPaystackThrowingValidatorAddon();
+$throwing_addon->settings = array('api_mode' => 'live', 'live_secret_key' => $sk_live);
+$throw_result = $throwing_addon->get_webhook_event($event_body);
+gf_paystack_test_check(is_wp_error($throw_result) && $throw_result->code === 'Webhook Validation Failed' && $throw_result->message === 'validator down' && count($throwing_addon->errors) === 1, 'webhook validator exception returns a WP_Error and is logged');
From cba5fe31da8ee63369292eb642f64ae9e05bd1a8 Mon Sep 17 00:00:00 2001
From: Jules Nsenda
Date: Wed, 18 Nov 2026 21:11:45 +0200
Subject: [PATCH 11/19] fix: close gaps found in the second diff review
- A domainless webhook also tries the site's API mode after the signing-secret
modes, so an sk merchant with a secret in only one mode keeps webhooks.
- Restricted-key characters and the log redactor's stop characters no longer
overlap; a failed verify answers with a fixed message.
- The plans check covers inactive subscription feeds, resolves feeds without a
mode like checkout does, and its settings-page copy fits that page.
- The probe time budget renews in long-lived processes; header names are
trimmed before the Authorization strip; chained feed callbacks get all args.
- Changelog notes the removed ?secret=/?public= override.
Co-Authored-By: Claude Opus 5.5
---
class-gf-paystack.php | 49 +++++++++++++------
includes/class-gf-paystack-keys.php | 4 +-
includes/class-gf-paystack-restricted-key.php | 15 ++++--
readme.txt | 1 +
tests/test-keys.php | 5 ++
tests/test-restricted-key.php | 41 ++++++++++++++++
tests/test-settings.php | 44 +++++++++++++++--
tests/test-webhook.php | 11 ++++-
8 files changed, 144 insertions(+), 26 deletions(-)
diff --git a/class-gf-paystack.php b/class-gf-paystack.php
index 70c3921..917b147 100644
--- a/class-gf-paystack.php
+++ b/class-gf-paystack.php
@@ -1356,7 +1356,7 @@ public function callback()
} catch (\Exception $e) {
$this->log_error(__METHOD__ . '(): Transaction could not be verified. Reason: ' . $e->getMessage());
- return new WP_Error('transaction_verification', $e->getMessage(), array('status_header' => 500));
+ return new WP_Error('transaction_verification', __('Transaction could not be verified.', 'gravityformspaystack'), array('status_header' => 500));
}
$charge = rgar($response, 'data');
@@ -1367,7 +1367,7 @@ public function callback()
return false;
}
- if ((string) rgar($charge, 'id') !== (string) rgars($event, 'data/id') || rgar($charge, 'reference') !== $reference) {
+ if (rgar($charge, 'id') === null || rgar($charge, 'id') === '' || (string) rgar($charge, 'id') !== (string) rgars($event, 'data/id') || rgar($charge, 'reference') !== $reference) {
$this->log_error(__METHOD__ . '(): Verified transaction does not match the webhook event. Aborting.');
return false;
@@ -1772,6 +1772,11 @@ public function get_webhook_event($body = null)
$candidates[] = $candidate_mode;
}
}
+
+ $api_mode = $this->get_api_mode($settings);
+ if (!in_array($api_mode, $candidates, true)) {
+ $candidates[] = $api_mode;
+ }
}
if (empty($candidates)) {
@@ -2059,7 +2064,7 @@ public function paystack_api($mode = null, $settings = null)
}
/**
- * Read straight from settings so the ?secret= override can't reach webhook verification.
+ * Reads straight from stored settings.
*
* @param string $mode
* @param array|null $settings
@@ -2188,10 +2193,10 @@ protected function validate_secret_key_for_mode($mode)
return;
}
- if ($this->has_active_subscription_feed($mode)) {
+ if ($this->has_subscription_feed($mode)) {
$plans = $this->probe_restricted_key_plans($key);
if ($plans !== 'ok') {
- $this->set_field_error(array('name' => "{$mode}_secret_key"), $this->plans_error_message($plans, $mode) . $this->not_saved_suffix());
+ $this->set_field_error(array('name' => "{$mode}_secret_key"), $this->plans_error_message($plans, $mode, 'settings') . $this->not_saved_suffix());
}
}
}
@@ -2201,10 +2206,10 @@ protected function validate_secret_key_for_mode($mode)
*
* @return bool
*/
- protected function has_active_subscription_feed($mode)
+ protected function has_subscription_feed($mode)
{
foreach ((array) $this->get_feeds() as $feed) {
- if (rgar($feed, 'is_active') && rgars($feed, 'meta/transactionType') === 'subscription' && $this->feed_mode($feed) === $mode) {
+ if (rgars($feed, 'meta/transactionType') === 'subscription' && $this->feed_mode($feed) === $mode) {
return true;
}
}
@@ -2215,11 +2220,16 @@ protected function has_active_subscription_feed($mode)
/**
* @param array|false $feed
*
- * @return string 'test' or 'live'; feeds default to live.
+ * @return string 'test' or 'live'; a feed without a mode follows the global API mode.
*/
protected function feed_mode($feed)
{
- return rgars($feed, 'meta/mode') === 'test' ? 'test' : 'live';
+ $mode = rgars($feed, 'meta/mode');
+ if ($mode === 'test' || $mode === 'live') {
+ return $mode;
+ }
+
+ return $this->get_api_mode($this->get_plugin_settings()) === 'test' ? 'test' : 'live';
}
/**
@@ -2245,23 +2255,25 @@ protected function probe_restricted_key_plans($key)
/**
* Subscription feeds need Plans: write, which the settings probe doesn't check.
*
- * @param array $field The transactionType field properties.
+ * @param array|object $field The transactionType field.
+ * @param mixed $value The submitted value, when the caller passes one.
*
* @return void
*/
- public function validate_subscription_plans($field)
+ public function validate_subscription_plans($field, $value = null)
{
if (is_callable($this->transaction_type_callback)) {
- call_user_func($this->transaction_type_callback, $field);
+ call_user_func_array($this->transaction_type_callback, func_get_args());
}
$settings = $this->get_posted_settings();
$type = rgar($settings, 'transactionType');
$allowed = array('product', 'subscription');
- if (is_array(rgar($field, 'choices'))) {
+ $choices = is_array($field) ? rgar($field, 'choices') : (is_object($field) && isset($field->choices) ? $field->choices : null);
+ if (is_array($choices)) {
$allowed = array();
- foreach ($field['choices'] as $choice) {
+ foreach ($choices as $choice) {
$allowed[] = isset($choice['value']) ? $choice['value'] : rgar($choice, 'name');
}
}
@@ -2294,13 +2306,18 @@ public function validate_subscription_plans($field)
/**
* @param string $result A probe_plans() code other than 'ok'.
- * @param string $mode 'test' or 'live'.
+ * @param string $mode 'test' or 'live'.
+ * @param string $context 'feed' or 'settings'.
*
* @return string
*/
- protected function plans_error_message($result, $mode)
+ protected function plans_error_message($result, $mode, $context = 'feed')
{
if ($result === 'plans_missing') {
+ if ($context === 'settings') {
+ return sprintf(esc_html__('Subscriptions need Plans: write on your %s restricted key. Add it in your Paystack Dashboard, then save these settings again.', 'gravityformspaystack'), $mode);
+ }
+
return sprintf(esc_html__('Subscriptions need Plans: write on your %s restricted key. Add it in your Paystack Dashboard, then save this feed again.', 'gravityformspaystack'), $mode);
}
diff --git a/includes/class-gf-paystack-keys.php b/includes/class-gf-paystack-keys.php
index c7e8857..61853df 100644
--- a/includes/class-gf-paystack-keys.php
+++ b/includes/class-gf-paystack-keys.php
@@ -6,10 +6,10 @@
final class GF_Paystack_Keys
{
const SK_SHAPE = '/^sk_(?:test|live)_[A-Za-z0-9]+$/';
- const RK_SHAPE = '/^rk_(?:test|live)_[\x21-\x7e]{16,256}$/';
+ const RK_SHAPE = '/^rk_(?:test|live)_[\x21\x23-\x26\x28-\x3b\x3d\x3f-\x5b\x5d-\x7e]{16,256}$/';
const WHSEC_SHAPE = '/^whsec_[A-Za-z0-9_]{16,}$/';
// A prefix glued to a word (`task_live_`) isn't a key, but one after a %XX escape (`secret%3Dsk_live_`) is.
- const REDACT_PATTERN = '/(?\\\\]+/';
+ const REDACT_PATTERN = '/(?]+/';
public static function type($key)
{
diff --git a/includes/class-gf-paystack-restricted-key.php b/includes/class-gf-paystack-restricted-key.php
index 87be077..4d96a46 100644
--- a/includes/class-gf-paystack-restricted-key.php
+++ b/includes/class-gf-paystack-restricted-key.php
@@ -36,6 +36,11 @@ class GF_Paystack_Restricted_Key
protected static $budget_seconds = 15.0;
protected static $deadline = null;
+ protected static function now()
+ {
+ return microtime(true);
+ }
+
public static function reset_budget()
{
self::$deadline = null;
@@ -54,11 +59,13 @@ public static function scope_label($scope)
private static function budget_left()
{
- if (self::$deadline === null) {
- self::$deadline = microtime(true) + static::$budget_seconds;
+ $now = static::now();
+ // A long-lived process must not stay out of budget forever after one slow request.
+ if (self::$deadline === null || $now > self::$deadline + 60) {
+ self::$deadline = $now + static::$budget_seconds;
}
- return microtime(true) < self::$deadline;
+ return $now < self::$deadline;
}
public static function validate($key, $request = null)
@@ -153,7 +160,7 @@ private static function send($request, $key, $method, $path, $body)
}
// Header names are case-insensitive, so a filter's differently-cased Authorization must not survive alongside ours.
foreach (array_keys($headers) as $name) {
- if (preg_match('/^authorization$/i', (string) $name)) {
+ if (strcasecmp(trim((string) $name), 'authorization') === 0) {
unset($headers[$name]);
}
}
diff --git a/readme.txt b/readme.txt
index b1ea135..a14d290 100644
--- a/readme.txt
+++ b/readme.txt
@@ -80,6 +80,7 @@ Yes you can! Join in on our [GitHub repository](https://github.com/PaystackHQ/pl
* Successful-payment (charge.success) webhooks are now confirmed with Paystack before an entry is marked as paid.
* Keys and signing secrets are hidden in logs.
* The key fields are now password inputs.
+* Removed the admin-only ?secret= / ?public= URL override for API keys.
= 2.0.9 - October 28, 2026 =
* Fixed a fatal error on the confirmation page after a successful payment when the usage tracking service is unreachable.
diff --git a/tests/test-keys.php b/tests/test-keys.php
index dfb0181..9e865d6 100644
--- a/tests/test-keys.php
+++ b/tests/test-keys.php
@@ -50,6 +50,7 @@
'query string' => array('x=1&secret=sk_live_abc&y=2', 'x=1&secret=sk_live_[redacted]'),
'rk with &,; chars' => array('k=rk_live_ab&cd,ef;gh_ijklmnop tail', 'k=rk_live_[redacted] tail'),
'json escaped' => array('{"key":"rk_live_abc123"}', '{"key":"rk_live_[redacted]"}'),
+ 'json escaped slash tail' => array('{"k":"rk_live_abcdefghij\\/klmnopTAIL"}', '{"k":"rk_live_[redacted]"}'),
'url encoded' => array('secret%3Dsk_live_abc%26y', 'secret%3Dsk_live_[redacted]'),
'pk' => array('pk_test_abc123', 'pk_test_[redacted]'),
'no secrets' => array('Payment verified for ref gf-9 task_live_x', 'Payment verified for ref gf-9 task_live_x'),
@@ -71,6 +72,10 @@
'whsec at 16 chars' => array(array('live', $sk_live, $sk_live, 'whsec_' . str_repeat('a', 16), '', true), false, null),
'whsec at 15 chars' => array(array('live', $sk_live, $sk_live, 'whsec_' . str_repeat('a', 15), '', true), false, 'whsec_format'),
'whitespace-only other whsec is blank' => array(array('live', $sk_live, $sk_live, $whsec_a, ' ', true), false, null),
+ 'rk containing a double quote' => array(array('live', 'rk_live_abcdefgh"ijklmnopqr', '', $whsec_a, '', true), false, 'invalid_format'),
+ 'rk containing a backslash' => array(array('live', 'rk_live_abcdefgh\\ijklmnopqr', '', $whsec_a, '', true), false, 'invalid_format'),
+ 'rk containing a less-than' => array(array('live', 'rk_live_abcdefgh array(array('live', "rk_live_abcdefgh'ijklmnopqr", '', $whsec_a, '', true), false, 'invalid_format'),
'rk error reports no probe' => array(array('live', $rk_live, '', '', '', true), false, 'whsec_required'),
);
foreach ($keys_extra as $label => $case) {
diff --git a/tests/test-restricted-key.php b/tests/test-restricted-key.php
index bdef3ca..d5f4691 100644
--- a/tests/test-restricted-key.php
+++ b/tests/test-restricted-key.php
@@ -143,6 +143,38 @@ class GF_Paystack_Restricted_Key_Zero extends GF_Paystack_Restricted_Key
});
gf_paystack_test_check($v['code'] === 'unverifiable' && $v['reason'] === 'transient' && strpos($v['probes'], 'transactions:read:200') === 0, 'rk budget exhausted mid-run is unverifiable transient');
+// A new window starts once the old one has been over for more than 60s.
+if (!class_exists('GF_Paystack_Restricted_Key_Clocked')) {
+ class GF_Paystack_Restricted_Key_Clocked extends GF_Paystack_Restricted_Key
+ {
+ public static $time = 1000.0;
+ protected static $budget_seconds = 5.0;
+
+ protected static function now()
+ {
+ return static::$time;
+ }
+ }
+}
+GF_Paystack_Restricted_Key::reset_budget();
+$clock_calls = 0;
+$clock_request = function () use (&$clock_calls) {
+ $clock_calls++;
+
+ return array('status' => 200, 'body' => null);
+};
+GF_Paystack_Restricted_Key_Clocked::$time = 1000.0;
+GF_Paystack_Restricted_Key_Clocked::validate($rk_key, $clock_request);
+$first_calls = $clock_calls;
+GF_Paystack_Restricted_Key_Clocked::$time = 1010.0;
+$clock_calls = 0;
+$v = GF_Paystack_Restricted_Key_Clocked::validate($rk_key, $clock_request);
+gf_paystack_test_check($first_calls > 0 && $clock_calls === 0 && $v['code'] === 'unverifiable', 'rk budget stays spent shortly after the window ends');
+GF_Paystack_Restricted_Key_Clocked::$time = 1066.0;
+$v = GF_Paystack_Restricted_Key_Clocked::validate($rk_key, $clock_request);
+gf_paystack_test_check($clock_calls > 0, 'rk budget opens a new window once the old one is over by more than 60s');
+GF_Paystack_Restricted_Key::reset_budget();
+
// Budget is shared across calls: a second validate() in the same request gets what the first left.
GF_Paystack_Restricted_Key::reset_budget();
$slow_ok = function ($m, $u, $h, $b) use ($rk_make, $rk_ok_map, $scope_msg) {
@@ -214,6 +246,15 @@ class GF_Paystack_Restricted_Key_Zero extends GF_Paystack_Restricted_Key
});
gf_paystack_test_check(count($auth_keys) === 1 && $sent_headers['Authorization'] === 'Bearer ' . $rk_key && $sent_headers['X-Extra'] === '1', 'rk probe headers keep a single Authorization with the saved key');
+foreach (array(' Authorization', 'authorization ') as $odd_name) {
+ $GLOBALS['gf_paystack_test_remote_calls'] = array();
+ $GLOBALS['gf_paystack_test_filters']['gf_paystack_request_headers'] = array($odd_name => 'Bearer other', 'X-Extra' => '1');
+ GF_Paystack_Restricted_Key::validate($rk_key);
+ $sent_headers = $GLOBALS['gf_paystack_test_remote_calls'][0][1]['headers'];
+ unset($GLOBALS['gf_paystack_test_filters']['gf_paystack_request_headers']);
+ gf_paystack_test_check(array_keys($sent_headers) === array('X-Extra', 'Authorization') && $sent_headers['Authorization'] === 'Bearer ' . $rk_key, 'rk probe strips a padded Authorization header name: ' . json_encode($odd_name));
+}
+
// # Coverage additions (dedicated test pass)
$rk_pinned = array(
diff --git a/tests/test-settings.php b/tests/test-settings.php
index f41e0cb..01cd12b 100644
--- a/tests/test-settings.php
+++ b/tests/test-settings.php
@@ -112,7 +112,7 @@
gf_paystack_test_check($a->plans_calls === array($st_rk_live), 'settings save treats a feed without a mode as live');
$a = $st_run('live', $rk_posted, array(), $with_feeds(array($sub_feed('live')), 'plans_missing'), 'key');
-gf_paystack_test_check($a->field_errors['live_secret_key'] === 'Subscriptions need Plans: write on your live restricted key. Add it in your Paystack Dashboard, then save this feed again.' . $st_suffix, 'settings save plans_missing error on the key field');
+gf_paystack_test_check($a->field_errors['live_secret_key'] === 'Subscriptions need Plans: write on your live restricted key. Add it in your Paystack Dashboard, then save these settings again.' . $st_suffix, 'settings save plans_missing error on the key field');
$a = $st_run('live', $rk_posted, array(), $with_feeds(array($sub_feed('live')), 'plans_mor'), 'key');
gf_paystack_test_check($a->field_errors['live_secret_key'] === 'Paystack subscriptions aren\'t available for merchant-of-record accounts.' . $st_suffix, 'settings save plans_mor error on the key field');
@@ -120,8 +120,14 @@
$a = $st_run('live', $rk_posted, array(), $with_feeds(array($sub_feed('live')), 'unverifiable'), 'key');
gf_paystack_test_check(strpos($a->field_errors['live_secret_key'], 'We couldn\'t reach Paystack') === 0, 'settings save plans unverifiable error on the key field');
-$a = $st_run('live', $rk_posted, array(), $with_feeds(array($sub_feed('test'), $sub_feed('live', '0'), $sub_feed('live', '1', 'product')), 'plans_missing'), 'key');
-gf_paystack_test_check($a->field_errors === array() && $a->plans_calls === array(), 'settings save skips plans when no active subscription feed uses that mode');
+$a = $st_run('live', $rk_posted, array(), $with_feeds(array($sub_feed('test'), $sub_feed('live', '1', 'product')), 'plans_missing'), 'key');
+gf_paystack_test_check($a->field_errors === array() && $a->plans_calls === array(), 'settings save skips plans when no subscription feed uses that mode');
+
+$a = $st_run('live', $rk_posted, array(), $with_feeds(array($sub_feed('live', '0'))), 'key');
+gf_paystack_test_check($a->plans_calls === array($st_rk_live), 'settings save probes plans for an inactive subscription feed too');
+
+$a = $st_run('test', array('test_secret_key' => $st_rk_test, 'test_webhook_secret' => $st_ws_test), array('api_mode' => 'test'), $with_feeds(array($sub_feed(null))), 'key');
+gf_paystack_test_check($a->plans_calls === array($st_rk_test), 'settings save treats a feed without a mode as the global api mode');
$a2 = $st_run('live', $rk_posted, array(), function ($addon) use ($sub_feed, $verdict) {
$addon->feeds = array($sub_feed('live'));
@@ -333,3 +339,35 @@ public function get_field($name, $fields)
gf_paystack_test_check($st_reader->get_webhook_secret('test') === $st_ws_test && $st_reader->get_webhook_secret('live') === $st_ws_live && $st_reader->get_webhook_secret('live', array()) === $st_ws_live, 'settings get_webhook_secret is per mode, trimmed, and falls back to plugin settings');
gf_paystack_test_check($st_reader->get_stored_secret_key('test') === $st_sk_test && $st_reader->get_stored_secret_key('live', array('live_secret_key' => 'x')) === 'x', 'settings get_stored_secret_key is per mode, trimmed, and prefers passed settings');
gf_paystack_test_check($st_reader->get_webhook_secret('test', array('test_webhook_secret' => $st_ws_live)) === $st_ws_live && (new GFPaystackSettingsFixture())->get_webhook_secret('test') === '', 'settings get_webhook_secret prefers passed settings and defaults to blank');
+
+// Feed: callback arguments, object fields and the global-mode default.
+class GFPaystackFeedArgsFixture extends GFPaystackFeedWiringFixture
+{
+ public $parent_args = array();
+
+ public function set_transaction_type_callback($callback)
+ {
+ $this->transaction_type_callback = $callback;
+ }
+
+ public function parent_callback($field, $value = null)
+ {
+ $this->parent_args = func_get_args();
+ }
+}
+
+$args_addon = new GFPaystackFeedArgsFixture();
+$args_addon->posted = array('transactionType' => 'product');
+$args_fields = $args_addon->feed_settings_fields();
+$args_addon->set_transaction_type_callback(array($args_addon, 'parent_callback'));
+$args_addon->validate_subscription_plans($feed_field, 'product');
+gf_paystack_test_check(count($args_addon->parent_args) === 2 && $args_addon->parent_args[1] === 'product', 'feed existing transactionType callback receives both arguments');
+
+$obj_field = (object) array('name' => 'transactionType', 'choices' => array(array('label' => 'Subscription', 'value' => 'subscription')));
+$a = $feed_run(array('transactionType' => 'product'), array(), 'ok', null, $obj_field);
+gf_paystack_test_check($a->field_errors === array('transactionType' => 'This field is required.'), 'feed object field choices are enforced');
+$a = $feed_run(array('transactionType' => 'subscription', 'mode' => 'test'), array('test_secret_key' => $st_rk_test), 'ok', null, $obj_field);
+gf_paystack_test_check($a->field_errors === array() && $a->plans_calls === array($st_rk_test), 'feed object field accepts a listed choice');
+
+$a = $feed_run(array('transactionType' => 'subscription'), array('api_mode' => 'test', 'test_secret_key' => $st_rk_test, 'live_secret_key' => $st_rk_live));
+gf_paystack_test_check($a->plans_calls === array($st_rk_test), 'feed without a mode follows the global api mode');
diff --git a/tests/test-webhook.php b/tests/test-webhook.php
index b55ca67..f8b6d53 100644
--- a/tests/test-webhook.php
+++ b/tests/test-webhook.php
@@ -89,6 +89,11 @@
$result = gf_paystack_callback_run(gf_paystack_charge_event(), 'live', $stored, null, null, $throwing_charge_api);
gf_paystack_test_check(is_wp_error($result) && $result->code === 'transaction_verification' && rgar($result->get_error_data(), 'status_header') === 500, 'callback case 32: verify throws asks Paystack to retry');
+gf_paystack_test_check(is_wp_error($result) && $result->get_error_message() === 'Transaction could not be verified.' && strpos($result->get_error_message(), 'request failed') === false, 'callback case 32b: verify failure message is fixed');
+
+$result = gf_paystack_callback_run(gf_paystack_charge_event(array('id' => '')), 'live', $stored, null, null, $charge_api(array('id' => '')));
+gf_paystack_test_check($result === false, 'callback case 33b: verified charge with an empty id is not completed');
+
$result = gf_paystack_callback_run(gf_paystack_charge_event(), 'live', $stored, null, null, $charge_api(array('id' => null)));
gf_paystack_test_check($result === false, 'callback case 33: verified charge without an id is not completed');
@@ -417,9 +422,13 @@ public function set_mode($mode)
gf_paystack_test_check(is_array($event_addon($both_sk)->get_webhook_event($event_body)), 'domain missing, no whsec: api mode key verifies');
$one_whsec = array('api_mode' => 'live', 'live_secret_key' => $sk_live, 'test_secret_key' => 'sk_test_abc123', 'test_webhook_secret' => $test_whsec);
+$_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] = hash_hmac('sha512', $event_body, 'sk_other');
+$addon = $event_addon($one_whsec);
+gf_paystack_test_check($addon->get_webhook_event($event_body) === false && $addon->webhook_mode_value() === 'live' && strpos($addon->errors[0], 'checks=test:whsec:malformed') !== false && strpos($addon->errors[0], 'live:legacy:invalid') !== false, 'domain missing: whsec modes first, then the api mode');
+
$_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] = hash_hmac('sha512', $event_body, $sk_live);
$addon = $event_addon($one_whsec);
-gf_paystack_test_check($addon->get_webhook_event($event_body) === false && $addon->webhook_mode_value() === 'test' && strpos($addon->errors[0], 'checks=test:whsec:malformed') !== false, 'domain missing: only modes with a whsec are candidates');
+gf_paystack_test_check(is_array($addon->get_webhook_event($event_body)) && $addon->webhook_mode_value() === 'live', 'domain missing: whsec in test, api mode live still verifies a legacy-signed event');
$reset_sig_headers();
// ?secret= must not change the verifying key
From 53614de4ea4e0892c1c732af1576845b7ac13157 Mon Sep 17 00:00:00 2001
From: Jules Nsenda
Date: Wed, 18 Nov 2026 21:33:10 +0200
Subject: [PATCH 12/19] refactor: simplify restricted-key settings, webhook
mode and probe helpers
No behaviour change: shared helpers for the other mode, save errors and
stored settings; webhook candidate modes in their own method; one request
default and verdict builder in the probe class; a cheaper log redactor.
Co-Authored-By: Claude Opus 5.5
---
class-gf-paystack.php | 182 ++++++------------
includes/class-gf-paystack-keys.php | 27 +--
includes/class-gf-paystack-restricted-key.php | 36 ++--
3 files changed, 83 insertions(+), 162 deletions(-)
diff --git a/class-gf-paystack.php b/class-gf-paystack.php
index 917b147..c2d5700 100644
--- a/class-gf-paystack.php
+++ b/class-gf-paystack.php
@@ -1761,27 +1761,7 @@ public function get_webhook_event($body = null)
$settings = $this->get_plugin_settings();
- $domain_mode = self::resolve_webhook_mode(rgars($response, 'data/domain'));
-
- if ($domain_mode) {
- $candidates = array($domain_mode);
- } else {
- $candidates = array();
- foreach (array('live', 'test') as $candidate_mode) {
- if ($this->get_webhook_secret($candidate_mode, $settings) !== '') {
- $candidates[] = $candidate_mode;
- }
- }
-
- $api_mode = $this->get_api_mode($settings);
- if (!in_array($api_mode, $candidates, true)) {
- $candidates[] = $api_mode;
- }
- }
-
- if (empty($candidates)) {
- $candidates = array($this->get_api_mode($settings));
- }
+ $candidates = $this->webhook_candidate_modes($response, $settings);
$check = null;
$mode = null;
@@ -1789,7 +1769,6 @@ public function get_webhook_event($body = null)
foreach ($candidates as $candidate_mode) {
$this->paystack_api($candidate_mode, $settings);
- // Validate Webhook Request Payload
try {
$is_verified = $this->paystack_api->validate_webhook($body);
} catch (\Exception $e) {
@@ -1819,13 +1798,36 @@ public function get_webhook_event($body = null)
return false;
}
- $this->log_debug(sprintf('%s(): Webhook verified. sig=%s result=%s', __METHOD__, rgar($check, 'sig'), rgar($check, 'result')));
-
- $this->log_debug(__METHOD__ . "(): Processing {$this->webhook_mode} mode event.");
+ $this->log_debug(sprintf('%s(): Webhook verified. Processing %s mode event. sig=%s result=%s', __METHOD__, $this->webhook_mode, rgar($check, 'sig'), rgar($check, 'result')));
return $response;
}
+ /**
+ * A payload's own domain decides the mode; otherwise try each mode with a signing secret, then the global mode.
+ */
+ private function webhook_candidate_modes($response, $settings)
+ {
+ $domain_mode = self::resolve_webhook_mode(rgars($response, 'data/domain'));
+ if ($domain_mode) {
+ return array($domain_mode);
+ }
+
+ $candidates = array();
+ foreach (array('live', 'test') as $candidate_mode) {
+ if ($this->get_webhook_secret($candidate_mode, $settings) !== '') {
+ $candidates[] = $candidate_mode;
+ }
+ }
+
+ $api_mode = $this->get_api_mode($settings);
+ if (!in_array($api_mode, $candidates, true)) {
+ $candidates[] = $api_mode;
+ }
+
+ return $candidates;
+ }
+
/**
* Generate the url Paystack webhooks should be sent to.
*
@@ -2063,28 +2065,20 @@ public function paystack_api($mode = null, $settings = null)
return $this->paystack_api = new GFPaystackApi($config);
}
- /**
- * Reads straight from stored settings.
- *
- * @param string $mode
- * @param array|null $settings
- *
- * @return string
- */
public function get_webhook_secret($mode, $settings = null)
{
- return trim((string) rgar(empty($settings) ? $this->get_plugin_settings() : $settings, "{$mode}_webhook_secret"));
+ return $this->stored_setting("{$mode}_webhook_secret", $settings);
}
- /**
- * @param string $mode
- * @param array|null $settings
- *
- * @return string
- */
public function get_stored_secret_key($mode, $settings = null)
{
- return trim((string) rgar(empty($settings) ? $this->get_plugin_settings() : $settings, "{$mode}_secret_key"));
+ return $this->stored_setting("{$mode}_secret_key", $settings);
+ }
+
+ // Reads straight from stored settings.
+ private function stored_setting($name, $settings)
+ {
+ return trim((string) rgar(empty($settings) ? $this->get_plugin_settings() : $settings, $name));
}
// # KEY VALIDATION ------------------------------------------------------------------------------------------------
@@ -2092,8 +2086,6 @@ public function get_stored_secret_key($mode, $settings = null)
/**
* Validation compares trimmed values, so store them trimmed too: a pasted key with a trailing space would
* otherwise pass validation but break the Authorization header.
- *
- * @param array $settings
*/
public function update_plugin_settings($settings)
{
@@ -2128,14 +2120,8 @@ public function validate_live_webhook_secret($field)
$this->validate_webhook_secret_for_mode('live');
}
- /**
- * @param string $mode 'test' or 'live'.
- *
- * @return array A GF_Paystack_Keys::resolve_save() result.
- */
protected function resolve_posted_key($mode)
{
- $other = $mode === 'test' ? 'live' : 'test';
$settings = $this->get_posted_settings();
return GF_Paystack_Keys::resolve_save(
@@ -2143,40 +2129,28 @@ protected function resolve_posted_key($mode)
trim((string) rgar($settings, "{$mode}_secret_key")),
$this->get_plugin_setting("{$mode}_secret_key"),
rgar($settings, "{$mode}_webhook_secret"),
- rgar($settings, "{$other}_webhook_secret"),
+ rgar($settings, $this->other_mode($mode) . '_webhook_secret'),
GF_Paystack_Keys::restricted_keys_enabled()
);
}
- /**
- * @param string $mode 'test' or 'live'.
- *
- * @return void
- */
protected function validate_webhook_secret_for_mode($mode)
{
$result = $this->resolve_posted_key($mode);
if ($result['error'] !== null && strpos($result['error'], 'whsec_') === 0) {
- $other = $mode === 'test' ? 'live' : 'test';
- $this->set_field_error(array('name' => "{$mode}_webhook_secret"), $this->key_error_message($result['error'], $mode, $other) . $this->not_saved_suffix());
+ $this->set_save_error("{$mode}_webhook_secret", $this->key_error_message($result['error'], $mode));
}
}
- /**
- * @param string $mode 'test' or 'live'.
- *
- * @return void
- */
protected function validate_secret_key_for_mode($mode)
{
- $other = $mode === 'test' ? 'live' : 'test';
$key = trim((string) rgar($this->get_posted_settings(), "{$mode}_secret_key"));
$result = $this->resolve_posted_key($mode);
if ($result['error'] !== null) {
if (strpos($result['error'], 'whsec_') !== 0) {
- $this->set_field_error(array('name' => "{$mode}_secret_key"), $this->key_error_message($result['error'], $mode, $other) . $this->not_saved_suffix());
+ $this->set_save_error("{$mode}_secret_key", $this->key_error_message($result['error'], $mode));
}
return;
}
@@ -2189,23 +2163,18 @@ protected function validate_secret_key_for_mode($mode)
$this->log_debug("rk validate mode={$mode} code={$verdict['code']} probes={$verdict['probes']}");
if ($verdict['code'] !== 'ok') {
- $this->set_field_error(array('name' => "{$mode}_secret_key"), $this->probe_error_message($verdict) . $this->not_saved_suffix());
+ $this->set_save_error("{$mode}_secret_key", $this->probe_error_message($verdict));
return;
}
if ($this->has_subscription_feed($mode)) {
$plans = $this->probe_restricted_key_plans($key);
if ($plans !== 'ok') {
- $this->set_field_error(array('name' => "{$mode}_secret_key"), $this->plans_error_message($plans, $mode, 'settings') . $this->not_saved_suffix());
+ $this->set_save_error("{$mode}_secret_key", $this->plans_error_message($plans, $mode, 'settings'));
}
}
}
- /**
- * @param string $mode 'test' or 'live'.
- *
- * @return bool
- */
protected function has_subscription_feed($mode)
{
foreach ((array) $this->get_feeds() as $feed) {
@@ -2217,36 +2186,22 @@ protected function has_subscription_feed($mode)
return false;
}
- /**
- * @param array|false $feed
- *
- * @return string 'test' or 'live'; a feed without a mode follows the global API mode.
- */
+ // A feed without a mode follows the global API mode.
protected function feed_mode($feed)
{
- $mode = rgars($feed, 'meta/mode');
- if ($mode === 'test' || $mode === 'live') {
+ $mode = self::resolve_webhook_mode(rgars($feed, 'meta/mode'));
+ if ($mode) {
return $mode;
}
return $this->get_api_mode($this->get_plugin_settings()) === 'test' ? 'test' : 'live';
}
- /**
- * @param string $key
- *
- * @return array
- */
protected function validate_restricted_key($key)
{
return GF_Paystack_Restricted_Key::validate($key);
}
- /**
- * @param string $key
- *
- * @return string
- */
protected function probe_restricted_key_plans($key)
{
return GF_Paystack_Restricted_Key::probe_plans($key);
@@ -2254,11 +2209,6 @@ protected function probe_restricted_key_plans($key)
/**
* Subscription feeds need Plans: write, which the settings probe doesn't check.
- *
- * @param array|object $field The transactionType field.
- * @param mixed $value The submitted value, when the caller passes one.
- *
- * @return void
*/
public function validate_subscription_plans($field, $value = null)
{
@@ -2304,21 +2254,12 @@ public function validate_subscription_plans($field, $value = null)
}
}
- /**
- * @param string $result A probe_plans() code other than 'ok'.
- * @param string $mode 'test' or 'live'.
- * @param string $context 'feed' or 'settings'.
- *
- * @return string
- */
protected function plans_error_message($result, $mode, $context = 'feed')
{
if ($result === 'plans_missing') {
- if ($context === 'settings') {
- return sprintf(esc_html__('Subscriptions need Plans: write on your %s restricted key. Add it in your Paystack Dashboard, then save these settings again.', 'gravityformspaystack'), $mode);
- }
+ $again = $context === 'settings' ? __('these settings', 'gravityformspaystack') : __('this feed', 'gravityformspaystack');
- return sprintf(esc_html__('Subscriptions need Plans: write on your %s restricted key. Add it in your Paystack Dashboard, then save this feed again.', 'gravityformspaystack'), $mode);
+ return sprintf(esc_html__('Subscriptions need Plans: write on your %1$s restricted key. Add it in your Paystack Dashboard, then save %2$s again.', 'gravityformspaystack'), $mode, esc_html($again));
}
if ($result === 'plans_mor') {
@@ -2328,26 +2269,21 @@ protected function plans_error_message($result, $mode, $context = 'feed')
return esc_html__('We couldn\'t reach Paystack to check this key. Please try again.', 'gravityformspaystack');
}
- /**
- * @return string
- */
- protected function not_saved_suffix()
+ protected function set_save_error($field_name, $message)
{
- return ' ' . esc_html__('No settings were saved.', 'gravityformspaystack');
+ $this->set_field_error(array('name' => $field_name), $message . ' ' . esc_html__('No settings were saved.', 'gravityformspaystack'));
}
- /**
- * @param string $code A GF_Paystack_Keys::resolve_save() error code.
- * @param string $mode
- * @param string $other
- *
- * @return string
- */
- protected function key_error_message($code, $mode, $other)
+ private function other_mode($mode)
+ {
+ return $mode === 'test' ? 'live' : 'test';
+ }
+
+ protected function key_error_message($code, $mode)
{
switch ($code) {
case 'wrong_field':
- return sprintf(esc_html__('This is a %1$s key. Paste it in the %1$s secret key field.', 'gravityformspaystack'), $other);
+ return sprintf(esc_html__('This is a %1$s key. Paste it in the %1$s secret key field.', 'gravityformspaystack'), $this->other_mode($mode));
case 'invalid_format':
return sprintf(esc_html__('Secret keys start with sk_%1$s_ and restricted keys with rk_%1$s_. Check you copied the whole key.', 'gravityformspaystack'), $mode);
case 'rk_disabled':
@@ -2363,11 +2299,6 @@ protected function key_error_message($code, $mode, $other)
return esc_html__('Paystack didn\'t accept this key.', 'gravityformspaystack');
}
- /**
- * @param array $verdict A GF_Paystack_Restricted_Key::validate() result.
- *
- * @return string
- */
protected function probe_error_message($verdict)
{
switch ($verdict['code']) {
@@ -2392,11 +2323,6 @@ protected function probe_error_message($verdict)
return esc_html__('We couldn\'t reach Paystack to check this key. Please try again.', 'gravityformspaystack');
}
- /**
- * @param array $scopes Scope ids.
- *
- * @return string
- */
protected function scope_labels($scopes)
{
$out = array();
diff --git a/includes/class-gf-paystack-keys.php b/includes/class-gf-paystack-keys.php
index 61853df..fdaac19 100644
--- a/includes/class-gf-paystack-keys.php
+++ b/includes/class-gf-paystack-keys.php
@@ -9,24 +9,25 @@ final class GF_Paystack_Keys
const RK_SHAPE = '/^rk_(?:test|live)_[\x21\x23-\x26\x28-\x3b\x3d\x3f-\x5b\x5d-\x7e]{16,256}$/';
const WHSEC_SHAPE = '/^whsec_[A-Za-z0-9_]{16,}$/';
// A prefix glued to a word (`task_live_`) isn't a key, but one after a %XX escape (`secret%3Dsk_live_`) is.
- const REDACT_PATTERN = '/(?]+/';
+ const REDACT_PATTERN = '/(?]+/';
public static function type($key)
{
- if (is_string($key) && preg_match('/^(sk|rk)_(?:live|test)_/', $key, $m)) {
- return $m[1];
- }
-
- return null;
+ return self::parse($key)[0];
}
public static function mode($key)
{
- if (is_string($key) && preg_match('/^(?:sk|rk)_(live|test)_/', $key, $m)) {
- return $m[1];
+ return self::parse($key)[1];
+ }
+
+ private static function parse($key)
+ {
+ if (is_string($key) && preg_match('/^(sk|rk)_(live|test)_/', $key, $m)) {
+ return array($m[1], $m[2]);
}
- return null;
+ return array(null, null);
}
public static function is_whsec_shaped($value)
@@ -87,14 +88,16 @@ public static function redact($string)
return $string;
}
+ if (strpos($string, '_live_') === false && strpos($string, '_test_') === false && strpos($string, 'whsec_') === false) {
+ return $string;
+ }
+
return preg_replace_callback(self::REDACT_PATTERN, array(__CLASS__, 'redact_match'), $string);
}
private static function redact_match($match)
{
- preg_match('/^(?:(?:sk|rk|pk)_(?:live|test)_|whsec_)/', $match[0], $prefix);
-
- return $prefix[0] . '[redacted]';
+ return $match[1] . '[redacted]';
}
private static function result($probe, $error)
diff --git a/includes/class-gf-paystack-restricted-key.php b/includes/class-gf-paystack-restricted-key.php
index 4d96a46..db133eb 100644
--- a/includes/class-gf-paystack-restricted-key.php
+++ b/includes/class-gf-paystack-restricted-key.php
@@ -71,10 +71,6 @@ private static function budget_left()
public static function validate($key, $request = null)
{
try {
- if (!is_callable($request)) {
- $request = array(__CLASS__, 'default_request');
- }
-
$results = array();
$baseline = null;
@@ -98,17 +94,13 @@ public static function validate($key, $request = null)
return self::decide($results);
} catch (\Throwable $e) {
- return self::verdict('unverifiable', array(), array(), 'transient');
+ return self::verdict('unverifiable', array(), array('reason' => 'transient'));
}
}
public static function probe_plans($key, $request = null)
{
try {
- if (!is_callable($request)) {
- $request = array(__CLASS__, 'default_request');
- }
-
if (!self::budget_left()) {
return 'unverifiable';
}
@@ -154,6 +146,10 @@ public static function default_request($method, $url, $headers, $body)
private static function send($request, $key, $method, $path, $body)
{
+ if (!is_callable($request)) {
+ $request = array(__CLASS__, 'default_request');
+ }
+
$headers = apply_filters('gf_paystack_request_headers', array('Authorization' => 'Bearer ' . $key, 'Content-Type' => 'application/json'));
if (!is_array($headers)) {
$headers = array();
@@ -225,7 +221,7 @@ private static function classify($probe, $response, $baseline)
private static function decide($results)
{
if ($results[0]['outcome'] === 'invalid') {
- return self::verdict('invalid_key', array(), array(), null, $results);
+ return self::verdict('invalid_key', $results);
}
$missing = array();
@@ -243,10 +239,10 @@ private static function decide($results)
}
if ($missing) {
- return self::verdict('missing_scope', $missing, $sensitive, null, $results);
+ return self::verdict('missing_scope', $results, array('scopes' => $missing, 'sensitive_scopes' => $sensitive));
}
if ($sensitive) {
- return self::verdict('sensitive_scope', array(), $sensitive, null, $results);
+ return self::verdict('sensitive_scope', $results, array('sensitive_scopes' => $sensitive));
}
if ($indeterminate) {
$reason = 'transient';
@@ -256,13 +252,13 @@ private static function decide($results)
}
}
- return self::verdict('unverifiable', array(), array(), $reason, $results);
+ return self::verdict('unverifiable', $results, array('reason' => $reason));
}
- return self::verdict('ok', array(), array(), null, $results);
+ return self::verdict('ok', $results);
}
- private static function verdict($code, $scopes, $sensitive_scopes, $reason, $results = array())
+ private static function verdict($code, $results = array(), $extra = array())
{
$parts = array();
foreach ($results as $r) {
@@ -271,13 +267,9 @@ private static function verdict($code, $scopes, $sensitive_scopes, $reason, $res
}
}
- return array(
- 'code' => $code,
- 'scopes' => $scopes,
- 'sensitive_scopes' => $sensitive_scopes,
- 'reason' => $reason,
- 'probes' => $parts ? implode(',', $parts) : '-',
- );
+ $defaults = array('scopes' => array(), 'sensitive_scopes' => array(), 'reason' => null);
+
+ return array('code' => $code) + array_merge($defaults, $extra) + array('probes' => $parts ? implode(',', $parts) : '-');
}
}
}
From 721f480464e9f6bab1001daaa50f73bf91ec7210 Mon Sep 17 00:00:00 2001
From: Jules Nsenda
Date: Thu, 19 Nov 2026 07:50:08 +0200
Subject: [PATCH 13/19] chore: release 2.0.10
Co-Authored-By: Claude Opus 5.5
---
paystack.php | 4 ++--
readme.txt | 7 +++++--
2 files changed, 7 insertions(+), 4 deletions(-)
diff --git a/paystack.php b/paystack.php
index 7f0d5ad..fbf8417 100644
--- a/paystack.php
+++ b/paystack.php
@@ -4,7 +4,7 @@
Plugin URI: https://paystack.com/docs/libraries-and-plugins/plugins#wordpress
0
Description: Integrates Gravity Forms with Paystack, enabling customers to pay for goods and services through Gravity Forms.
-Version: 2.0.9
+Version: 2.0.10
Author: Paystack
Author URI: https://developers.paystack.com
License: GPL-2.0+
@@ -31,7 +31,7 @@
defined('ABSPATH') || die();
-define('GF_PAYSTACK_VERSION', '2.0.9');
+define('GF_PAYSTACK_VERSION', '2.0.10');
require_once __DIR__ . '/includes/php-advisory.php';
add_action('admin_notices', 'gf_paystack_php_advisory_notice');
diff --git a/readme.txt b/readme.txt
index a14d290..57e3c49 100644
--- a/readme.txt
+++ b/readme.txt
@@ -5,7 +5,7 @@ Tags: payments, subscriptions, gravityforms
Requires at least: 5.1
Tested up to: 7.1
Requires PHP: 7.2
-Stable tag: 2.0.9
+Stable tag: 2.0.10
License: GPLv2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
@@ -74,7 +74,7 @@ Yes you can! Join in on our [GitHub repository](https://github.com/PaystackHQ/pl
== Changelog ==
-= Unreleased =
+= 2.0.10 - November 19, 2026 =
* Added support for Paystack restricted keys (`rk_test_...` / `rk_live_...`).
* Added Test and Live webhook signing secret fields, and webhook signature verification when one is set.
* Successful-payment (charge.success) webhooks are now confirmed with Paystack before an entry is marked as paid.
@@ -123,6 +123,9 @@ Yes you can! Join in on our [GitHub repository](https://github.com/PaystackHQ/pl
== Upgrade Notice ==
+= 2.0.10 =
+* Adds optional Paystack restricted keys and webhook signing secrets. Existing secret keys keep working with no changes needed. The ?secret= / ?public= URL override has been removed.
+
= 2.0.9 =
* Fixes a fatal error customers could see after paying. Please update.
From afb04e9748278174bc2efc278a4b0b8cd4beaeec Mon Sep 17 00:00:00 2001
From: Jules Nsenda
Date: Thu, 19 Nov 2026 21:01:54 +0200
Subject: [PATCH 14/19] feat: accept only restricted keys for new keys and show
one mode at a time
New or changed keys must be rk_ keys; an sk_ key saved by an earlier
version keeps working until it is replaced. The public key fields are
gone (payments never used them). Test and Live fields show only for the
selected mode, so credentials are validated from the Mode field for both
modes: Gravity Forms skips validation of fields a dependency hides but
still saves their values. Requires Gravity Forms 2.5.
Co-Authored-By: Claude Opus 5.5
---
class-gf-paystack-api.php | 10 --
class-gf-paystack.php | 136 +++++++++++++---------------
includes/class-gf-paystack-keys.php | 24 ++---
readme.txt | 19 ++--
tests/test-keys.php | 77 ++++++++--------
tests/test-settings.php | 87 +++++++++++++-----
tests/test-webhook.php | 4 +-
7 files changed, 186 insertions(+), 171 deletions(-)
diff --git a/class-gf-paystack-api.php b/class-gf-paystack-api.php
index a828cca..63588f0 100644
--- a/class-gf-paystack-api.php
+++ b/class-gf-paystack-api.php
@@ -10,7 +10,6 @@ class GFPaystackApi
{
public $plugin_name;
- protected $public_key;
protected $secret_key;
@@ -25,7 +24,6 @@ public function __construct($config)
{
$this->plugin_name = 'Paystack Addon for Gravity Forms';
$this->secret_key = $config->secret_key ?? '';
- $this->public_key = $config->public_key ?? '';
$this->webhook_secret = $config->webhook_secret ?? '';
$this->stored_secret_key = $config->stored_secret_key ?? '';
}
@@ -38,16 +36,8 @@ public function __construct($config)
*/
public function log_transaction_success($reference)
{
- // Send reference to logger along with plugin name and public key
- // $params = [
- // 'plugin_name' => $this->plugin_name,
- // 'public_key' => $this->public_key,
- // 'transaction_reference' => $reference
- // ];
-
$params = [
'plugin_name' => 'pstk-gravityforms',
- 'public_key' => $this->public_key,
'transaction_reference' => $reference
];
diff --git a/class-gf-paystack.php b/class-gf-paystack.php
index c2d5700..b41a8a4 100644
--- a/class-gf-paystack.php
+++ b/class-gf-paystack.php
@@ -56,7 +56,7 @@ class GFPaystack extends GFPaymentAddOn
*
* @var string $_min_gravityforms_version The minimum version required.
*/
- protected $_min_gravityforms_version = '2.0';
+ protected $_min_gravityforms_version = '2.5';
/**
* Defines the plugin slug.
@@ -301,10 +301,11 @@ public function plugin_settings_fields()
*/
public function api_settings_fields()
{
- $api_mode = '';
+ // Each mode's fields only show while that mode is selected, so a first-time setup starts in Test.
+ $api_mode = 'test';
- if ($this->is_detail_page() && empty($api_mode)) {
- $api_mode = $this->get_plugin_setting('api_mode');
+ if ($this->is_detail_page()) {
+ $api_mode = $this->get_plugin_setting('api_mode') ?: 'test';
}
$fields = array(
@@ -313,6 +314,7 @@ public function api_settings_fields()
'label' => esc_html__('Mode', 'gravityformspaystack'),
'type' => 'radio',
'default_value' => $api_mode,
+ 'validation_callback' => array($this, 'validate_credentials'),
'choices' => array(
array(
'label' => esc_html__('Live', 'gravityformspaystack'),
@@ -327,24 +329,18 @@ public function api_settings_fields()
)
);
- $key_help = '' . esc_html__('Secret or Restricted Key', 'gravityformspaystack') . '
' . esc_html__('A restricted key limits what this plugin can do with your Paystack account. Create one in your Paystack Dashboard with Transactions: read and write, plus Plans: write if you sell subscriptions.', 'gravityformspaystack');
- $whsec_help = '' . esc_html__('Webhook Signing Secret', 'gravityformspaystack') . '
' . esc_html__('Copy it from Settings → API Keys & Webhooks in your Paystack Dashboard. Required with a restricted key.', 'gravityformspaystack');
+ $key_help = '' . esc_html__('Restricted Key', 'gravityformspaystack') . '
' . esc_html__('Create a restricted key in your Paystack Dashboard with Transactions: read and write, plus Plans: write if you sell subscriptions.', 'gravityformspaystack');
+ $whsec_help = '' . esc_html__('Webhook Signing Secret', 'gravityformspaystack') . '
' . esc_html__('Copy it from Settings → API Keys & Webhooks in your Paystack Dashboard.', 'gravityformspaystack');
$credentials_fields = array(
array(
- 'name' => 'test_public_key',
- 'label' => esc_html__('Test Public Key', 'gravityformspaystack'),
- 'type' => 'text',
- 'class' => 'medium',
- ),
- array(
'name' => 'test_secret_key',
- 'label' => esc_html__('Test Secret or Restricted Key', 'gravityformspaystack'),
+ 'label' => esc_html__('Test Restricted Key', 'gravityformspaystack'),
'type' => 'text',
'input_type' => 'password',
'class' => 'medium',
'tooltip' => $key_help,
- 'validation_callback' => array($this, 'validate_test_secret_key'),
+ 'dependency' => $this->mode_dependency('test'),
),
array(
'name' => 'test_webhook_secret',
@@ -353,22 +349,16 @@ public function api_settings_fields()
'input_type' => 'password',
'class' => 'medium',
'tooltip' => $whsec_help,
- 'validation_callback' => array($this, 'validate_test_webhook_secret'),
- ),
- array(
- 'name' => 'live_public_key',
- 'label' => esc_html__('Live Public Key', 'gravityformspaystack'),
- 'type' => 'text',
- 'class' => 'medium',
+ 'dependency' => $this->mode_dependency('test'),
),
array(
'name' => 'live_secret_key',
- 'label' => esc_html__('Live Secret or Restricted Key', 'gravityformspaystack'),
+ 'label' => esc_html__('Live Restricted Key', 'gravityformspaystack'),
'type' => 'text',
'input_type' => 'password',
'class' => 'medium',
'tooltip' => $key_help,
- 'validation_callback' => array($this, 'validate_live_secret_key'),
+ 'dependency' => $this->mode_dependency('live'),
),
array(
'name' => 'live_webhook_secret',
@@ -377,7 +367,7 @@ public function api_settings_fields()
'input_type' => 'password',
'class' => 'medium',
'tooltip' => $whsec_help,
- 'validation_callback' => array($this, 'validate_live_webhook_secret'),
+ 'dependency' => $this->mode_dependency('live'),
),
);
@@ -407,6 +397,15 @@ public function api_settings_fields()
return $fields;
}
+ // Gravity Forms 2.5+ live dependency: the field shows and hides as the Mode radio changes.
+ protected function mode_dependency($mode)
+ {
+ return array(
+ 'live' => true,
+ 'fields' => array(array('field' => 'api_mode', 'values' => array($mode))),
+ );
+ }
+
/**
* Define the markup to be displayed for the webhooks section description.
*
@@ -441,7 +440,7 @@ public function get_webhooks_section_description()
-
+
@@ -2036,7 +2035,6 @@ public function get_paystack_meta_data($feed, $entry, $form)
* @used-by GFPaystack::subscribe()
* @uses GFAddOn::get_base_path()
* @uses GFPaystack::get_secret_api_key()
- * @uses GFPaystack::get_public_api_key()
*
* @param null|string $mode The API mode; live or test.
* @param null|array $settings The settings.
@@ -2055,7 +2053,6 @@ public function paystack_api($mode = null, $settings = null)
$config = (object) array(
'secret_key' => $this->get_secret_api_key($mode, $settings),
- 'public_key' => $this->get_public_api_key($mode, $settings),
'webhook_secret' => $this->get_webhook_secret($mode, $settings),
'stored_secret_key' => $this->get_stored_secret_key($mode, $settings)
);
@@ -2095,29 +2092,31 @@ public function update_plugin_settings($settings)
$settings[$name] = trim($settings[$name]);
}
}
+ unset($settings['test_public_key'], $settings['live_public_key']);
}
parent::update_plugin_settings($settings);
}
- public function validate_test_secret_key($field)
- {
- $this->validate_secret_key_for_mode('test');
- }
-
- public function validate_live_secret_key($field)
+ /**
+ * Runs from the always-visible Mode field: Gravity Forms skips validation of fields hidden by a dependency but
+ * still saves their posted values, so both modes' credentials are checked on every save.
+ */
+ public function validate_credentials($field = null)
{
- $this->validate_secret_key_for_mode('live');
- }
+ $selected = rgar($this->get_posted_settings(), 'api_mode');
+ if ($selected !== 'test' && $selected !== 'live') {
+ $this->set_field_error(array('name' => 'api_mode'), esc_html__('Choose Test or Live.', 'gravityformspaystack'));
+ }
- public function validate_test_webhook_secret($field)
- {
- $this->validate_webhook_secret_for_mode('test');
- }
+ foreach (array('test', 'live') as $mode) {
+ $failed = $this->validate_secret_key_for_mode($mode);
+ $failed = $this->validate_webhook_secret_for_mode($mode) || $failed;
- public function validate_live_webhook_secret($field)
- {
- $this->validate_webhook_secret_for_mode('live');
+ if ($failed && $mode !== $selected && ($selected === 'test' || $selected === 'live')) {
+ $this->set_field_error(array('name' => 'api_mode'), sprintf(esc_html__('Your %1$s settings have a problem. Select %2$s to see it. No settings were saved.', 'gravityformspaystack'), $mode, $mode === 'test' ? esc_html__('Test', 'gravityformspaystack') : esc_html__('Live', 'gravityformspaystack')));
+ }
+ }
}
protected function resolve_posted_key($mode)
@@ -2129,8 +2128,7 @@ protected function resolve_posted_key($mode)
trim((string) rgar($settings, "{$mode}_secret_key")),
$this->get_plugin_setting("{$mode}_secret_key"),
rgar($settings, "{$mode}_webhook_secret"),
- rgar($settings, $this->other_mode($mode) . '_webhook_secret'),
- GF_Paystack_Keys::restricted_keys_enabled()
+ rgar($settings, $this->other_mode($mode) . '_webhook_secret')
);
}
@@ -2140,7 +2138,11 @@ protected function validate_webhook_secret_for_mode($mode)
if ($result['error'] !== null && strpos($result['error'], 'whsec_') === 0) {
$this->set_save_error("{$mode}_webhook_secret", $this->key_error_message($result['error'], $mode));
+
+ return true;
}
+
+ return false;
}
protected function validate_secret_key_for_mode($mode)
@@ -2151,12 +2153,15 @@ protected function validate_secret_key_for_mode($mode)
if ($result['error'] !== null) {
if (strpos($result['error'], 'whsec_') !== 0) {
$this->set_save_error("{$mode}_secret_key", $this->key_error_message($result['error'], $mode));
+
+ return true;
}
- return;
+
+ return false;
}
if (!$result['probe']) {
- return;
+ return false;
}
$verdict = $this->validate_restricted_key($key);
@@ -2164,15 +2169,20 @@ protected function validate_secret_key_for_mode($mode)
if ($verdict['code'] !== 'ok') {
$this->set_save_error("{$mode}_secret_key", $this->probe_error_message($verdict));
- return;
+
+ return true;
}
if ($this->has_subscription_feed($mode)) {
$plans = $this->probe_restricted_key_plans($key);
if ($plans !== 'ok') {
$this->set_save_error("{$mode}_secret_key", $this->plans_error_message($plans, $mode, 'settings'));
+
+ return true;
}
}
+
+ return false;
}
protected function has_subscription_feed($mode)
@@ -2282,14 +2292,14 @@ private function other_mode($mode)
protected function key_error_message($code, $mode)
{
switch ($code) {
+ case 'secret_key':
+ return sprintf(esc_html__('Use a %s restricted key instead. Create one in your Paystack Dashboard with Transactions: read and write.', 'gravityformspaystack'), $mode);
case 'wrong_field':
- return sprintf(esc_html__('This is a %1$s key. Paste it in the %1$s secret key field.', 'gravityformspaystack'), $this->other_mode($mode));
+ return sprintf(esc_html__('This is a %1$s key. Paste it in the %1$s restricted key field.', 'gravityformspaystack'), $this->other_mode($mode));
case 'invalid_format':
- return sprintf(esc_html__('Secret keys start with sk_%1$s_ and restricted keys with rk_%1$s_. Check you copied the whole key.', 'gravityformspaystack'), $mode);
- case 'rk_disabled':
- return esc_html__('Restricted keys are turned off on this site. Use your secret key instead.', 'gravityformspaystack');
+ return sprintf(esc_html__('Restricted keys start with rk_%s_. Check you copied the whole key.', 'gravityformspaystack'), $mode);
case 'whsec_required':
- return sprintf(esc_html__('A restricted key can\'t verify Paystack webhooks. Add your %s webhook signing secret from Settings → API Keys & Webhooks in your Paystack Dashboard.', 'gravityformspaystack'), $mode);
+ return sprintf(esc_html__('Add your %s webhook signing secret from Settings → API Keys & Webhooks in your Paystack Dashboard.', 'gravityformspaystack'), $mode);
case 'whsec_format':
return esc_html__('Webhook signing secrets start with whsec_. Copy it from Settings → API Keys & Webhooks in your Paystack Dashboard.', 'gravityformspaystack');
case 'whsec_same':
@@ -2340,7 +2350,6 @@ protected function scope_labels($scopes)
*
* @access public
*
- * @used-by GFPaystack::get_public_api_key()
* @used-by GFPaystack::get_secret_api_key()
* @uses GFAddOn::get_plugin_settings()
* @uses GFPaystack::get_api_mode()
@@ -2399,28 +2408,13 @@ public function get_api_mode($settings, $feed_id = null)
}
/**
- * Retrieve the public api key.
- *
- * @access public
- *
- * @uses GFPaystack::get_api_key()
- *
- * @param null|string $mode The API mode; live or test.
- * @param array|null $settings The current settings.
- *
- * @return string The public API key.
+ * @deprecated 2.0.10 Public keys are no longer used.
*/
public function get_public_api_key($mode = null, $settings = null)
{
- if (empty($settings)) {
- $settings = $this->get_plugin_settings();
- }
-
- if (empty($mode)) {
- $mode = $this->get_api_mode($settings);
- }
+ _deprecated_function(__METHOD__, '2.0.10');
- return $this->get_api_key('public', $mode, $settings);
+ return '';
}
/**
diff --git a/includes/class-gf-paystack-keys.php b/includes/class-gf-paystack-keys.php
index fdaac19..daf4464 100644
--- a/includes/class-gf-paystack-keys.php
+++ b/includes/class-gf-paystack-keys.php
@@ -5,7 +5,6 @@
if (!class_exists('GF_Paystack_Keys')) {
final class GF_Paystack_Keys
{
- const SK_SHAPE = '/^sk_(?:test|live)_[A-Za-z0-9]+$/';
const RK_SHAPE = '/^rk_(?:test|live)_[\x21\x23-\x26\x28-\x3b\x3d\x3f-\x5b\x5d-\x7e]{16,256}$/';
const WHSEC_SHAPE = '/^whsec_[A-Za-z0-9_]{16,}$/';
// A prefix glued to a word (`task_live_`) isn't a key, but one after a %XX escape (`secret%3Dsk_live_`) is.
@@ -35,12 +34,8 @@ public static function is_whsec_shaped($value)
return is_string($value) && preg_match(self::WHSEC_SHAPE, $value) === 1;
}
- public static function restricted_keys_enabled()
- {
- return (bool) apply_filters('gform_paystack_restricted_keys_enabled', true);
- }
-
- public static function resolve_save($mode, $posted_key, $stored_key, $posted_whsec, $other_mode_whsec, $rk_enabled)
+ // Only a new or changed key must be restricted: an sk_ key saved by an earlier version keeps working until replaced.
+ public static function resolve_save($mode, $posted_key, $stored_key, $posted_whsec, $other_mode_whsec)
{
$key = trim((string) $posted_key);
$stored = trim((string) $stored_key);
@@ -49,23 +44,20 @@ public static function resolve_save($mode, $posted_key, $stored_key, $posted_whs
$probe = false;
if ($key !== '' && $key !== $stored) {
+ if (self::type($key) === 'sk') {
+ return self::result(false, 'secret_key');
+ }
+
$key_mode = self::mode($key);
if ($key_mode !== null && $key_mode !== $mode) {
return self::result(false, 'wrong_field');
}
- $type = self::type($key);
- $shaped = $type === 'sk' ? preg_match(self::SK_SHAPE, $key) : ($type === 'rk' ? preg_match(self::RK_SHAPE, $key) : 0);
- if (!$shaped) {
+ if (!preg_match(self::RK_SHAPE, $key)) {
return self::result(false, 'invalid_format');
}
- if ($type === 'rk') {
- if (!$rk_enabled) {
- return self::result(false, 'rk_disabled');
- }
- $probe = true;
- }
+ $probe = true;
}
// A blank key is a cleared field, so it never needs a signing secret.
diff --git a/readme.txt b/readme.txt
index 57e3c49..e650d6a 100644
--- a/readme.txt
+++ b/readme.txt
@@ -13,30 +13,26 @@ License URI: http://www.gnu.org/licenses/gpl-2.0.html
The Paystack Addon for Gravity Forms allows you to quickly and easily implement credit card payments with WordPress. With the Paystack Add-On you can capture one time credit card payments or setup recurring payment subscriptions.
= Restricted keys =
-You can use a Paystack restricted key instead of your full secret key. Paste an `rk_test_...` or `rk_live_...` key into the matching Test or Live Secret key field.
+The add-on connects to Paystack with a restricted key. Choose Test or Live under Mode, then paste an `rk_test_...` or `rk_live_...` key into that mode's Restricted Key field. Only the selected mode's fields are shown.
* The key needs Transactions: read and write permissions, plus Plans: write if you sell subscriptions.
* Keys with permissions that can move money (transfers, refunds, settlements, payouts and similar) are rejected.
* The key is checked with Paystack when you save it, and only then. If you change its permissions later in the Paystack Dashboard, it is not checked again.
* A restricted key needs the Webhook signing secret for the same mode (see below).
+* Sites set up before version 2.0.10 keep working with the key they already saved. When you replace it, the new key must be a restricted key.
= Webhook signing secret =
The Test and Live settings have a "Webhook signing secret" field. Copy the `whsec_...` value from Settings > API Keys & Webhooks in your Paystack Dashboard.
-* It is required when you use a restricted key, and optional when you use a secret key.
+* It is required with a restricted key.
* Once it is set, webhooks are only accepted with a valid Paystack-Signature header that was signed within the last 5 minutes.
* Successful-payment webhooks are confirmed with Paystack before an entry is marked as paid.
-= For developers =
-Restricted keys can be turned off with the `gform_paystack_restricted_keys_enabled` filter (default `true`). Restricted keys that were already saved keep working.
-
-`add_filter( 'gform_paystack_restricted_keys_enabled', '__return_false' );`
-
== Installation ==
= Minimum Requirements =
-* Gravity Forms v2.4+
+* Gravity Forms v2.5+
* WordPress v5.1+
* SSL Certificate Installed and - Configured
* Download and install the add-on
@@ -75,7 +71,10 @@ Yes you can! Join in on our [GitHub repository](https://github.com/PaystackHQ/pl
== Changelog ==
= 2.0.10 - November 19, 2026 =
-* Added support for Paystack restricted keys (`rk_test_...` / `rk_live_...`).
+* The add-on now uses Paystack restricted keys (`rk_test_...` / `rk_live_...`). A key saved by an earlier version keeps working until you replace it; a new key must be a restricted key.
+* Removed the public key fields. Payments never used them.
+* The settings page shows only the selected mode's fields.
+* Requires Gravity Forms 2.5 or later.
* Added Test and Live webhook signing secret fields, and webhook signature verification when one is set.
* Successful-payment (charge.success) webhooks are now confirmed with Paystack before an entry is marked as paid.
* Keys and signing secrets are hidden in logs.
@@ -124,7 +123,7 @@ Yes you can! Join in on our [GitHub repository](https://github.com/PaystackHQ/pl
== Upgrade Notice ==
= 2.0.10 =
-* Adds optional Paystack restricted keys and webhook signing secrets. Existing secret keys keep working with no changes needed. The ?secret= / ?public= URL override has been removed.
+* Adds Paystack restricted keys and webhook signing secrets. Your saved key keeps working with no changes needed; a new key must be a restricted key. Requires Gravity Forms 2.5 or later. The ?secret= / ?public= URL override has been removed.
= 2.0.9 =
* Fixes a fatal error customers could see after paying. Please update.
diff --git a/tests/test-keys.php b/tests/test-keys.php
index 9e865d6..2d3ecca 100644
--- a/tests/test-keys.php
+++ b/tests/test-keys.php
@@ -13,31 +13,30 @@
gf_paystack_test_check(GF_Paystack_Keys::type('pk_live_x') === null && GF_Paystack_Keys::type(null) === null, 'keys type case 2');
gf_paystack_test_check(GF_Paystack_Keys::mode($sk_test) === 'test' && GF_Paystack_Keys::mode($rk_live) === 'live' && GF_Paystack_Keys::mode('nope') === null, 'keys mode case 1');
gf_paystack_test_check(GF_Paystack_Keys::is_whsec_shaped($whsec_a) && !GF_Paystack_Keys::is_whsec_shaped('whsec_short') && !GF_Paystack_Keys::is_whsec_shaped('whsec_' . str_repeat('a', 20) . '+'), 'keys whsec shape');
-gf_paystack_test_check(GF_Paystack_Keys::restricted_keys_enabled() === true, 'keys gate default on');
$keys_cases = array(
- 'blank key' => array(array('live', '', $sk_live, '', '', true), false, null),
- 'blank key, stored rk, no whsec' => array(array('live', '', $rk_live, '', '', true), false, null),
- 'unchanged odd shape' => array(array('live', 'weird-key', 'weird-key', '', '', true), false, null),
- 'unchanged wrong field' => array(array('live', $sk_test, $sk_test, '', '', true), false, null),
- 'unchanged with whitespace' => array(array('live', " $sk_live ", $sk_live, '', '', true), false, null),
- 'new sk' => array(array('live', $sk_live, '', '', '', true), false, null),
- 'new sk other mode' => array(array('live', $sk_test, '', '', '', true), false, 'wrong_field'),
- 'new rk other mode' => array(array('test', $rk_live, '', $whsec_a, '', true), false, 'wrong_field'),
- 'new key bad shape' => array(array('live', 'sk_live_', '', '', '', true), false, 'invalid_format'),
- 'new key unknown prefix' => array(array('live', 'pk_live_abc', '', '', '', true), false, 'invalid_format'),
- 'new rk too short' => array(array('live', 'rk_live_short', '', $whsec_a, '', true), false, 'invalid_format'),
- 'new rk with whsec' => array(array('live', $rk_live, '', $whsec_a, $whsec_b, true), true, null),
- 'new rk gate off' => array(array('live', $rk_live, '', $whsec_a, '', false), false, 'rk_disabled'),
- 'kept rk gate off' => array(array('live', $rk_live, $rk_live, $whsec_a, '', false), false, null),
- 'new rk without whsec' => array(array('live', $rk_live, '', '', '', true), false, 'whsec_required'),
- 'kept rk without whsec' => array(array('live', $rk_live, $rk_live, '', '', true), false, 'whsec_required'),
- 'new sk without whsec' => array(array('live', $sk_live, '', '', '', true), false, null),
- 'sk with whsec' => array(array('live', $sk_live, $sk_live, $whsec_a, '', true), false, null),
- 'whsec same as other mode' => array(array('live', $sk_live, $sk_live, $whsec_a, $whsec_a, true), false, 'whsec_same'),
- 'whsec bad shape' => array(array('live', $sk_live, $sk_live, 'whsec_x', '', true), false, 'whsec_format'),
- 'whsec bad shape with blank key' => array(array('live', '', '', 'nope', '', true), false, 'whsec_format'),
- 'key error before whsec error' => array(array('live', $sk_test, '', 'nope', '', true), false, 'wrong_field'),
+ 'blank key' => array(array('live', '', $sk_live, '', ''), false, null),
+ 'blank key, stored rk, no whsec' => array(array('live', '', $rk_live, '', ''), false, null),
+ 'unchanged odd shape' => array(array('live', 'weird-key', 'weird-key', '', ''), false, null),
+ 'unchanged wrong field' => array(array('live', $sk_test, $sk_test, '', ''), false, null),
+ 'unchanged with whitespace' => array(array('live', " $sk_live ", $sk_live, '', ''), false, null),
+ 'new sk refused' => array(array('live', $sk_live, '', '', ''), false, 'secret_key'),
+ 'new sk other mode refused' => array(array('live', $sk_test, '', '', ''), false, 'secret_key'),
+ 'changed sk refused' => array(array('live', 'sk_live_rotated999', $sk_live, '', ''), false, 'secret_key'),
+ 'stored sk replaced by rk' => array(array('live', $rk_live, $sk_live, $whsec_a, ''), true, null),
+ 'new rk other mode' => array(array('test', $rk_live, '', $whsec_a, ''), false, 'wrong_field'),
+ 'new key bad shape' => array(array('live', 'rk_live_', '', $whsec_a, ''), false, 'invalid_format'),
+ 'new key unknown prefix' => array(array('live', 'pk_live_abc', '', '', ''), false, 'invalid_format'),
+ 'new rk too short' => array(array('live', 'rk_live_short', '', $whsec_a, ''), false, 'invalid_format'),
+ 'new rk with whsec' => array(array('live', $rk_live, '', $whsec_a, $whsec_b), true, null),
+ 'new rk without whsec' => array(array('live', $rk_live, '', '', ''), false, 'whsec_required'),
+ 'kept rk without whsec' => array(array('live', $rk_live, $rk_live, '', ''), false, 'whsec_required'),
+ 'kept sk without whsec' => array(array('live', $sk_live, $sk_live, '', ''), false, null),
+ 'sk with whsec' => array(array('live', $sk_live, $sk_live, $whsec_a, ''), false, null),
+ 'whsec same as other mode' => array(array('live', $sk_live, $sk_live, $whsec_a, $whsec_a), false, 'whsec_same'),
+ 'whsec bad shape' => array(array('live', $sk_live, $sk_live, 'whsec_x', ''), false, 'whsec_format'),
+ 'whsec bad shape with blank key' => array(array('live', '', '', 'nope', ''), false, 'whsec_format'),
+ 'key error before whsec error' => array(array('live', $rk_test, '', 'nope', ''), false, 'wrong_field'),
);
foreach ($keys_cases as $label => $case) {
$result = call_user_func_array(array('GF_Paystack_Keys', 'resolve_save'), $case[0]);
@@ -63,29 +62,25 @@
// # Coverage additions (dedicated test pass)
gf_paystack_test_check(GF_Paystack_Keys::mode('sk_livefoo') === null && GF_Paystack_Keys::type('sk_livefoo') === null, 'keys prefix needs the trailing underscore');
$keys_extra = array(
- 'prefix without trailing underscore' => array(array('test', 'sk_livefoo', '', '', '', true), false, 'invalid_format'),
- 'rk body at 256 chars' => array(array('live', 'rk_live_' . str_repeat('a', 256), '', $whsec_a, '', true), true, null),
- 'rk body over 256 chars' => array(array('live', 'rk_live_' . str_repeat('a', 257), '', $whsec_a, '', true), false, 'invalid_format'),
- 'rk at 16 chars' => array(array('live', 'rk_live_' . str_repeat('a', 16), '', $whsec_a, '', true), true, null),
- 'rk at 15 chars' => array(array('live', 'rk_live_' . str_repeat('a', 15), '', $whsec_a, '', true), false, 'invalid_format'),
- 'blank whsec on both sides is not a duplicate' => array(array('live', $sk_live, $sk_live, '', '', true), false, null),
- 'whsec at 16 chars' => array(array('live', $sk_live, $sk_live, 'whsec_' . str_repeat('a', 16), '', true), false, null),
- 'whsec at 15 chars' => array(array('live', $sk_live, $sk_live, 'whsec_' . str_repeat('a', 15), '', true), false, 'whsec_format'),
- 'whitespace-only other whsec is blank' => array(array('live', $sk_live, $sk_live, $whsec_a, ' ', true), false, null),
- 'rk containing a double quote' => array(array('live', 'rk_live_abcdefgh"ijklmnopqr', '', $whsec_a, '', true), false, 'invalid_format'),
- 'rk containing a backslash' => array(array('live', 'rk_live_abcdefgh\\ijklmnopqr', '', $whsec_a, '', true), false, 'invalid_format'),
- 'rk containing a less-than' => array(array('live', 'rk_live_abcdefgh array(array('live', "rk_live_abcdefgh'ijklmnopqr", '', $whsec_a, '', true), false, 'invalid_format'),
- 'rk error reports no probe' => array(array('live', $rk_live, '', '', '', true), false, 'whsec_required'),
+ 'prefix without trailing underscore' => array(array('test', 'sk_livefoo', '', '', ''), false, 'invalid_format'),
+ 'rk body at 256 chars' => array(array('live', 'rk_live_' . str_repeat('a', 256), '', $whsec_a, ''), true, null),
+ 'rk body over 256 chars' => array(array('live', 'rk_live_' . str_repeat('a', 257), '', $whsec_a, ''), false, 'invalid_format'),
+ 'rk at 16 chars' => array(array('live', 'rk_live_' . str_repeat('a', 16), '', $whsec_a, ''), true, null),
+ 'rk at 15 chars' => array(array('live', 'rk_live_' . str_repeat('a', 15), '', $whsec_a, ''), false, 'invalid_format'),
+ 'blank whsec on both sides is not a duplicate' => array(array('live', $sk_live, $sk_live, '', ''), false, null),
+ 'whsec at 16 chars' => array(array('live', $sk_live, $sk_live, 'whsec_' . str_repeat('a', 16), ''), false, null),
+ 'whsec at 15 chars' => array(array('live', $sk_live, $sk_live, 'whsec_' . str_repeat('a', 15), ''), false, 'whsec_format'),
+ 'whitespace-only other whsec is blank' => array(array('live', $sk_live, $sk_live, $whsec_a, ' '), false, null),
+ 'rk containing a double quote' => array(array('live', 'rk_live_abcdefgh"ijklmnopqr', '', $whsec_a, ''), false, 'invalid_format'),
+ 'rk containing a backslash' => array(array('live', 'rk_live_abcdefgh\\ijklmnopqr', '', $whsec_a, ''), false, 'invalid_format'),
+ 'rk containing a less-than' => array(array('live', 'rk_live_abcdefgh array(array('live', "rk_live_abcdefgh'ijklmnopqr", '', $whsec_a, ''), false, 'invalid_format'),
+ 'rk error reports no probe' => array(array('live', $rk_live, '', '', ''), false, 'whsec_required'),
);
foreach ($keys_extra as $label => $case) {
$result = call_user_func_array(array('GF_Paystack_Keys', 'resolve_save'), $case[0]);
gf_paystack_test_check($result === array('probe' => $case[1], 'error' => $case[2]), 'keys resolve_save ' . $label);
}
-$GLOBALS['gf_paystack_test_filters']['gform_paystack_restricted_keys_enabled'] = false;
-gf_paystack_test_check(GF_Paystack_Keys::restricted_keys_enabled() === false, 'keys gate filter can turn restricted keys off');
-unset($GLOBALS['gf_paystack_test_filters']['gform_paystack_restricted_keys_enabled']);
-
gf_paystack_test_check(GF_Paystack_Keys::redact('a sk_live_abc and rk_test_def and whsec_ghi') === 'a sk_live_[redacted] and rk_test_[redacted] and whsec_[redacted]', 'keys redact several secrets in one string');
gf_paystack_test_check(GF_Paystack_Keys::redact('sk_live_abc"') === 'sk_live_[redacted]"', 'keys redact stops at a closing quote');
diff --git a/tests/test-settings.php b/tests/test-settings.php
index 01cd12b..798f0e0 100644
--- a/tests/test-settings.php
+++ b/tests/test-settings.php
@@ -16,21 +16,54 @@
if ($configure) {
$configure($addon);
}
+ $call = function ($method) use ($addon, $mode) {
+ return (function () use ($method, $mode) {
+ return $this->$method($mode);
+ })->call($addon);
+ };
if ($which !== 'whsec') {
- $addon->{"validate_{$mode}_secret_key"}(array());
+ $call('validate_secret_key_for_mode');
}
if ($which !== 'key') {
- $addon->{"validate_{$mode}_webhook_secret"}(array());
+ $call('validate_webhook_secret_for_mode');
+ }
+
+ return $addon;
+};
+
+// The Mode field's callback checks both modes, so a key hidden by the mode switch can't skip validation.
+$cred = function ($posted, $stored = array(), $configure = null) {
+ $GLOBALS['gf_paystack_test_gf_logs'] = array();
+ $addon = new GFPaystackSettingsFixture();
+ $addon->posted = $posted;
+ $addon->stored = $stored;
+ if ($configure) {
+ $configure($addon);
}
+ $addon->validate_credentials(array());
return $addon;
};
+$a = $cred(array('api_mode' => 'live', 'test_secret_key' => $st_sk_test));
+gf_paystack_test_check(isset($a->field_errors['test_secret_key']) && strpos($a->field_errors['api_mode'] ?? '', 'Your test settings have a problem. Select Test to see it.') === 0, 'credentials: new sk in the hidden test fields is refused and flagged on Mode');
+$a = $cred(array('api_mode' => 'live', 'test_secret_key' => $st_rk_test, 'test_webhook_secret' => ''));
+gf_paystack_test_check(isset($a->field_errors['test_webhook_secret']) && isset($a->field_errors['api_mode']), 'credentials: hidden rk without whsec is refused');
+$a = $cred(array('api_mode' => 'test', 'live_secret_key' => $st_rk_live, 'live_webhook_secret' => 'nope'));
+gf_paystack_test_check(isset($a->field_errors['live_webhook_secret']) && strpos($a->field_errors['api_mode'] ?? '', 'Your live settings') === 0, 'credentials: hidden bad whsec is refused');
+$a = $cred(array('api_mode' => 'test', 'live_secret_key' => $st_rk_live, 'live_webhook_secret' => $st_ws_live));
+gf_paystack_test_check($a->validate_calls === array($st_rk_live), 'credentials: hidden new rk is still probed');
+$a = $cred(array('api_mode' => 'test', 'test_secret_key' => $st_sk_test));
+gf_paystack_test_check(isset($a->field_errors['test_secret_key']) && !isset($a->field_errors['api_mode']), 'credentials: an error in the selected mode is not repeated on Mode');
+$a = $cred(array('api_mode' => 'test', 'test_secret_key' => $st_sk_test, 'live_secret_key' => $st_sk_live), array('test_secret_key' => $st_sk_test, 'live_secret_key' => $st_sk_live));
+gf_paystack_test_check($a->field_errors === array() && $a->validate_calls === array(), 'credentials: grandfathered sk keys in both modes save');
+$a = $cred(array('api_mode' => ''));
+gf_paystack_test_check(($a->field_errors['api_mode'] ?? '') === 'Choose Test or Live.', 'credentials: a missing mode is refused');
$a = $st_run('test', array('test_secret_key' => $st_sk_test), array('test_secret_key' => $st_sk_test));
gf_paystack_test_check($a->field_errors === array() && $a->validate_calls === array(), 'settings unchanged sk saves');
$a = $st_run('live', array('live_secret_key' => $st_sk_live), array());
-gf_paystack_test_check($a->field_errors === array() && $a->validate_calls === array(), 'settings new sk saves without probe');
+gf_paystack_test_check(strpos($a->field_errors['live_secret_key'] ?? '', 'Use a live restricted key instead.') === 0 && $a->validate_calls === array(), 'settings new sk refused without probe');
$a = $st_run('test', array('test_secret_key' => ' ' . $st_rk_test . ' ', 'test_webhook_secret' => $st_ws_test));
gf_paystack_test_check($a->field_errors === array() && $a->validate_calls === array($st_rk_test), 'settings new rk with whsec probes trimmed key and saves');
@@ -71,14 +104,17 @@
$a = $st_run('test', array('test_secret_key' => $st_rk_test, 'test_webhook_secret' => 'nope'), array('test_secret_key' => $st_rk_test));
gf_paystack_test_check(strpos($a->field_errors['test_webhook_secret'], 'Webhook signing secrets start with whsec_.') === 0, 'settings bad whsec shape errors');
-$a = $st_run('live', array('live_secret_key' => $st_sk_live, 'live_webhook_secret' => $st_ws_live, 'test_webhook_secret' => $st_ws_live));
+$a = $st_run('live', array('live_secret_key' => $st_sk_live, 'live_webhook_secret' => $st_ws_live, 'test_webhook_secret' => $st_ws_live), array('live_secret_key' => $st_sk_live));
gf_paystack_test_check(isset($a->field_errors['live_webhook_secret']) && strpos($a->field_errors['live_webhook_secret'], 'are the same') !== false, 'settings test==live whsec errors');
-$a = $st_run('live', array('live_secret_key' => $st_sk_test));
-gf_paystack_test_check($a->field_errors['live_secret_key'] === 'This is a test key. Paste it in the test secret key field.' . $st_suffix, 'settings wrong_field copy');
+$a = $st_run('live', array('live_secret_key' => $st_rk_test, 'live_webhook_secret' => $st_ws_live));
+gf_paystack_test_check($a->field_errors['live_secret_key'] === 'This is a test key. Paste it in the test restricted key field.' . $st_suffix, 'settings wrong_field copy');
+
+$a = $st_run('live', array('live_secret_key' => 'sk_live_rotated123'), array('live_secret_key' => $st_sk_live));
+gf_paystack_test_check($a->field_errors['live_secret_key'] === 'Use a live restricted key instead. Create one in your Paystack Dashboard with Transactions: read and write.' . $st_suffix, 'settings changed sk refused copy');
$a = $st_run('test', array('test_secret_key' => 'garbage'));
-gf_paystack_test_check($a->field_errors['test_secret_key'] === 'Secret keys start with sk_test_ and restricted keys with rk_test_. Check you copied the whole key.' . $st_suffix, 'settings invalid_format copy');
+gf_paystack_test_check($a->field_errors['test_secret_key'] === 'Restricted keys start with rk_test_. Check you copied the whole key.' . $st_suffix, 'settings invalid_format copy');
// Each callback reports only its own codes.
$a = $st_run('test', array('test_secret_key' => $st_rk_test, 'test_webhook_secret' => ''), array(), null, 'key');
@@ -91,7 +127,7 @@
gf_paystack_test_check($a->error_log === array('live_secret_key'), 'settings key code is reported once across both callbacks');
$a = $st_run('live', $rk_posted, array(), $verdict(array('code' => 'invalid_key')));
gf_paystack_test_check($a->error_log === array('live_secret_key'), 'settings probe result is reported once across both callbacks');
-$a = $st_run('live', array('live_secret_key' => $st_sk_live, 'live_webhook_secret' => 'nope'), array(), null, 'key');
+$a = $st_run('live', array('live_secret_key' => $st_sk_live, 'live_webhook_secret' => 'nope'), array('live_secret_key' => $st_sk_live), null, 'key');
gf_paystack_test_check($a->error_log === array(), 'settings key callback silent on bad whsec shape');
// Plans check on save.
@@ -139,13 +175,8 @@
$a = $st_run('live', array('live_secret_key' => $st_rk_live, 'live_webhook_secret' => $st_ws_live), array('live_secret_key' => $st_rk_live), $with_feeds(array($sub_feed('live')), 'plans_missing'), 'key');
gf_paystack_test_check($a->plans_calls === array() && $a->field_errors === array(), 'settings save skips plans for an unchanged key');
-$GLOBALS['gf_paystack_test_filters'] = array('gform_paystack_restricted_keys_enabled' => false);
-$a = $st_run('live', $rk_posted);
-gf_paystack_test_check(isset($a->field_errors['live_secret_key']) && strpos($a->field_errors['live_secret_key'], 'Restricted keys are turned off on this site.') === 0 && $a->validate_calls === array(), 'settings gate off new rk rejected');
-
-$a = $st_run('live', $rk_posted, array('live_secret_key' => $st_rk_live));
-gf_paystack_test_check($a->field_errors === array() && $a->validate_calls === array(), 'settings gate off kept rk ok');
-unset($GLOBALS['gf_paystack_test_filters']);
+$a = $st_run('live', array('live_secret_key' => $st_rk_live, 'live_webhook_secret' => $st_ws_live), array('live_secret_key' => $st_sk_live));
+gf_paystack_test_check($a->field_errors === array() && $a->validate_calls === array($st_rk_live), 'settings stored sk replaced by rk is probed');
// Fields.
$fa = new GFPaystackSettingsFixture();
@@ -160,7 +191,21 @@
gf_paystack_test_check($pw_ok, 'settings secret and whsec fields are password inputs');
$order = array_keys($by_name);
gf_paystack_test_check(array_search('test_webhook_secret', $order) === array_search('test_secret_key', $order) + 1 && array_search('live_webhook_secret', $order) === array_search('live_secret_key', $order) + 1, 'settings whsec fields follow their secret key');
-gf_paystack_test_check($by_name['test_secret_key']['label'] === 'Test Secret or Restricted Key' && $by_name['live_webhook_secret']['label'] === 'Live Webhook Signing Secret' && strpos($by_name['live_secret_key']['tooltip'], 'A restricted key limits what this plugin can do with your Paystack account.') !== false, 'settings labels and help text');
+gf_paystack_test_check($by_name['test_secret_key']['label'] === 'Test Restricted Key' && $by_name['live_webhook_secret']['label'] === 'Live Webhook Signing Secret' && strpos($by_name['live_secret_key']['tooltip'], 'Create a restricted key in your Paystack Dashboard') !== false, 'settings labels and help text');
+gf_paystack_test_check(!isset($by_name['test_public_key']) && !isset($by_name['live_public_key']), 'settings have no public key fields');
+$labels = '';
+foreach ($by_name as $f) {
+ $labels .= ' ' . rgar($f, 'label') . ' ' . rgar($f, 'tooltip');
+}
+gf_paystack_test_check(stripos($labels, 'secret key') === false, 'settings never mention secret keys');
+$dep_ok = true;
+foreach (array('test' => array('test_secret_key', 'test_webhook_secret'), 'live' => array('live_secret_key', 'live_webhook_secret')) as $dep_mode => $names) {
+ foreach ($names as $n) {
+ $dep_ok = $dep_ok && rgar($by_name[$n], 'dependency') === array('live' => true, 'fields' => array(array('field' => 'api_mode', 'values' => array($dep_mode))));
+ }
+}
+gf_paystack_test_check($dep_ok, 'settings key fields show only for their own mode');
+gf_paystack_test_check($by_name['api_mode']['default_value'] === 'test' && !isset($by_name['webhooks_enabled']['dependency']['live']), 'settings mode defaults to test and webhook checkbox shows in both modes');
// Feed.
$feed = function ($posted, $stored, $plans = 'ok') {
@@ -293,12 +338,12 @@ public function get_field($name, $fields)
// # Coverage additions (dedicated test pass)
-// Each credential field is wired to its own callback.
-$wiring_ok = true;
-foreach (array('test_secret_key' => 'validate_test_secret_key', 'live_secret_key' => 'validate_live_secret_key', 'test_webhook_secret' => 'validate_test_webhook_secret', 'live_webhook_secret' => 'validate_live_webhook_secret') as $field_name => $callback) {
- $wiring_ok = $wiring_ok && isset($by_name[$field_name]['validation_callback']) && $by_name[$field_name]['validation_callback'] === array($fa, $callback);
+// Credentials are validated from the always-visible Mode field, never from fields a dependency can hide.
+$wiring_ok = $by_name['api_mode']['validation_callback'] === array($fa, 'validate_credentials');
+foreach (array('test_secret_key', 'live_secret_key', 'test_webhook_secret', 'live_webhook_secret') as $field_name) {
+ $wiring_ok = $wiring_ok && !isset($by_name[$field_name]['validation_callback']);
}
-gf_paystack_test_check($wiring_ok, 'settings each key and whsec field carries its own validation callback');
+gf_paystack_test_check($wiring_ok, 'settings credentials are validated from the Mode field');
// Each callback validates its own mode.
$a = $st_run('test', array('test_secret_key' => $st_sk_live, 'live_secret_key' => $st_sk_test));
diff --git a/tests/test-webhook.php b/tests/test-webhook.php
index f8b6d53..0569887 100644
--- a/tests/test-webhook.php
+++ b/tests/test-webhook.php
@@ -454,9 +454,9 @@ public function set_mode($mode)
return $this->$prop;
})->call($api);
};
-$qs_addon = $event_addon(array('api_mode' => 'live', 'live_secret_key' => $sk_live, 'live_public_key' => 'pk_live_stored'));
+$qs_addon = $event_addon(array('api_mode' => 'live', 'live_secret_key' => $sk_live));
$qs_api = $qs_addon->paystack_api();
-gf_paystack_test_check($read_prop($qs_api, 'secret_key') === $sk_live && $read_prop($qs_api, 'public_key') === 'pk_live_stored', '?secret= and ?public= ignored when building the API client');
+gf_paystack_test_check($read_prop($qs_api, 'secret_key') === $sk_live, '?secret= ignored when building the API client');
unset($_GET['secret'], $_GET['public'], $GLOBALS['gf_paystack_test_caps']);
// # Coverage additions (dedicated test pass)
From fdc984ab9061642f526c909e83d1814eff08064c Mon Sep 17 00:00:00 2001
From: Jules Nsenda
Date: Thu, 19 Nov 2026 21:15:56 +0200
Subject: [PATCH 15/19] feat: re-check a saved restricted key's permissions on
every save
Permissions can change in the Paystack Dashboard without the key
changing, so a kept rk_ key is probed again whenever settings are saved.
A definite refusal blocks the save; an unreachable Paystack does not
block a key that was already accepted.
Co-Authored-By: Claude Opus 5.5
---
class-gf-paystack.php | 9 ++++++++-
includes/class-gf-paystack-keys.php | 4 ++++
readme.txt | 3 ++-
tests/test-keys.php | 1 +
tests/test-settings.php | 17 ++++++++++++++++-
5 files changed, 31 insertions(+), 3 deletions(-)
diff --git a/class-gf-paystack.php b/class-gf-paystack.php
index b41a8a4..1502d84 100644
--- a/class-gf-paystack.php
+++ b/class-gf-paystack.php
@@ -2167,6 +2167,13 @@ protected function validate_secret_key_for_mode($mode)
$verdict = $this->validate_restricted_key($key);
$this->log_debug("rk validate mode={$mode} code={$verdict['code']} probes={$verdict['probes']}");
+ // A key that was already accepted stays usable when Paystack can't be reached, so an outage never blocks
+ // saving unrelated settings. A definite refusal still blocks.
+ $kept = $key === trim((string) $this->get_plugin_setting("{$mode}_secret_key"));
+ if ($kept && $verdict['code'] === 'unverifiable') {
+ return false;
+ }
+
if ($verdict['code'] !== 'ok') {
$this->set_save_error("{$mode}_secret_key", $this->probe_error_message($verdict));
@@ -2175,7 +2182,7 @@ protected function validate_secret_key_for_mode($mode)
if ($this->has_subscription_feed($mode)) {
$plans = $this->probe_restricted_key_plans($key);
- if ($plans !== 'ok') {
+ if ($plans !== 'ok' && !($kept && $plans === 'unverifiable')) {
$this->set_save_error("{$mode}_secret_key", $this->plans_error_message($plans, $mode, 'settings'));
return true;
diff --git a/includes/class-gf-paystack-keys.php b/includes/class-gf-paystack-keys.php
index daf4464..542f663 100644
--- a/includes/class-gf-paystack-keys.php
+++ b/includes/class-gf-paystack-keys.php
@@ -35,6 +35,7 @@ public static function is_whsec_shaped($value)
}
// Only a new or changed key must be restricted: an sk_ key saved by an earlier version keeps working until replaced.
+ // A restricted key, new or kept, is always probed.
public static function resolve_save($mode, $posted_key, $stored_key, $posted_whsec, $other_mode_whsec)
{
$key = trim((string) $posted_key);
@@ -57,6 +58,9 @@ public static function resolve_save($mode, $posted_key, $stored_key, $posted_whs
return self::result(false, 'invalid_format');
}
+ $probe = true;
+ } elseif ($key !== '' && self::type($key) === 'rk') {
+ // Permissions can change in the Dashboard without the key changing, so a kept key is checked again.
$probe = true;
}
diff --git a/readme.txt b/readme.txt
index e650d6a..5b49881 100644
--- a/readme.txt
+++ b/readme.txt
@@ -17,7 +17,7 @@ The add-on connects to Paystack with a restricted key. Choose Test or Live under
* The key needs Transactions: read and write permissions, plus Plans: write if you sell subscriptions.
* Keys with permissions that can move money (transfers, refunds, settlements, payouts and similar) are rejected.
-* The key is checked with Paystack when you save it, and only then. If you change its permissions later in the Paystack Dashboard, it is not checked again.
+* The key is checked with Paystack every time you save the settings, so after changing its permissions in the Paystack Dashboard, click Save to check them. If Paystack can't be reached, a key that was already saved stays in use.
* A restricted key needs the Webhook signing secret for the same mode (see below).
* Sites set up before version 2.0.10 keep working with the key they already saved. When you replace it, the new key must be a restricted key.
@@ -75,6 +75,7 @@ Yes you can! Join in on our [GitHub repository](https://github.com/PaystackHQ/pl
* Removed the public key fields. Payments never used them.
* The settings page shows only the selected mode's fields.
* Requires Gravity Forms 2.5 or later.
+* A restricted key's permissions are checked with Paystack every time the settings are saved.
* Added Test and Live webhook signing secret fields, and webhook signature verification when one is set.
* Successful-payment (charge.success) webhooks are now confirmed with Paystack before an entry is marked as paid.
* Keys and signing secrets are hidden in logs.
diff --git a/tests/test-keys.php b/tests/test-keys.php
index 2d3ecca..928e3a6 100644
--- a/tests/test-keys.php
+++ b/tests/test-keys.php
@@ -23,6 +23,7 @@
'new sk refused' => array(array('live', $sk_live, '', '', ''), false, 'secret_key'),
'new sk other mode refused' => array(array('live', $sk_test, '', '', ''), false, 'secret_key'),
'changed sk refused' => array(array('live', 'sk_live_rotated999', $sk_live, '', ''), false, 'secret_key'),
+ 'kept rk with whsec is probed again' => array(array('live', $rk_live, $rk_live, $whsec_a, ''), true, null),
'stored sk replaced by rk' => array(array('live', $rk_live, $sk_live, $whsec_a, ''), true, null),
'new rk other mode' => array(array('test', $rk_live, '', $whsec_a, ''), false, 'wrong_field'),
'new key bad shape' => array(array('live', 'rk_live_', '', $whsec_a, ''), false, 'invalid_format'),
diff --git a/tests/test-settings.php b/tests/test-settings.php
index 798f0e0..a2d4d24 100644
--- a/tests/test-settings.php
+++ b/tests/test-settings.php
@@ -173,7 +173,22 @@
gf_paystack_test_check($a2->plans_calls === array() && strpos($a2->field_errors['live_secret_key'], 'Paystack didn\'t accept this key.') === 0, 'settings save skips plans when the settings probe fails');
$a = $st_run('live', array('live_secret_key' => $st_rk_live, 'live_webhook_secret' => $st_ws_live), array('live_secret_key' => $st_rk_live), $with_feeds(array($sub_feed('live')), 'plans_missing'), 'key');
-gf_paystack_test_check($a->plans_calls === array() && $a->field_errors === array(), 'settings save skips plans for an unchanged key');
+gf_paystack_test_check($a->plans_calls === array($st_rk_live) && strpos($a->field_errors['live_secret_key'] ?? '', 'Subscriptions need Plans: write') === 0, 'settings save re-checks plans for a kept key');
+
+// A kept restricted key is checked again on every save; only an unreachable Paystack is let through.
+$kept = array('live_secret_key' => $st_rk_live, 'live_webhook_secret' => $st_ws_live);
+$a = $st_run('live', $kept, array('live_secret_key' => $st_rk_live), $verdict(array('code' => 'sensitive_scope', 'sensitive_scopes' => array('transfers'))), 'key');
+gf_paystack_test_check($a->validate_calls === array($st_rk_live) && strpos($a->field_errors['live_secret_key'] ?? '', 'remove Transfers') !== false, 'settings kept key that gained transfers is refused');
+$a = $st_run('live', $kept, array('live_secret_key' => $st_rk_live), $verdict(array('code' => 'unverifiable', 'reason' => 'transient')), 'key');
+gf_paystack_test_check($a->field_errors === array(), 'settings kept key saves when Paystack is unreachable');
+$a = $st_run('live', $kept, array('live_secret_key' => $st_rk_live), $verdict(array('code' => 'unverifiable', 'reason' => 'blocked')), 'key');
+gf_paystack_test_check($a->field_errors === array(), 'settings kept key saves when the check is blocked');
+$a = $st_run('live', $kept, array(), $verdict(array('code' => 'unverifiable', 'reason' => 'transient')), 'key');
+gf_paystack_test_check(isset($a->field_errors['live_secret_key']), 'settings new key is refused when Paystack is unreachable');
+$a = $st_run('live', $kept, array('live_secret_key' => $st_rk_live), $with_feeds(array($sub_feed('live')), 'unverifiable'), 'key');
+gf_paystack_test_check($a->field_errors === array(), 'settings kept key saves when the plans check cannot reach Paystack');
+$a = $st_run('live', $kept, array('live_secret_key' => $st_rk_live), $verdict(array('code' => 'invalid_key')), 'key');
+gf_paystack_test_check(strpos($a->field_errors['live_secret_key'] ?? '', 'Paystack didn\'t accept this key.') === 0, 'settings kept key that was revoked is refused');
$a = $st_run('live', array('live_secret_key' => $st_rk_live, 'live_webhook_secret' => $st_ws_live), array('live_secret_key' => $st_sk_live));
gf_paystack_test_check($a->field_errors === array() && $a->validate_calls === array($st_rk_live), 'settings stored sk replaced by rk is probed');
From 76930c4b35040f9e1f130cebbb5b73ce304918ba Mon Sep 17 00:00:00 2001
From: Jules Nsenda
Date: Thu, 19 Nov 2026 21:25:53 +0200
Subject: [PATCH 16/19] docs: list the webhook events the plugin needs
Co-Authored-By: Claude Opus 5.5
---
class-gf-paystack.php | 1 +
readme.txt | 1 +
2 files changed, 2 insertions(+)
diff --git a/class-gf-paystack.php b/class-gf-paystack.php
index 1502d84..eef37e3 100644
--- a/class-gf-paystack.php
+++ b/class-gf-paystack.php
@@ -439,6 +439,7 @@ public function get_webhooks_section_description()
get_webhook_url($this->get_current_feed_id()); ?>
+
diff --git a/readme.txt b/readme.txt
index 5b49881..556e44e 100644
--- a/readme.txt
+++ b/readme.txt
@@ -27,6 +27,7 @@ The Test and Live settings have a "Webhook signing secret" field. Copy the `whse
* It is required with a restricted key.
* Once it is set, webhooks are only accepted with a valid Paystack-Signature header that was signed within the last 5 minutes.
* Successful-payment webhooks are confirmed with Paystack before an entry is marked as paid.
+* The webhook URL must listen to charge.success. Forms that sell subscriptions also need subscription.create, subscription.disable, invoice.create, invoice.update and invoice.payment_failed.
== Installation ==
From 492c781ceabb152459f4f5019507345704e75de6 Mon Sep 17 00:00:00 2001
From: Jules Nsenda
Date: Thu, 19 Nov 2026 21:26:21 +0200
Subject: [PATCH 17/19] docs: note that a webhook URL may listen to all events
Co-Authored-By: Claude Opus 5.5
---
class-gf-paystack.php | 2 +-
readme.txt | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/class-gf-paystack.php b/class-gf-paystack.php
index eef37e3..c15dc1b 100644
--- a/class-gf-paystack.php
+++ b/class-gf-paystack.php
@@ -439,7 +439,7 @@ public function get_webhooks_section_description()
get_webhook_url($this->get_current_feed_id()); ?>
-
+
diff --git a/readme.txt b/readme.txt
index 556e44e..ee50bfa 100644
--- a/readme.txt
+++ b/readme.txt
@@ -27,7 +27,7 @@ The Test and Live settings have a "Webhook signing secret" field. Copy the `whse
* It is required with a restricted key.
* Once it is set, webhooks are only accepted with a valid Paystack-Signature header that was signed within the last 5 minutes.
* Successful-payment webhooks are confirmed with Paystack before an entry is marked as paid.
-* The webhook URL must listen to charge.success. Forms that sell subscriptions also need subscription.create, subscription.disable, invoice.create, invoice.update and invoice.payment_failed.
+* The webhook URL must listen to charge.success. Forms that sell subscriptions also need subscription.create, subscription.disable, invoice.create, invoice.update and invoice.payment_failed. Selecting all events is fine: the others are ignored.
== Installation ==
From f37a49237b7d1057bed20e80cdbf9a91dbe96d02 Mon Sep 17 00:00:00 2001
From: Jules Nsenda
Date: Fri, 20 Nov 2026 11:36:09 +0200
Subject: [PATCH 18/19] fix: record settings errors on Gravity Forms field
objects
Gravity Forms 2.5+ takes the settings field object by reference in
set_field_error(). Passing an array crashed every refused save with a
fatal error on PHP 8, including the existing custom-metadata checks on
feeds. Errors now go through set_setting_error(), which looks the field
up through the settings renderer and falls back to the field being
validated. The test stubs now follow the same contract.
Found by testing against real Gravity Forms 2.7.
Co-Authored-By: Claude Opus 5.5
---
class-gf-paystack.php | 32 +++++++++++++++++++++-------
tests/fixtures.php | 46 ++++++++++++++++++++++++++++++++++++++---
tests/stubs.php | 12 +++++++++++
tests/test-settings.php | 21 +++++++++++++++++++
4 files changed, 100 insertions(+), 11 deletions(-)
diff --git a/class-gf-paystack.php b/class-gf-paystack.php
index c15dc1b..f62712d 100644
--- a/class-gf-paystack.php
+++ b/class-gf-paystack.php
@@ -860,17 +860,17 @@ public function validate_custom_meta($field)
// If there are more than 20 metadata keys, set field error.
if ($meta_count > 20) {
- $this->set_field_error(array(esc_html__('You may only have 20 custom keys.'), 'gravityformspaystack'));
+ $this->set_setting_error('metaData', esc_html__('You may only have 20 custom keys.', 'gravityformspaystack'), $field);
return;
}
// Loop through metadata and check the key name length (custom_key).
foreach ($meta_data as $meta) {
if (empty($meta['custom_key']) && !empty($meta['value'])) {
- $this->set_field_error(array('name' => 'metaData'), esc_html__("A field has been mapped to a custom key without a name. Please enter a name for the custom key, remove the metadata item, or return the corresponding drop down to 'Select a Field'.", 'gravityformspaystack'));
+ $this->set_setting_error('metaData', esc_html__("A field has been mapped to a custom key without a name. Please enter a name for the custom key, remove the metadata item, or return the corresponding drop down to 'Select a Field'.", 'gravityformspaystack'), $field);
break;
} else if (strlen($meta['custom_key']) > 40) {
- $this->set_field_error(array('name' => 'metaData'), sprintf(esc_html__('The name of custom key %s is too long. Please shorten this to 40 characters or less.', 'gravityformspaystack'), $meta['custom_key']));
+ $this->set_setting_error('metaData', sprintf(esc_html__('The name of custom key %s is too long. Please shorten this to 40 characters or less.', 'gravityformspaystack'), esc_html($meta['custom_key'])), $field);
break;
}
}
@@ -2107,7 +2107,7 @@ public function validate_credentials($field = null)
{
$selected = rgar($this->get_posted_settings(), 'api_mode');
if ($selected !== 'test' && $selected !== 'live') {
- $this->set_field_error(array('name' => 'api_mode'), esc_html__('Choose Test or Live.', 'gravityformspaystack'));
+ $this->set_setting_error('api_mode', esc_html__('Choose Test or Live.', 'gravityformspaystack'), $field);
}
foreach (array('test', 'live') as $mode) {
@@ -2115,7 +2115,7 @@ public function validate_credentials($field = null)
$failed = $this->validate_webhook_secret_for_mode($mode) || $failed;
if ($failed && $mode !== $selected && ($selected === 'test' || $selected === 'live')) {
- $this->set_field_error(array('name' => 'api_mode'), sprintf(esc_html__('Your %1$s settings have a problem. Select %2$s to see it. No settings were saved.', 'gravityformspaystack'), $mode, $mode === 'test' ? esc_html__('Test', 'gravityformspaystack') : esc_html__('Live', 'gravityformspaystack')));
+ $this->set_setting_error('api_mode', sprintf(esc_html__('Your %1$s settings have a problem. Select %2$s to see it. No settings were saved.', 'gravityformspaystack'), $mode, $mode === 'test' ? esc_html__('Test', 'gravityformspaystack') : esc_html__('Live', 'gravityformspaystack')));
}
}
}
@@ -2247,7 +2247,7 @@ public function validate_subscription_plans($field, $value = null)
}
if (!is_string($type) || $type === '' || !in_array($type, $allowed, true)) {
- $this->set_field_error(array('name' => 'transactionType'), esc_html__('This field is required.', 'gravityformspaystack'));
+ $this->set_setting_error('transactionType', esc_html__('This field is required.', 'gravityformspaystack'), $field);
return;
}
@@ -2268,7 +2268,7 @@ public function validate_subscription_plans($field, $value = null)
$result = $this->probe_restricted_key_plans($key);
if ($result !== 'ok') {
- $this->set_field_error(array('name' => 'transactionType'), $this->plans_error_message($result, $mode));
+ $this->set_setting_error('transactionType', $this->plans_error_message($result, $mode), $field);
}
}
@@ -2289,7 +2289,23 @@ protected function plans_error_message($result, $mode, $context = 'feed')
protected function set_save_error($field_name, $message)
{
- $this->set_field_error(array('name' => $field_name), $message . ' ' . esc_html__('No settings were saved.', 'gravityformspaystack'));
+ $this->set_setting_error($field_name, $message . ' ' . esc_html__('No settings were saved.', 'gravityformspaystack'));
+ }
+
+ /**
+ * Gravity Forms 2.5+ only records an error on the settings field object, passed by reference, so the field is
+ * looked up by name. $fallback (the field being validated) keeps the save blocked if the lookup ever fails.
+ */
+ protected function set_setting_error($name, $message, $fallback = null)
+ {
+ $renderer = $this->get_settings_renderer();
+ $field = $renderer ? $renderer->get_field($name) : false;
+ if (!is_object($field)) {
+ $field = $fallback;
+ }
+ if (is_object($field)) {
+ $this->set_field_error($field, $message);
+ }
}
private function other_mode($mode)
diff --git a/tests/fixtures.php b/tests/fixtures.php
index bf06d19..59adbb2 100644
--- a/tests/fixtures.php
+++ b/tests/fixtures.php
@@ -184,6 +184,45 @@ function gf_paystack_exception_message($callback)
return '';
}
+// Stands in for Gravity Forms' Settings renderer and its field objects; errors land in the fixture's field_errors.
+class GFPaystackTestSettingField
+{
+ public $name;
+ private $fixture;
+
+ public function __construct($name, $fixture)
+ {
+ $this->name = $name;
+ $this->fixture = $fixture;
+ }
+
+ public function set_error($message = '')
+ {
+ $this->fixture->field_errors[$this->name] = $message;
+ $this->fixture->error_log[] = $this->name;
+ }
+}
+
+class GFPaystackTestSettingsRenderer
+{
+ private $fixture;
+
+ public function __construct($fixture)
+ {
+ $this->fixture = $fixture;
+ }
+
+ public function get_field($name)
+ {
+ $known = $this->fixture->renderer_fields;
+ if (is_array($known) && !in_array($name, $known, true)) {
+ return false;
+ }
+
+ return new GFPaystackTestSettingField($name, $this->fixture);
+ }
+}
+
class GFPaystackSettingsFixture extends GFPaystack
{
public $posted = array();
@@ -222,10 +261,11 @@ public function get_plugin_settings()
return $this->stored;
}
- public function set_field_error($field, $message = '')
+ public $renderer_fields = null;
+
+ public function get_settings_renderer()
{
- $this->field_errors[$field['name']] = $message;
- $this->error_log[] = $field['name'];
+ return new GFPaystackTestSettingsRenderer($this);
}
public function is_detail_page()
diff --git a/tests/stubs.php b/tests/stubs.php
index 753fe1b..3ecb005 100644
--- a/tests/stubs.php
+++ b/tests/stubs.php
@@ -156,6 +156,18 @@ public static function include_payment_addon_framework()
if (!class_exists('GFAddOn')) {
class GFAddOn
{
+ // Same contract as Gravity Forms 2.5+: the field is a settings field object, passed by reference.
+ public function set_field_error(&$field, $error_message = '')
+ {
+ if (is_object($field) && method_exists($field, 'set_error')) {
+ $field->set_error($error_message);
+ }
+ }
+
+ public function get_settings_renderer()
+ {
+ return false;
+ }
}
}
diff --git a/tests/test-settings.php b/tests/test-settings.php
index a2d4d24..9114f3e 100644
--- a/tests/test-settings.php
+++ b/tests/test-settings.php
@@ -431,3 +431,24 @@ public function parent_callback($field, $value = null)
$a = $feed_run(array('transactionType' => 'subscription'), array('api_mode' => 'test', 'test_secret_key' => $st_rk_test, 'live_secret_key' => $st_rk_live));
gf_paystack_test_check($a->plans_calls === array($st_rk_test), 'feed without a mode follows the global api mode');
+
+// Gravity Forms 2.5+ only records errors on field objects, so errors must never be raised with an array.
+$plugin_src = file_get_contents(dirname(__DIR__) . '/class-gf-paystack.php');
+gf_paystack_test_check(!preg_match('/set_field_error\(\s*array\(/', $plugin_src), 'no field error is raised with an array (Gravity Forms 2.5+ needs the field object)');
+
+$meta_run = function ($meta, $renderer_fields = null) {
+ $addon = new GFPaystackSettingsFixture();
+ $addon->posted = array('metaData' => $meta);
+ $addon->renderer_fields = $renderer_fields;
+ $addon->validate_custom_meta(new GFPaystackTestSettingField('metaData', $addon));
+
+ return $addon;
+};
+$a = $meta_run(array_fill(0, 21, array('custom_key' => 'k', 'value' => '1')));
+gf_paystack_test_check(($a->field_errors['metaData'] ?? '') === 'You may only have 20 custom keys.', 'feed metadata over 20 keys is flagged on metaData');
+$a = $meta_run(array(array('custom_key' => '', 'value' => '3')));
+gf_paystack_test_check(strpos($a->field_errors['metaData'] ?? '', 'A field has been mapped to a custom key without a name.') === 0, 'feed metadata without a key name is flagged');
+$a = $meta_run(array(array('custom_key' => str_repeat('', 14), 'value' => '3')));
+gf_paystack_test_check(strpos($a->field_errors['metaData'] ?? '', '<b>') !== false && strpos($a->field_errors['metaData'], '') === false, 'feed metadata long key name is flagged and escaped');
+$a = $meta_run(array(array('custom_key' => '', 'value' => '3')), array());
+gf_paystack_test_check(isset($a->field_errors['metaData']), 'an error falls back to the validated field when the renderer cannot find it');
From ff0d80c21547b76df94cf625d348b828db74353a Mon Sep 17 00:00:00 2001
From: Jules Nsenda
Date: Fri, 20 Nov 2026 11:45:03 +0200
Subject: [PATCH 19/19] fix: never drop a settings error when its field can't
be found
Credential errors had no fallback: if Gravity Forms couldn't find the
named field, the error was lost and a refused key would save. While
validate_credentials() runs, errors now fall back to the Mode field, and
an error with nowhere to go is logged. Scope labels in key errors are
escaped, since Gravity Forms prints field errors as HTML.
Tests: the stub set_field_error() now throws on anything Gravity Forms
would ignore, the fixture renderer only finds the add-on's defined
fields, and the fallback paths are covered.
Note on f37a492: the array argument crashed on every supported PHP
version (7.2+), not only PHP 8.
Co-Authored-By: Claude Opus 5.5
---
class-gf-paystack.php | 23 +++++++++++++++++++----
tests/fixtures.php | 28 +++++++++++++++++++++++++++-
tests/stubs.php | 8 +++++---
tests/test-settings.php | 37 +++++++++++++++++++++++++++++++++++--
4 files changed, 86 insertions(+), 10 deletions(-)
diff --git a/class-gf-paystack.php b/class-gf-paystack.php
index f62712d..26d0914 100644
--- a/class-gf-paystack.php
+++ b/class-gf-paystack.php
@@ -2104,6 +2104,16 @@ public function update_plugin_settings($settings)
* still saves their posted values, so both modes' credentials are checked on every save.
*/
public function validate_credentials($field = null)
+ {
+ $this->validating_field = $field;
+ try {
+ $this->validate_both_modes($field);
+ } finally {
+ $this->validating_field = null;
+ }
+ }
+
+ private function validate_both_modes($field)
{
$selected = rgar($this->get_posted_settings(), 'api_mode');
if ($selected !== 'test' && $selected !== 'live') {
@@ -2115,7 +2125,7 @@ public function validate_credentials($field = null)
$failed = $this->validate_webhook_secret_for_mode($mode) || $failed;
if ($failed && $mode !== $selected && ($selected === 'test' || $selected === 'live')) {
- $this->set_setting_error('api_mode', sprintf(esc_html__('Your %1$s settings have a problem. Select %2$s to see it. No settings were saved.', 'gravityformspaystack'), $mode, $mode === 'test' ? esc_html__('Test', 'gravityformspaystack') : esc_html__('Live', 'gravityformspaystack')));
+ $this->set_setting_error('api_mode', sprintf(esc_html__('Your %1$s settings have a problem. Select %2$s to see it. No settings were saved.', 'gravityformspaystack'), $mode, $mode === 'test' ? esc_html__('Test', 'gravityformspaystack') : esc_html__('Live', 'gravityformspaystack')), $field);
}
}
}
@@ -2287,6 +2297,9 @@ protected function plans_error_message($result, $mode, $context = 'feed')
return esc_html__('We couldn\'t reach Paystack to check this key. Please try again.', 'gravityformspaystack');
}
+ /** The Mode field while validate_credentials() runs: where an error goes if its own field can't be found. */
+ private $validating_field = null;
+
protected function set_save_error($field_name, $message)
{
$this->set_setting_error($field_name, $message . ' ' . esc_html__('No settings were saved.', 'gravityformspaystack'));
@@ -2294,18 +2307,20 @@ protected function set_save_error($field_name, $message)
/**
* Gravity Forms 2.5+ only records an error on the settings field object, passed by reference, so the field is
- * looked up by name. $fallback (the field being validated) keeps the save blocked if the lookup ever fails.
+ * looked up by name. If the lookup fails, the error goes on the field being validated, so the save stays blocked.
*/
protected function set_setting_error($name, $message, $fallback = null)
{
$renderer = $this->get_settings_renderer();
$field = $renderer ? $renderer->get_field($name) : false;
if (!is_object($field)) {
- $field = $fallback;
+ $field = is_object($fallback) ? $fallback : $this->validating_field;
}
if (is_object($field)) {
$this->set_field_error($field, $message);
+ return;
}
+ $this->log_error(__METHOD__ . "(): no settings field to attach an error to ({$name}).");
}
private function other_mode($mode)
@@ -2361,7 +2376,7 @@ protected function scope_labels($scopes)
{
$out = array();
foreach ($scopes as $scope) {
- $out[] = GF_Paystack_Restricted_Key::scope_label($scope);
+ $out[] = esc_html(GF_Paystack_Restricted_Key::scope_label($scope));
}
return implode(', ', $out);
diff --git a/tests/fixtures.php b/tests/fixtures.php
index 59adbb2..3f8bc34 100644
--- a/tests/fixtures.php
+++ b/tests/fixtures.php
@@ -212,15 +212,41 @@ public function __construct($fixture)
$this->fixture = $fixture;
}
+ // Like Gravity Forms, only fields the add-on defines are found; renderer_fields overrides the list.
public function get_field($name)
{
$known = $this->fixture->renderer_fields;
- if (is_array($known) && !in_array($name, $known, true)) {
+ if (!is_array($known)) {
+ $known = self::defined_field_names($this->fixture);
+ }
+ if (!in_array($name, $known, true)) {
return false;
}
return new GFPaystackTestSettingField($name, $this->fixture);
}
+
+ public static function defined_field_names($addon)
+ {
+ $names = array();
+ $collect = function ($items) use (&$collect, &$names) {
+ foreach ((array) $items as $item) {
+ if (!is_array($item)) {
+ continue;
+ }
+ if (isset($item['name'])) {
+ $names[] = $item['name'];
+ }
+ if (isset($item['fields'])) {
+ $collect($item['fields']);
+ }
+ }
+ };
+ $collect($addon->plugin_settings_fields());
+ $collect($addon->feed_settings_fields());
+
+ return $names;
+ }
}
class GFPaystackSettingsFixture extends GFPaystack
diff --git a/tests/stubs.php b/tests/stubs.php
index 3ecb005..fe7fc2a 100644
--- a/tests/stubs.php
+++ b/tests/stubs.php
@@ -156,12 +156,14 @@ public static function include_payment_addon_framework()
if (!class_exists('GFAddOn')) {
class GFAddOn
{
- // Same contract as Gravity Forms 2.5+: the field is a settings field object, passed by reference.
+ // Gravity Forms 2.5+ takes the settings field object by reference and silently ignores anything else;
+ // the stub throws instead, so a dropped error fails the test.
public function set_field_error(&$field, $error_message = '')
{
- if (is_object($field) && method_exists($field, 'set_error')) {
- $field->set_error($error_message);
+ if (!$field instanceof GFPaystackTestSettingField) {
+ throw new LogicException('set_field_error() needs a settings field object');
}
+ $field->set_error($error_message ? $error_message : 'This field is required.');
}
public function get_settings_renderer()
diff --git a/tests/test-settings.php b/tests/test-settings.php
index 9114f3e..4c909c9 100644
--- a/tests/test-settings.php
+++ b/tests/test-settings.php
@@ -432,9 +432,42 @@ public function parent_callback($field, $value = null)
$a = $feed_run(array('transactionType' => 'subscription'), array('api_mode' => 'test', 'test_secret_key' => $st_rk_test, 'live_secret_key' => $st_rk_live));
gf_paystack_test_check($a->plans_calls === array($st_rk_test), 'feed without a mode follows the global api mode');
-// Gravity Forms 2.5+ only records errors on field objects, so errors must never be raised with an array.
+// Gravity Forms 2.5+ only records errors on field objects, so every error goes through set_setting_error().
$plugin_src = file_get_contents(dirname(__DIR__) . '/class-gf-paystack.php');
-gf_paystack_test_check(!preg_match('/set_field_error\(\s*array\(/', $plugin_src), 'no field error is raised with an array (Gravity Forms 2.5+ needs the field object)');
+gf_paystack_test_check(substr_count($plugin_src, '->set_field_error(') === 1, 'set_field_error is only called from set_setting_error');
+$names = GFPaystackTestSettingsRenderer::defined_field_names(new GFPaystackSettingsFixture());
+$wanted = array('api_mode', 'test_secret_key', 'test_webhook_secret', 'live_secret_key', 'live_webhook_secret', 'transactionType');
+gf_paystack_test_check(!array_diff($wanted, $names), 'every field an error is raised on is a defined settings field: missing ' . implode(',', array_diff($wanted, $names)));
+// metaData is added after Gravity Forms' own billingInformation field, which the stubs don't build.
+gf_paystack_test_check(preg_match("/'name'\\s*=>\\s*'metaData'/", $plugin_src) === 1, 'metaData is a defined feed field');
+
+// If a field can't be found, the credential error lands on the Mode field instead of being dropped.
+$cred_lookup_fails = function ($posted, $stored = array()) {
+ $addon = new GFPaystackSettingsFixture();
+ $addon->posted = $posted;
+ $addon->stored = $stored;
+ $addon->renderer_fields = array();
+ $addon->validate_credentials(new GFPaystackTestSettingField('api_mode', $addon));
+
+ return $addon;
+};
+$a = $cred_lookup_fails(array('api_mode' => 'test', 'test_secret_key' => $st_sk_test . 'x'));
+gf_paystack_test_check(strpos($a->field_errors['api_mode'] ?? '', 'Use a test restricted key instead.') === 0, 'credentials: selected-mode key error falls back to Mode when its field is missing');
+$a = $cred_lookup_fails(array('api_mode' => 'test', 'live_secret_key' => $st_sk_live . 'x'));
+gf_paystack_test_check(isset($a->field_errors['api_mode']), 'credentials: other-mode error falls back to Mode when fields are missing');
+$a = $cred_lookup_fails(array('api_mode' => 'test', 'test_secret_key' => $st_rk_test));
+gf_paystack_test_check(isset($a->field_errors['api_mode']), 'credentials: missing signing secret falls back to Mode');
+
+$GLOBALS['gf_paystack_test_gf_logs'] = array();
+$a = new GFPaystackSettingsFixture();
+$a->renderer_fields = array();
+(function () { $this->set_setting_error('nope', 'x'); })->call($a);
+gf_paystack_test_check($a->field_errors === array() && strpos(json_encode($GLOBALS['gf_paystack_test_gf_logs']), 'no settings field to attach an error to (nope)') !== false, 'an error with nowhere to go is logged, not silently dropped');
+
+$a = $st_run('live', array('api_mode' => 'live', 'live_secret_key' => $st_rk_live, 'live_webhook_secret' => $st_ws_live), array(), function ($addon) {
+ $addon->verdict = array('code' => 'sensitive_scope', 'scopes' => array(), 'sensitive_scopes' => array('
'), 'reason' => null, 'probes' => '');
+});
+gf_paystack_test_check(strpos($a->field_errors['live_secret_key'] ?? '', '<img') !== false && strpos($a->field_errors['live_secret_key'], '![]()