This will be mostly a Drupal question rather may not have any relation to Drupal commerce checkout.

I have an Offsite Checkout redirect payment method in which I have a buildRedirectFrom as stated in https://docs.drupalcommerce.org/commerce2/developer-guide/payments/create-payment-gateway/off-site-gateways/off-site-redirect which will redirect to a vendor site for payment. I have the CompleteUrl which will come back the call to the controller method after payment completion.

I need to show a custom error message after redirecting to the checkout page, when the payment fails or canceled the payment based on the status I receive from vendor API.

But somehow the message is not showing up after the redirection. I tried to show the message first and then redirect too. Is there any solution in Drupal or particularly in commerce for this?

My try

In controller method:

if( $statusFromAPI != 'PAYSUCCESS' ){
        $redirect = new RedirectResponse('/checkout/' .$order_id . '/review');
        if($statusFromAPI == 'ERROR'){
          $this->messenger()->addError("Payment has been failed. Please check the payment details.", TRUE);
        } else if($statusFromAPI == 'PAYSTART'){
          $this->messenger()->addWarning("Please review the payment details again.");
        } else{
          $this->messenger()->addWarning("Please review the payment details.", TRUE);

1 Answer 1


A controller has to return the result, this includes the redirect response. But before you have to set the message:

$redirect = new RedirectResponse('/checkout/' . $order_id . '/review');
$this->messenger()->addWarning('This is a warning!');
return $redirect;

BTW in Drupal it's not allowed to send responses. If you are in a form you can set it in $form_state, in an event subscriber set it in the event if it is one of the three main Symfony kernel events.

  • Fortunately, I have to give an exit after sending the redirection. As mentioned in drupal.stackexchange.com/questions/198906/…. But the approach works as we have to set the message before the redirection has been called. +1
    – KTM
    Commented Sep 25, 2023 at 10:42
  • 1
    Read the warning in the first comment under the linked question. The OP asked how to get a hacky code working. This doesn't make it any less wrong.
    – 4uk4
    Commented Sep 25, 2023 at 11:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.