Advertisement
swte

Create WP order

May 14th, 2025
576
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.87 KB | None | 0 0
  1. <?php
  2. /**
  3.  * Plugin Name: Stripe Sync Order
  4.  * Description: REST API endpoint for creating and completing WooCommerce orders via Stripe webhook or other external service.
  5.  * Version: 1.0
  6.  * Author: T+GM Consulting
  7.  */
  8.  
  9. // Register custom REST endpoint
  10. add_action('rest_api_init', function () {
  11.     register_rest_route('stripe-sync/v1', '/create-order', [
  12.         'methods'  => 'POST',
  13.         'callback' => 'stripe_sync_create_order',
  14.         'permission_callback' => '__return_true', // Biztonság: majd érdemes lehet hitelesítést tenni rá
  15.     ]);
  16. });
  17.  
  18. function stripe_sync_create_order(WP_REST_Request $request) {
  19.     $product_id = 123; // ← IDE írd be a termék ID-ját
  20.     $user_id = 0; // 0 ha guest user
  21.     $quantity = 1;
  22.  
  23.     // Dummy billing address
  24.     $address = [
  25.         'first_name' => 'Stripe',
  26.         'last_name'  => 'User',
  27.         'email'      => '[email protected]',
  28.         'phone'      => '06301234567',
  29.         'address_1'  => 'Stripe Street 1',
  30.         'city'       => 'Budapest',
  31.         'postcode'   => '1111',
  32.         'country'    => 'HU',
  33.     ];
  34.  
  35.     try {
  36.         $order = wc_create_order(['customer_id' => $user_id]);
  37.         $product = wc_get_product($product_id);
  38.         if (!$product) {
  39.             return new WP_Error('invalid_product', 'A megadott termék nem létezik', ['status' => 400]);
  40.         }
  41.  
  42.         $order->add_product($product, $quantity);
  43.         $order->set_address($address, 'billing');
  44.         $order->calculate_totals();
  45.         $order->update_status('completed', 'Rendelés automatikusan lezárva Stripe-ból.');
  46.  
  47.         return [
  48.             'success' => true,
  49.             'order_id' => $order->get_id(),
  50.             'status' => $order->get_status(),
  51.         ];
  52.  
  53.     } catch (Exception $e) {
  54.         return new WP_Error('order_creation_failed', $e->getMessage(), ['status' => 500]);
  55.     }
  56. }
  57.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement