diff --git a/payments_payu/provider.py b/payments_payu/provider.py index 1f84a89..9387325 100644 --- a/payments_payu/provider.py +++ b/payments_payu/provider.py @@ -340,7 +340,7 @@ def post_request(self, url, *args, **kwargs): kwargs["headers"] = self.get_token_headers() response = requests.post(url, *args, **kwargs) response_dict = json.loads(response.text) - if ( + if (response_dict.get("error") == "invalid_token") or ( "status" in response_dict and "statusCode" in response_dict["status"] and response_dict["status"]["statusCode"] == "UNAUTHORIZED" diff --git a/tests/test_payu.py b/tests/test_payu.py index 7719708..1cb9441 100644 --- a/tests/test_payu.py +++ b/tests/test_payu.py @@ -491,6 +491,34 @@ def test_redirect_payu_unauthorized_status(self): headers={"Content-Type": "application/x-www-form-urlencoded"}, ) + def test_redirect_payu_unauthorized_error(self): + self.set_up_provider( + True, False, get_refund_description=lambda payment, amount: "test" + ) + + with patch("requests.post") as mocked_post: + mocked_post.return_value = MagicMock( + status_code=401, + text='{"error": "invalid_token", "error_description": "Access token expired"}', + ) + + with self.assertRaisesRegex( + PayuApiError, + r"^Unable to regain authorization token " + r"\{'error': 'invalid_token', 'error_description': 'Access token expired'}$", + ): + self.provider.get_form(payment=self.payment) + + mocked_post.assert_called_with( + "http://mock.url/pl/standard/user/oauth/authorize", + data={ + "grant_type": "client_credentials", + "client_id": "123abc", + "client_secret": "123abc", + }, + headers={"Content-Type": "application/x-www-form-urlencoded"}, + ) + def test_get_access_token_trusted_merchant(self): self.set_up_provider( True, False, get_refund_description=lambda payment, amount: "test"