Jake Vanderwerf
10 days ago 97e7c319d656a5f05489ca996e249e7359303d4d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
<?php
namespace JVBase\rest\routes;
 
use JVBase\rest\Rest;
use JVBase\rest\Route;
use WP_REST_Request;
use WP_REST_Response;
use Exception;
 
if (!defined('ABSPATH')) {
    exit;
}
 
class IntegrationsHelcimRoutes extends Rest
{
    public function registerRoutes(): void
    {
        Route::for('helcim/initialize-checkout')
            ->post([$this, 'handleInitializeCheckout'])
            ->auth('user')
            ->rateLimit(5)
            ->register();
 
        Route::for('helcim/invoices')
            ->get([$this, 'getInvoices'])
            ->auth('user')
            ->rateLimit(10)
            ->register();
 
        Route::for(Route::pattern('helcim/invoices/{invoice_id}'))
            ->get([$this, 'getInvoice'])
            ->auth('user')
            ->rateLimit(10)
            ->register();
 
        Route::for('helcim/saved-cards')
            ->get([$this, 'getSavedCards'])
            ->auth('user')
            ->rateLimit(5)
            ->register();
 
        Route::for('helcim/validate-transaction')
            ->post([$this, 'validateTransaction'])
            ->auth('user')
            ->rateLimit(10)
            ->register();
    }
 
    /**
     * Initialize a HelcimPay.js checkout session.
     *
     * Returns checkoutToken for the frontend to call
     * appendHelcimPayIframe(checkoutToken).
     */
    public function handleInitializeCheckout(WP_REST_Request $request): WP_REST_Response
    {
        $data    = $request->get_json_params();
        $user_id = absint($data['user'] ?? get_current_user_id());
 
        if (empty($data['amount'])) {
            return $this->validationError(['message' => 'Amount is required']);
        }
 
        try {
            $helcim = JVB()->connect('helcim');
 
            // Auto-resolve customer ID from logged-in user
            if (empty($data['customerId']) && $user_id) {
                $data['customerId'] = $helcim->resolveCustomerId($user_id);
            }
 
            $result = $helcim->initializeCheckout($data);
 
            if (!$result['success']) {
                return $this->error($result['message'] ?? 'Checkout initialization failed');
            }
 
            return $this->success($result);
 
        } catch (Exception $e) {
            $this->logError('Helcim checkout init failed', ['error' => $e->getMessage()]);
            return $this->error($e->getMessage());
        }
    }
 
    /**
     * Get invoices for the current user.
     */
    public function getInvoices(WP_REST_Request $request): WP_REST_Response
    {
        $user_id = absint($request->get_param('user') ?? get_current_user_id());
 
        if (!$user_id) {
            return $this->validationError(['message' => 'Not logged in']);
        }
 
        try {
            $helcim    = JVB()->connect('helcim');
            $user      = get_userdata($user_id);
            $result    = $helcim->handleGetInvoices([
                'email' => $user->user_email,
            ]);
 
            return $this->success($result);
 
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
    }
 
    /**
     * Get a single invoice by Helcim invoice ID.
     */
    public function getInvoice(WP_REST_Request $request): WP_REST_Response
    {
        $invoiceId = $request->get_param('invoice_id');
 
        if (!$invoiceId) {
            return $this->validationError(['message' => 'Invoice ID required']);
        }
 
        try {
            $helcim = JVB()->connect('helcim');
            $result = $helcim->handleGetInvoice(['invoiceId' => $invoiceId]);
 
            return $this->success($result);
 
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
    }
 
    /**
     * Get saved cards for the current user.
     */
    public function getSavedCards(WP_REST_Request $request): WP_REST_Response
    {
        $user_id = absint($request->get_param('user') ?? get_current_user_id());
 
        if (!$user_id) {
            return $this->validationError(['message' => 'Not logged in']);
        }
 
        try {
            $helcim = JVB()->connect('helcim');
            $result = $helcim->handleGetCustomerCards([
                'email' => get_userdata($user_id)->user_email,
            ]);
 
            return $this->success($result);
 
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
    }
 
    /**
     * Validate a HelcimPay.js transaction server-side.
     *
     * Called after the frontend receives a SUCCESS message event.
     * Verifies the transaction hash using the secretToken stored
     * in the user's session/transient.
     */
    public function validateTransaction(WP_REST_Request $request): WP_REST_Response
    {
        $data = $request->get_json_params();
 
        if (empty($data['secretToken']) || empty($data['transactionData'])) {
            return $this->validationError(['message' => 'Missing secretToken or transactionData']);
        }
 
        try {
            $helcim = JVB()->connect('helcim');
            $valid  = $helcim->validateTransaction(
                $data['secretToken'],
                $data['transactionData']
            );
 
            return $this->success([
                'valid' => $valid,
            ]);
 
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
    }
}