| 1 |
<?php |
| 2 |
|
| 3 |
namespace Templately\API; |
| 4 |
|
| 5 |
/** |
| 6 |
* Plugin-initiated checkout. |
| 7 |
* |
| 8 |
* Asks the backend for a frontend checkout URL carrying a short-lived login |
| 9 |
* token bound to the connected api_key account (no front-end re-login), and |
| 10 |
* hands it back to the React app, which redirects the buyer to it. After |
| 11 |
* payment the frontend returns the buyer to `return_url` with |
| 12 |
* `templately_purchase`. |
| 13 |
*/ |
| 14 |
class Checkout extends API { |
| 15 |
|
| 16 |
public function register_routes() { |
| 17 |
$this->post( 'checkout', [ $this, 'checkout' ] ); |
| 18 |
} |
| 19 |
|
| 20 |
public function checkout() { |
| 21 |
$purchase_type = $this->get_param( 'purchase_type', 'template' ); |
| 22 |
$id = $this->get_param( 'id', 0, 'intval' ); |
| 23 |
$return_url = $this->get_param( 'return_url', admin_url( 'admin.php?page=templately' ), 'esc_url_raw' ); |
| 24 |
|
| 25 |
if ( empty( $id ) ) { |
| 26 |
return $this->error( 'invalid_checkout_item', __( 'No item selected for purchase.', 'templately' ), 'checkout', 422 ); |
| 27 |
} |
| 28 |
|
| 29 |
$funcArgs = [ |
| 30 |
'api_key' => $this->api_key, |
| 31 |
'purchase_type' => $purchase_type, |
| 32 |
'id' => $id, |
| 33 |
'return_url' => $return_url, |
| 34 |
]; |
| 35 |
|
| 36 |
foreach ( [ 'item_type', 'billing_interval', 'coupon' ] as $optional ) { |
| 37 |
$value = $this->get_param( $optional, '' ); |
| 38 |
if ( ! empty( $value ) ) { |
| 39 |
$funcArgs[ $optional ] = $value; |
| 40 |
} |
| 41 |
} |
| 42 |
|
| 43 |
$response = $this->http()->mutation( 'pluginCheckout', 'status, message, data', $funcArgs )->post(); |
| 44 |
|
| 45 |
if ( is_wp_error( $response ) ) { |
| 46 |
return $this->error( 'invalid_checkout_response', $response->get_error_message(), 'checkout' ); |
| 47 |
} |
| 48 |
|
| 49 |
$data = ! empty( $response['data'] ) ? json_decode( $response['data'], true ) : []; |
| 50 |
|
| 51 |
// Frontend checkout URL created — the app redirects the buyer to it. |
| 52 |
if ( ! empty( $data['url'] ) ) { |
| 53 |
return $this->success( [ 'url' => $data['url'] ] ); |
| 54 |
} |
| 55 |
|
| 56 |
$message = ! empty( $response['message'] ) ? $response['message'] : __( 'Could not start the checkout. Please try again.', 'templately' ); |
| 57 |
|
| 58 |
return $this->error( 'checkout_failed', $message, 'checkout' ); |
| 59 |
} |
| 60 |
} |
| 61 |
|