InvoiceRedirectMiddleware.php
| 1 | <?php |
| 2 | namespace SureCart\Middleware; |
| 3 | |
| 4 | use Closure; |
| 5 | use SureCart\Models\Invoice; |
| 6 | use SureCartCore\Requests\RequestInterface; |
| 7 | use SureCartCore\Responses\RedirectResponse; |
| 8 | |
| 9 | /** |
| 10 | * Middleware for handling invoice redirects. |
| 11 | */ |
| 12 | class InvoiceRedirectMiddleware { |
| 13 | /** |
| 14 | * Handle the invoice redirect. |
| 15 | * |
| 16 | * @param RequestInterface $request Request. |
| 17 | * @param Closure $next Next middleware. |
| 18 | * |
| 19 | * @return RedirectResponse|\SureCartVendors\Psr\Http\Message\ResponseInterface |
| 20 | */ |
| 21 | public function handle( RequestInterface $request, Closure $next ) { |
| 22 | $id = $request->query( 'invoice_id' ); |
| 23 | |
| 24 | // no invoice id, next request. |
| 25 | if ( empty( $id ) ) { |
| 26 | return $next( $request ); |
| 27 | } |
| 28 | |
| 29 | // Find the invoice and redirect to the invoice's checkout |
| 30 | $invoice = Invoice::find($id); |
| 31 | |
| 32 | // show error if the invoice is not found. |
| 33 | if ( is_wp_error( $invoice ) ) { |
| 34 | return wp_die( wp_kses_post( $invoice->get_error_message() ) ); |
| 35 | } |
| 36 | |
| 37 | // show error if the invoice does not have a checkout id. |
| 38 | if ( empty( $invoice->id ) ) { |
| 39 | return wp_die( esc_html__( 'Invoice not found.', 'surecart' ) ); |
| 40 | } |
| 41 | |
| 42 | // show error if the invoice checkout is not found. |
| 43 | if ( empty( $invoice->checkout_id ) ) { |
| 44 | return wp_die( esc_html__( 'Invoice checkout not found.', 'surecart' ) ); |
| 45 | } |
| 46 | |
| 47 | // redirect to the invoice's checkout. |
| 48 | return ( new RedirectResponse( $request ) )->to( |
| 49 | add_query_arg( |
| 50 | [ |
| 51 | 'checkout_id' => $invoice->checkout_id, |
| 52 | ], |
| 53 | \SureCart::getUrl()->checkout() |
| 54 | ) |
| 55 | ); |
| 56 | } |
| 57 | } |
| 58 |