-
Notifications
You must be signed in to change notification settings - Fork 1
/
lnbits.php
292 lines (239 loc) · 10.8 KB
/
lnbits.php
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
<?php
/*
Plugin Name: Bitcoin/Lightning Payment Gateway - LNbits
Plugin URI: https://gitlab.com/sovereign-individuals/lnbits-for-woocommerce
Description: Accept Bitcoin over Lightning instantly and without fees
Version: 0.0.4
Author: Phaedrus
Author URI: https://gitlab.com/sovereign-individuals
*/
add_action('plugins_loaded', 'lnbits_init');
define('LNBITS_PAYMENT_PAGE_SLUG', 'lnbits_payment');
require_once(__DIR__ . '/includes/init.php');
use LNbitsPlugin\Utils;
use LNbitsPlugin\LNbitsAPI;
function woocommerce_lnbits_activate() {
if (!current_user_can('activate_plugins')) return;
global $wpdb;
if ( null === $wpdb->get_row( "SELECT post_name FROM {$wpdb->prefix}posts WHERE post_name = '".LNBITS_PAYMENT_PAGE_SLUG."'", 'ARRAY_A' ) ) {
$page = array(
'post_title' => __( 'Lightning Payment' ),
'post_name' => LNBITS_PAYMENT_PAGE_SLUG,
'post_status' => 'publish',
'post_author' => wp_get_current_user()->ID,
'post_type' => 'page',
'post_content' => render_template('payment_page.php', array())
);
// insert the post into the database
wp_insert_post( $page );
}
}
register_activation_hook(__FILE__, 'woocommerce_lnbits_activate');
// Helper to render templates under ./templates.
function render_template($tpl_name, $params) {
return wc_get_template_html($tpl_name, $params, '', plugin_dir_path(__FILE__).'templates/');
}
// Generate lnbits_payment page, using ./templates/lnbits_payment.php
function lnbits_payment_shortcode() {
$check_payment_url = trailingslashit(get_bloginfo('wpurl')) . '?wc-api=wc_gateway_lnbits';
if (isset($_REQUEST['order_id'])) {
$order_id = absint($_REQUEST['order_id']);
$order = wc_get_order($order_id);
$invoice = $order->get_meta("lnbits_invoice");
$success_url = $order->get_checkout_order_received_url();
} else {
// Likely when editting page with this shortcode, use dummy order.
$order_id = 1;
$invoice = "lnbc0000";
$success_url = "/dummy-success";
}
$template_params = array(
"invoice" => $invoice,
"check_payment_url" => $check_payment_url,
'order_id' => $order_id,
'success_url' => $success_url
);
return render_template('payment_shortcode.php', $template_params);
}
// This is the entry point of the plugin, where everything is registered/hooked up into WordPress.
function lnbits_init() {
if (!class_exists('WC_Payment_Gateway')) {
return;
};
// Register shortcode for rendering Lightning invoice (QR code)
add_shortcode('lnbits_payment_shortcode', 'lnbits_payment_shortcode');
// Set the cURL timeout to 15 seconds. When requesting a lightning invoice
// over Tor, a short timeout can result in failures.
add_filter('http_request_args', 'lnbits_http_request_args', 100, 1);
function lnbits_http_request_args($r) //called on line 237
{
$r['timeout'] = 15;
return $r;
}
add_action('http_api_curl', 'lnbits_http_api_curl', 100, 1);
function lnbits_http_api_curl($handle) //called on line 1315
{
curl_setopt( $handle, CURLOPT_CONNECTTIMEOUT, 15 );
curl_setopt( $handle, CURLOPT_TIMEOUT, 15 );
}
// Register the gateway, essentially a controller that handles all requests.
function add_lnbits_gateway($methods) {
$methods[] = 'WC_Gateway_LNbits';
return $methods;
}
add_filter('woocommerce_payment_gateways', 'add_lnbits_gateway');
// Defined here, because it needs to be defined after WC_Payment_Gateway is already loaded.
class WC_Gateway_LNbits extends WC_Payment_Gateway {
public function __construct() {
global $woocommerce;
$this->id = 'lnbits';
$this->icon = plugin_dir_url(__FILE__).'assets/lightning.png';
$this->has_fields = false;
$this->method_title = 'LNbits';
$this->method_description = 'Take payments in Bitcoin over Lightning, without extra fees, using LNbits.';
$this->init_form_fields();
$this->init_settings();
$this->title = $this->get_option('title');
$this->description = $this->get_option('description');
$url = $this->get_option('lnbits_url');
$api_key = $this->get_option('lnbits_api_key');
$this->api = new LNbitsAPI($url, $api_key);
add_action('woocommerce_update_options_payment_gateways_'.$this->id, array($this, 'process_admin_options'));
add_action('woocommerce_api_wc_gateway_'.$this->id, array($this, 'check_payment'));
}
/**
* Render admin options/settings.
*/
public function admin_options() {
?>
<h3><?php _e('LNbits', 'woothemes'); ?></h3>
<p><?php _e('Accept Bitcoin instantly through LNbits/Lightning.', 'woothemes'); ?></p>
<table class="form-table">
<?php $this->generate_settings_html(); ?>
</table>
<?php
}
/**
* Generate config form fields, shown in admin->WooCommerce->Settings.
*/
public function init_form_fields() {
// echo("init_form_fields");
$this->form_fields = array(
'enabled' => array(
'title' => __('Enable LNbits payment', 'woocommerce'),
'label' => __('Enable Bitcoin payments via LNbits', 'woocommerce'),
'type' => 'checkbox',
'description' => '',
'default' => 'no',
),
'title' => array(
'title' => __('Title', 'woocommerce'),
'type' => 'text',
'description' => __('The payment method title which a customer sees at the checkout of your store.', 'woocommerce'),
'default' => __('Pay with Bitcoin over Lightning via LNbits', 'woocommerce'),
),
'description' => array(
'title' => __('Description', 'woocommerce'),
'type' => 'textarea',
'description' => __('The payment method description which a customer sees at the checkout of your store.', 'woocommerce'),
'default' => __('Powered by LNbits. You can use any Lightning wallet to pay.'),
),
'lnbits_api_key' => array(
'title' => __('LNbits API Invoice/Read Key', 'woocommerce'),
'type' => 'text',
'description' => __('Available from your LNbits\' wallet\'s API info sidebar.', 'woocommerce'),
'default' => '',
),
'lnbits_url' => array(
'title' => __('LNbits URL', 'woocommerce'),
'description' => __('URL where LNbits server is running.', 'woocommerce'),
'type' => 'text',
'default' => 'https://legend.lnbits.com',
),
);
}
/**
* ? Output for thank you page.
*/
public function thankyou() {
if ($description = $this->get_description()) {
echo esc_html(wpautop(wptexturize($description)));
}
}
/**
* Called from checkout page, when "Place order" hit, through AJAX.
*
* Call LNbits API to create an invoice, and store the invoice in the order metadata.
*/
public function process_payment($order_id) {
$order = wc_get_order($order_id);
// This will be stored in the Lightning invoice (ie. can be used to match orders in LNbits)
$memo = "WordPress Order=".$order->get_id()." Total=".$order->get_total().get_woocommerce_currency();
$amount = Utils::convert_to_satoshis($order->get_total(), get_woocommerce_currency());
// Call LNbits server to create invoice
// Expected 201
// {
// "checking_id": "e0dfcde5ff9708d71e5947c86b9d46cc230fd0f16e0a5f03b00ac97f0b23e684",
// "lnurl_response": null,
// "payment_hash": "e0dfcde5ff9708d71e5947c86b9d46cc230fd0f16e0a5f03b00ac97f0b23e684",
// "payment_request": "..."
// }
$r = $this->api->createInvoice($amount, $memo);
if ($r['status'] == 201) {
$resp = $r['response'];
$order->add_meta_data('lnbits_invoice', $resp['payment_request'], true);
$order->add_meta_data('lnbits_payment_hash', $resp['payment_hash'], true);
$order->save();
// TODO: configurable payment page slug
$redirect_url = add_query_arg(array("order_id" => $order->get_id()), get_permalink( get_page_by_path( LNBITS_PAYMENT_PAGE_SLUG ) ));
return array(
"result" => "success",
"redirect" => $redirect_url
);
} else {
error_log("LNbits API failure. Status=".$r['status']);
error_log($r['response']);
return array(
"result" => "failure",
"messages" => array("Failed to create LNbits invoice.")
);
}
}
/**
* Called by lnbits_payment page (with QR code), through ajax.
*
* Checks whether given invoice was paid, using LNbits API,
* and updates order metadata in the database.
*/
public function check_payment() {
$order = wc_get_order($_REQUEST['order_id']);
$payment_hash = $order->get_meta('lnbits_payment_hash');
$r = $this->api->checkInvoicePaid($payment_hash);
if ($r['status'] == 200) {
if ($r['response']['paid'] == true) {
$order->add_order_note('Payment is settled and has been credited to your LNbits account. Purchased goods/services can be securely delivered to the customer.');
$order->payment_complete();
$order->save();
error_log("PAID");
echo(json_encode(array(
'result' => 'success',
'redirect' => $order->get_checkout_order_received_url(),
'paid' => true
)));
} else {
echo(json_encode(array(
'result' => 'success',
'paid' => false
)));
}
} else {
echo(json_encode(array(
'result' => 'failure',
'paid' => false,
'messages' => array('Request to LNbits failed.')
)));
}
die();
}
}
}