-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlibrary.js
More file actions
280 lines (241 loc) · 10.2 KB
/
Copy pathlibrary.js
File metadata and controls
280 lines (241 loc) · 10.2 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
'use strict';
/*
* nodebb-ucashpay
* U.CASH Pay / tip button for NodeBB (crypto + cards, non-custodial).
*
* Two integration surfaces, both powered by the store Cloud Token (publishable):
*
* 1. CLIENT-SIDE hosted pay link (default): the post/profile button links
* directly to https://pay.u.cash/embed.php?<params>. The Cloud Token is
* publishable and safe to expose in the browser, so this needs no server
* secret and works straight from a static page.
*
* 2. SERVER-SIDE tracked checkout (optional): an admin toggle routes the
* button through a NodeBB route that calls the pay.u.cash
* create-transaction endpoint. This records a checkout (idempotent per
* external_reference) so you can reconcile paid orders back to NodeBB
* content. It uses the same publishable store Cloud Token.
*
* See README.md for setup (store Cloud Token at pay.u.cash).
*/
const url = require('url');
const http = require('http');
const https = require('https');
const EMBED_ENDPOINT = 'https://pay.u.cash/embed.php';
const AJAX_ENDPOINT = 'https://pay.u.cash/payment/ajax.php';
const plugin = {};
/* ------------------------------------------------------------------ */
/* NodeBB module accessors (lazily loaded) */
/* ------------------------------------------------------------------ */
function getMeta() {
try { return require.main.require('./src/meta'); }
catch (e) { return null; }
}
function getSettings() {
const meta = getMeta();
return (meta && meta.settings && meta.settings['nodebb-plugin-ucashpay']) || {};
}
function getSetting(key, fallback) {
const settings = getSettings();
const value = settings[key];
if (value === undefined || value === null || value === '') return fallback;
return value;
}
function toBool(value, fallback) {
if (value === undefined || value === null || value === '') return fallback;
return value === true || value === 'true' || value === '1' || value === 1;
}
/* ------------------------------------------------------------------ */
/* URL + HTTP helpers */
/* ------------------------------------------------------------------ */
function buildEmbedUrl(params) {
const query = new URLSearchParams();
if (params.cloud) query.set('cloud', params.cloud);
if (params.amount) query.set('amount', String(params.amount));
query.set('currency', params.currency || 'USD');
if (params.title) query.set('title', params.title);
if (params.external_reference) query.set('external_reference', params.external_reference);
if (params.redirect) query.set('redirect', params.redirect);
return EMBED_ENDPOINT + '?' + query.toString();
}
/* Minimal form-encoded POST with a callback. Node 16+ has global fetch, but
* older NodeBB Node LTS versions may not; keep a portable http(s) impl. */
function postForm(targetUrl, fields, callback) {
let body = '';
Object.keys(fields).forEach((key) => {
const val = fields[key] === undefined || fields[key] === null ? '' : String(fields[key]);
if (body.length) body += '&';
body += encodeURIComponent(key) + '=' + encodeURIComponent(val);
});
const parsed = url.parse(targetUrl);
const transport = parsed.protocol === 'https:' ? https : http;
const options = {
hostname: parsed.hostname,
port: parsed.port,
path: parsed.path,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(body),
'Accept': 'application/json',
'User-Agent': 'nodebb-ucashpay/0.1.0'
}
};
const req = transport.request(options, (res) => {
let data = '';
res.setEncoding('utf8');
res.on('data', (chunk) => { data += chunk; });
res.on('end', () => {
if (res.statusCode < 200 || res.statusCode >= 300) {
return callback(new Error('pay.u.cash returned HTTP ' + res.statusCode));
}
let json;
try { json = JSON.parse(data); } catch (e) {
return callback(new Error('pay.u.cash returned non-JSON response'));
}
callback(null, json);
});
});
req.on('error', callback);
req.write(body);
req.end();
}
/* create-transaction response is { success, response: [paymentUrl, txnId, ...] }.
* The payment URL is the array element starting with http(s)://. */
function extractPaymentUrl(responseBody) {
const arr = (responseBody && responseBody.response) || [];
if (Array.isArray(arr)) {
for (let i = 0; i < arr.length; i++) {
if (typeof arr[i] === 'string' && /^https?:\/\//i.test(arr[i])) {
return arr[i];
}
}
}
return null;
}
/* Public helper: create a tracked checkout on pay.u.cash.
* idempotent per external_reference. */
plugin.createTransaction = function (params, callback) {
postForm(AJAX_ENDPOINT, {
function: 'create-transaction',
amount: params.amount || '',
currency_code: params.currency || 'USD',
cryptocurrency_code: '',
external_reference: params.external_reference || '',
title: params.title || '',
redirect: params.redirect || '',
cloud: params.cloud || '',
idempotent: '1'
}, callback);
};
/* ------------------------------------------------------------------ */
/* Hook: static:app.load -> register server route */
/* ------------------------------------------------------------------ */
plugin.onLoad = function (params, callback) {
const { router, middleware } = params;
const controllers = require('./lib/controllers');
const admin = require('./lib/admin');
// Public checkout route. Calls pay.u.cash create-transaction server-side
// and redirects to the returned payment URL.
router.get('/ucashpay/checkout', middleware.stripGlobalVariable, controllers.embedCheckout);
// ACP settings page.
router.get('/admin/plugins/ucashpay', middleware.admin.buildHeader, admin.render);
router.get('/api/admin/plugins/ucashpay', admin.render);
callback();
};
/* ------------------------------------------------------------------ */
/* Hook: filter:post.getPosts -> attach button data to each post */
/* ------------------------------------------------------------------ */
plugin.posts = {};
plugin.posts.getPosts = function (payload, callback) {
attachButtonData(payload, 'post', callback);
};
/* ------------------------------------------------------------------ */
/* Hook: filter:admin.header.build -> ACP menu entry */
/* ------------------------------------------------------------------ */
plugin.admin = {};
plugin.admin.menu = function (customHeader, callback) {
customHeader.navigation.push({
route: '/plugins/ucashpay',
icon: 'fa-solid fa-coins',
name: 'U.CASH Pay'
});
callback(null, customHeader);
};
/* ------------------------------------------------------------------ */
/* Hook: filter:meta.getMetaTags -> emit publishable client config */
/* ------------------------------------------------------------------ */
plugin.meta = {};
plugin.meta.getMetaTags = function (data, callback) {
const cloud = getSetting('cloudToken', '');
if (!cloud) {
return callback(null, data);
}
const cfg = {
cloud: cloud,
currency: getSetting('defaultCurrency', 'USD'),
amount: getSetting('defaultAmount', ''),
label: getSetting('buttonLabel', 'Tip'),
serverTracked: toBool(getSetting('serverTracked', false), false),
enablePosts: toBool(getSetting('enablePosts', true), true),
enableProfiles: toBool(getSetting('enableProfiles', false), false)
};
// Encoded JSON inside a meta tag so the client script can read publishable
// config without an extra round-trip. The store Cloud Token is publishable.
data.metaTags = data.metaTags || [];
data.metaTags.push({
name: 'ucashpay-config',
content: encodeURIComponent(JSON.stringify(cfg))
});
callback(null, data);
};
/* ------------------------------------------------------------------ */
/* Shared attach logic */
/* ------------------------------------------------------------------ */
function attachButtonData(payload, kind, callback) {
const posts = Array.isArray(payload) ? payload : (payload && payload.posts);
if (!posts || !posts.length) {
return callback(null, payload);
}
const cloud = getSetting('cloudToken', '');
const currency = getSetting('defaultCurrency', 'USD');
const amount = getSetting('defaultAmount', '');
const label = getSetting('buttonLabel', 'Tip');
const serverTracked = toBool(getSetting('serverTracked', false), false);
const enabledForKind = (kind === 'post')
? toBool(getSetting('enablePosts', true), true)
: toBool(getSetting('enableProfiles', false), false);
posts.forEach((post) => {
if (!post) return;
if (!cloud || !enabledForKind) {
post.ucashpay = null;
return;
}
const ref = ['nodebb', kind, String(post.pid || post.uid || '')].join(':');
const title = 'Tip for ' + (post.user && post.user.username ? post.user.username : 'this post');
if (serverTracked) {
post.ucashpay = {
enabled: true,
label: label,
href: '/ucashpay/checkout?ref=' + encodeURIComponent(ref) +
'&title=' + encodeURIComponent(title) +
(amount ? '&amount=' + encodeURIComponent(amount) : '') +
'¤cy=' + encodeURIComponent(currency)
};
} else {
post.ucashpay = {
enabled: true,
label: label,
href: buildEmbedUrl({
cloud: cloud, amount: amount, currency: currency,
title: title, external_reference: ref, redirect: ''
})
};
}
});
callback(null, payload);
}
module.exports = plugin;
module.exports.buildEmbedUrl = buildEmbedUrl;
module.exports.postForm = postForm;
module.exports.extractPaymentUrl = extractPaymentUrl;