-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheadless-wp-members.php
More file actions
413 lines (342 loc) · 17.1 KB
/
headless-wp-members.php
File metadata and controls
413 lines (342 loc) · 17.1 KB
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
<?php
/**
* Plugin Name: Headless WP — Members API
* Description: Registers a "Member Article" custom post type and exposes it via
* a Bearer-token-protected REST API endpoint for a Next.js frontend.
* Version: 1.0.0
* Requires PHP: 7.4
*
* Setup:
* 1. Copy to wp-content/plugins/headless-wp-members/headless-wp-members.php
* 2. Activate via WP Admin → Plugins
* 3. Add to wp-config.php:
* define( 'HEADLESS_API_TOKEN', 'your-secret-token' );
* 4. Set WORDPRESS_API_TOKEN=your-secret-token in Next.js .env.local
*/
if ( ! defined( 'ABSPATH' ) ) exit;
// ─── Custom Post Types ───────────────────────────────────────────────────────
add_action( 'init', 'hwp_register_member_article_cpt' );
add_action( 'init', 'hwp_register_member_cpt' );
// Stores one record per paying customer — email, Stripe session ID, granted_at.
// Lives in WP Admin → Members (not Users), keeping customer data separate from
// WP accounts. No WP user is created for paying customers.
function hwp_register_member_cpt(): void {
register_post_type( 'member', [
'label' => 'Members',
'public' => false,
'show_ui' => true,
'show_in_rest' => false,
'supports' => [ 'title', 'custom-fields' ],
'menu_icon' => 'dashicons-groups',
'capability_type' => 'post',
'rewrite' => false,
] );
}
function hwp_register_member_article_cpt(): void {
register_post_type( 'member_article', [
'label' => 'Member Articles',
'public' => false, // not in sitemaps or public archives
'show_ui' => true, // visible in WP Admin
'show_in_rest' => false, // NOT via core REST — use our custom endpoint
'supports' => [ 'title', 'editor', 'excerpt', 'custom-fields' ],
'menu_icon' => 'dashicons-lock',
'capability_type' => 'post',
'rewrite' => false,
] );
}
// ─── REST API ─────────────────────────────────────────────────────────────────
add_action( 'rest_api_init', 'hwp_register_rest_routes' );
function hwp_register_rest_routes(): void {
$namespace = 'headless/v1';
// GET /wp-json/headless/v1/articles
register_rest_route( $namespace, '/articles', [
'methods' => WP_REST_Server::READABLE,
'callback' => 'hwp_get_articles',
'permission_callback' => 'hwp_check_bearer_token',
'args' => [
'page' => [ 'default' => 1, 'sanitize_callback' => 'absint' ],
'per_page' => [ 'default' => 10, 'sanitize_callback' => 'absint' ],
],
] );
// GET /wp-json/headless/v1/articles/{id}
register_rest_route( $namespace, '/articles/(?P<id>\d+)', [
'methods' => WP_REST_Server::READABLE,
'callback' => 'hwp_get_article',
'permission_callback' => 'hwp_check_bearer_token',
'args' => [
'id' => [
'validate_callback' => fn( $v ) => is_numeric( $v ),
'sanitize_callback' => 'absint',
],
],
] );
// GET /wp-json/headless/v1/articles/public
// Public teaser endpoint — no auth required.
// Returns title, excerpt, date, readTime, category for the home page.
// Full content is intentionally omitted — only authenticated members
// (via /articles and /articles/{id}) can access it.
register_rest_route( $namespace, '/articles/public', [
'methods' => WP_REST_Server::READABLE,
'callback' => 'hwp_get_public_articles',
'permission_callback' => '__return_true',
'args' => [
'page' => [ 'default' => 1, 'sanitize_callback' => 'absint' ],
'per_page' => [ 'default' => 10, 'sanitize_callback' => 'absint' ],
],
] );
// POST /wp-json/headless/v1/grant-membership
// Called by the Next.js Stripe webhook (checkout.session.completed).
// Finds or creates a WP user by email and assigns the member role.
// Protected by the same Bearer token as the article endpoints.
register_rest_route( $namespace, '/grant-membership', [
'methods' => WP_REST_Server::CREATABLE,
'callback' => 'hwp_grant_membership',
'permission_callback' => 'hwp_check_bearer_token',
'args' => [
'email' => [ 'required' => true, 'sanitize_callback' => 'sanitize_email' ],
'stripe_session_id' => [ 'required' => true, 'sanitize_callback' => 'sanitize_text_field' ],
],
] );
// POST /wp-json/headless/v1/set-password
// Called after a successful Stripe payment to let the member set a password
// for future logins. Stores a bcrypt hash in member_password_hash meta.
register_rest_route( $namespace, '/set-password', [
'methods' => WP_REST_Server::CREATABLE,
'callback' => 'hwp_set_password',
'permission_callback' => 'hwp_check_bearer_token',
'args' => [
'email' => [ 'required' => true, 'sanitize_callback' => 'sanitize_email' ],
'password' => [ 'required' => true, 'sanitize_callback' => 'sanitize_text_field' ],
],
] );
// POST /wp-json/headless/v1/verify-credentials
// Called by the Next.js login route to authenticate a returning member.
// Returns { valid: true, session_id } on success, { valid: false } on failure.
register_rest_route( $namespace, '/verify-credentials', [
'methods' => WP_REST_Server::CREATABLE,
'callback' => 'hwp_verify_credentials',
'permission_callback' => 'hwp_check_bearer_token',
'args' => [
'email' => [ 'required' => true, 'sanitize_callback' => 'sanitize_email' ],
'password' => [ 'required' => true, 'sanitize_callback' => 'sanitize_text_field' ],
],
] );
}
// ─── Permission callback ──────────────────────────────────────────────────────
function hwp_check_bearer_token( WP_REST_Request $request ): bool|WP_Error {
$secret = defined( 'HEADLESS_API_TOKEN' ) ? HEADLESS_API_TOKEN : '';
if ( ! $secret ) {
return new WP_Error( 'no_token_configured', 'API token not configured.', [ 'status' => 500 ] );
}
$auth = $request->get_header( 'Authorization' );
$token = '';
if ( $auth && stripos( $auth, 'Bearer ' ) === 0 ) {
$token = trim( substr( $auth, 7 ) );
}
// hash_equals prevents timing attacks
if ( ! hash_equals( $secret, $token ) ) {
return new WP_Error( 'unauthorized', 'Invalid or missing API token.', [ 'status' => 401 ] );
}
return true;
}
// ─── Route handlers ───────────────────────────────────────────────────────────
function hwp_get_articles( WP_REST_Request $request ): WP_REST_Response {
$page = $request->get_param( 'page' );
$per_page = min( $request->get_param( 'per_page' ), 100 );
$query = new WP_Query( [
'post_type' => 'member_article',
'post_status' => 'publish',
'posts_per_page' => $per_page,
'paged' => $page,
'orderby' => 'date',
'order' => 'DESC',
] );
$articles = array_map( 'hwp_format_article', $query->posts );
$response = new WP_REST_Response( [
'articles' => $articles,
'total' => (int) $query->found_posts,
'totalPages' => (int) $query->max_num_pages,
], 200 );
$response->header( 'X-WP-Total', (string) $query->found_posts );
$response->header( 'X-WP-TotalPages', (string) $query->max_num_pages );
return $response;
}
function hwp_get_public_articles( WP_REST_Request $request ): WP_REST_Response {
$page = $request->get_param( 'page' );
$per_page = min( $request->get_param( 'per_page' ), 100 );
$query = new WP_Query( [
'post_type' => 'member_article',
'post_status' => 'publish',
'posts_per_page' => $per_page,
'paged' => $page,
'orderby' => 'date',
'order' => 'DESC',
] );
$articles = array_map( 'hwp_format_article_teaser', $query->posts );
$response = new WP_REST_Response( [
'articles' => $articles,
'total' => (int) $query->found_posts,
'totalPages' => (int) $query->max_num_pages,
], 200 );
$response->header( 'X-WP-Total', (string) $query->found_posts );
$response->header( 'X-WP-TotalPages', (string) $query->max_num_pages );
return $response;
}
function hwp_get_article( WP_REST_Request $request ): WP_REST_Response|WP_Error {
$post = get_post( $request->get_param( 'id' ) );
if ( ! $post || $post->post_type !== 'member_article' || $post->post_status !== 'publish' ) {
return new WP_Error( 'not_found', 'Article not found.', [ 'status' => 404 ] );
}
return new WP_REST_Response( hwp_format_article( $post ), 200 );
}
// ─── Serializer ───────────────────────────────────────────────────────────────
function hwp_format_article( WP_Post $post ): array {
// Only expose whitelisted fields — never json_encode the whole WP_Post object.
$read_time = (int) get_post_meta( $post->ID, 'read_time', true );
$category = (string) get_post_meta( $post->ID, 'article_category', true );
return [
'id' => $post->ID,
'slug' => $post->post_name,
'title' => wp_strip_all_tags( $post->post_title ),
'excerpt' => wp_strip_all_tags( $post->post_excerpt ?: wp_trim_words( $post->post_content, 30 ) ),
'content' => wp_kses_post( $post->post_content ),
'date' => get_the_date( 'c', $post ),
'readTime' => $read_time ?: hwp_estimate_read_time( $post->post_content ),
'category' => $category ?: 'General',
];
}
function hwp_estimate_read_time( string $content ): int {
$word_count = str_word_count( wp_strip_all_tags( $content ) );
return max( 1, (int) ceil( $word_count / 200 ) ); // ~200 wpm
}
// Teaser serializer — omits full content so unauthenticated callers
// can render the public listing without access to member-only body text.
function hwp_format_article_teaser( WP_Post $post ): array {
$read_time = (int) get_post_meta( $post->ID, 'read_time', true );
$category = (string) get_post_meta( $post->ID, 'article_category', true );
return [
'id' => $post->ID,
'slug' => $post->post_name,
'title' => wp_strip_all_tags( $post->post_title ),
'excerpt' => wp_strip_all_tags( $post->post_excerpt ?: wp_trim_words( $post->post_content, 30 ) ),
'date' => get_the_date( 'c', $post ),
'readTime' => $read_time ?: hwp_estimate_read_time( $post->post_content ),
'category' => $category ?: 'General',
// 'content' deliberately excluded — full body requires Bearer token auth
];
}
// ─── On-demand revalidation trigger ──────────────────────────────────────────
// When an article is saved, ping the Next.js revalidation endpoint.
add_action( 'save_post_member_article', 'hwp_trigger_revalidation', 10, 2 );
function hwp_trigger_revalidation( int $post_id, WP_Post $post ): void {
if ( $post->post_status !== 'publish' ) return;
$next_url = defined( 'NEXT_REVALIDATE_URL' ) ? NEXT_REVALIDATE_URL : '';
$secret = defined( 'REVALIDATION_SECRET' ) ? REVALIDATION_SECRET : '';
if ( ! $next_url || ! $secret ) return;
// Bust all three cache layers in one request:
// - 'articles' → member article list (TTL 300 s)
// - 'public-articles' → public teaser list (TTL 3600 s)
// - 'article-{id}' → individual article page (TTL 300 s)
// The Next.js `/api/revalidate` route accepts a `tags` array so all
// three are purged atomically without three round-trips.
// blocking: true with a short timeout — more reliable than fire-and-forget on
// PHP-FPM hosts where the process may terminate before the cURL socket flushes.
// Vercel responds in < 200 ms so the 5 s timeout is never hit in practice.
wp_remote_post( $next_url, [
'headers' => [ 'Content-Type' => 'application/json' ],
'body' => wp_json_encode( [
'secret' => $secret,
'tags' => [ 'articles', 'public-articles', 'article-' . $post_id ],
] ),
'timeout' => 5,
'blocking' => true,
] );
}
// ─── Stripe membership fulfillment ───────────────────────────────────────────
// Called by POST /api/webhooks/stripe in the Next.js app after a successful
// checkout.session.completed event. Finds or creates a `member` CPT post by
// email — no WP user account is created. Customer records live in
// WP Admin → Members, completely separate from the Users list.
function hwp_grant_membership( WP_REST_Request $request ): WP_REST_Response|WP_Error {
$email = $request->get_param( 'email' );
$session_id = $request->get_param( 'stripe_session_id' );
if ( ! is_email( $email ) ) {
return new WP_Error( 'invalid_email', 'Invalid email address.', [ 'status' => 400 ] );
}
// Find existing member post by email meta (idempotent on repeat deliveries).
$existing = get_posts( [
'post_type' => 'member',
'post_status' => 'publish',
'numberposts' => 1,
'meta_query' => [ [
'key' => 'member_email',
'value' => $email,
] ],
] );
if ( $existing ) {
$member_id = $existing[0]->ID;
} else {
// Create a new member record — title is the email for easy scanning in WP Admin.
$member_id = wp_insert_post( [
'post_type' => 'member',
'post_status' => 'publish',
'post_title' => $email,
], true );
if ( is_wp_error( $member_id ) ) {
return new WP_Error(
'member_create_failed',
$member_id->get_error_message(),
[ 'status' => 500 ]
);
}
update_post_meta( $member_id, 'member_email', $email );
}
// Update audit meta on every grant (handles repeat Stripe deliveries).
update_post_meta( $member_id, 'stripe_session_id', $session_id );
update_post_meta( $member_id, 'membership_granted_at', current_time( 'mysql' ) );
return new WP_REST_Response( [
'member_id' => $member_id,
'email' => $email,
'granted' => true,
], 200 );
}
// ─── Password management ──────────────────────────────────────────────────────
function hwp_set_password( WP_REST_Request $request ): WP_REST_Response|WP_Error {
$email = $request->get_param( 'email' );
$password = $request->get_param( 'password' );
if ( strlen( $password ) < 8 ) {
return new WP_Error( 'password_too_short', 'Password must be at least 8 characters.', [ 'status' => 400 ] );
}
$existing = get_posts( [
'post_type' => 'member',
'post_status' => 'publish',
'numberposts' => 1,
'meta_query' => [ [ 'key' => 'member_email', 'value' => $email ] ],
] );
if ( ! $existing ) {
return new WP_Error( 'member_not_found', 'No member found for this email.', [ 'status' => 404 ] );
}
update_post_meta( $existing[0]->ID, 'member_password_hash', password_hash( $password, PASSWORD_BCRYPT ) );
return new WP_REST_Response( [ 'ok' => true ], 200 );
}
function hwp_verify_credentials( WP_REST_Request $request ): WP_REST_Response {
$email = $request->get_param( 'email' );
$password = $request->get_param( 'password' );
$existing = get_posts( [
'post_type' => 'member',
'post_status' => 'publish',
'numberposts' => 1,
'meta_query' => [ [ 'key' => 'member_email', 'value' => $email ] ],
] );
if ( ! $existing ) {
return new WP_REST_Response( [ 'valid' => false ], 200 );
}
$hash = get_post_meta( $existing[0]->ID, 'member_password_hash', true );
if ( ! $hash || ! password_verify( $password, $hash ) ) {
return new WP_REST_Response( [ 'valid' => false ], 200 );
}
return new WP_REST_Response( [
'valid' => true,
'session_id' => (string) get_post_meta( $existing[0]->ID, 'stripe_session_id', true ),
], 200 );
}