forked from joaodealmeida/woocommerce-gateway-lightning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwoocommerce-gateway-lightning.php
274 lines (230 loc) · 10.6 KB
/
woocommerce-gateway-lightning.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
<?php
/*
Plugin Name: WooCommerce Lightning Gateway
Plugin URI: https://joaoalmeida.me
Description: Enable instant and fee-reduced payments in BTC and LTC through Lightning Network.
Author: João Almeida
Author URI: https://joaoalmeida.me
Version: 0.1.0
GitHub Plugin URI: https://github.com/joaodealmeida/woocommerce-gateway-zap
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
register_activation_hook( __FILE__, function(){
if (!extension_loaded('gd') || !extension_loaded('curl')) {
die('The php-curl and php-gd extensions are required. Please contact your hosting provider for additional help.');
}
});
require_once 'Lnd_wrapper.php';
if (!function_exists('init_wc_lightning')) {
function init_wc_lightning() {
if (!class_exists('WC_Payment_Gateway')) return;
class WC_Gateway_Lightning extends WC_Payment_Gateway {
public function __construct() {
$this->id = 'lightning';
$this->order_button_text = __('Proceed to Lightning Payment', 'woocommerce');
$this->method_title = __('Lightning', 'woocommerce');
$this->method_description = __('Lightning Network Payment');
$this->icon = plugin_dir_url(__FILE__).'img/logo.png';
$this->supports = array();
// Load the settings.
$this->init_form_fields();
$this->init_settings();
// Define user set variables.
$this->title = $this->get_option('title');
$this->description = $this->get_option('description');
$this->endpoint = $this->get_option( 'endpoint' );
$this->macaroon = $this->get_option( 'macaroon' );
$this->lndCon = LndWrapper::instance();
$this->lndCon->setCredentials ( $this->get_option( 'endpoint' ), $this->get_option( 'macaroon' ), $this->get_option( 'ssl' ));
$this->lndCon->setCoin( $this->get_option( 'coin' ) );
add_action('woocommerce_payment_gateways', array($this, 'register_gateway'));
add_action('woocommerce_update_options_payment_gateways_lightning', array($this, 'process_admin_options'));
add_action('woocommerce_receipt_lightning', array($this, 'show_payment_info'));
add_action('woocommerce_thankyou_lightning', array($this, 'show_payment_info'));
add_action('wp_ajax_ln_wait_invoice', array($this, 'wait_invoice'));
add_action('wp_ajax_nopriv_ln_wait_invoice', array($this, 'wait_invoice'));
}
/**
* Initialise Gateway Settings Form Fields.
*/
public function init_form_fields() {
$tlsPath = plugin_dir_path(__FILE__).'tls/tls.cert';
$this->form_fields = array(
'enabled' => array(
'title' => __( 'Enable/Disable', 'woocommerce-gateway-lightning' ),
'label' => __( 'Enable Lightning payments', 'woocommerce-gateway-lightning' ),
'type' => 'checkbox',
'description' => '',
'default' => 'no',
),
'title' => array(
'title' => __('Title', 'lightning'),
'type' => 'text',
'description' => __('Controls the name of this payment method as displayed to the customer during checkout.', 'lightning'),
'default' => __('Bitcoin Lightning', 'lightning'),
'desc_tip' => true,
),
'coin' => array(
'title' => __('Coin', 'lightning'),
'type' => 'select',
'description' => __('Select the coin network your LND is connected to.', 'lightning'),
'default' => __('BTC', 'lightning'),
'options' => array(
'BTC' => __('BTC','lightning'),
'LTC' => __('LTC','lightning')
),
'desc_tip' => true,
),
'endpoint' => array(
'title' => __( 'Endpoint', 'lightning' ),
'type' => 'textarea',
'description' => __( 'Place here the API endpoint', 'lightning' ),
'default' => 'https://localhost:8080',
'desc_tip' => true,
),
'macaroon' => array(
'title' => __('Macaroon Hex', 'lightning'),
'type' => 'textarea',
'description' => __('Input Macaroon Hex to get access to LND API', 'lightning'),
'default' => '',
'desc_tip' => true,
),
'description' => array(
'title' => __('Customer Message', 'lightning'),
'type' => 'textarea',
'description' => __('Message to explain how the customer will be paying for the purchase.', 'lightning'),
'default' => 'You will pay using the Lightning Network.',
'desc_tip' => true,
),
'ssl' => array(
'title' => __('SSL Certificate Path', 'lightning'),
'type' => 'textarea',
'description' => __('Put your LND SSL certificate path.', 'lightning'),
'default' => $tlsPath,
'desc_tip' => true,
)
);
}
/**
* Process the payment and return the result.
* @param int $order_id
* @return array
*/
public function process_payment( $order_id ) {
$order = wc_get_order($order_id);
$usedCurrency = get_woocommerce_currency();
$livePrice = $this->lndCon->getLivePrice();
$invoiceInfo = array();
$btcPrice = $order->get_total() * ((float)1/ $livePrice);
$invoiceInfo['value'] = round($btcPrice * 100000000);
$invoiceInfo['memo'] = "Order key: " . $order->get_checkout_order_received_url();
$invoiceResponse = $this->lndCon->createInvoice ( $invoiceInfo );
if(property_exists($invoiceResponse, 'error')){
wc_add_notice( __('Error: ', 'lightning') . $invoiceResponse->error, 'error' );
return;
}
if(!property_exists($invoiceResponse, 'payment_request')) {
wc_add_notice( __('Error: ', 'lightning') . 'Lightning Node is not reachable at this time. Please contact the store administrator.', 'error' );
return;
}
update_post_meta( $order->get_id(), 'LN_INVOICE', $invoiceResponse->payment_request, true);
update_post_meta( $order->get_id(), 'LN_HASH', $invoiceResponse->r_hash, true);
$order->add_order_note("Awaiting payment of " . number_format((float)$btcPrice, 7, '.', '') . " " . $this->lndCon->getCoin() . "@ 1 " . $this->lndCon->getCoin() . " ~ " . $livePrice ." USD. <br> Invoice ID: " . $invoiceResponse->payment_request);
return array(
'result' => 'success',
'redirect' => $order->get_checkout_payment_url(true)
);
}
/**
* JSON endpoint for long polling payment updates.
*/
public function wait_invoice() {
$order = wc_get_order($_POST['invoice_id']);
if($order->get_status() == 'processing'){
status_header(200);
wp_send_json(true);
return;
}
/**
*
* Check if invoice is paid
*/
$payHash = get_post_meta( $_POST['invoice_id'], 'LN_HASH', true );
$callResponse = $this->lndCon->getInvoiceInfoFromHash( bin2hex(base64_decode( $payHash ) ) );
if(!property_exists( $callResponse, 'r_hash' )) {
status_header(410);
wp_send_json(false);
return;
}
$invoiceTime = $callResponse->creation_date + $callResponse->expiry;
if($invoiceTime < time()) {
//Invoice expired
$livePrice = $this->lndCon->getLivePrice();
$invoiceInfo = array();
$btcPrice = $order->get_total() * ((float)1/ $livePrice);
$invoiceInfo['value'] = round($btcPrice * 100000000);
$invoiceInfo['memo'] = "Order key: " . $order->get_checkout_order_received_url();
$invoiceResponse = $this->lndCon->createInvoice ( $invoiceInfo );
update_post_meta( $order->get_id(), 'LN_INVOICE', $invoiceResponse->payment_request);
update_post_meta( $order->get_id(), 'LN_HASH', $invoiceResponse->r_hash);
$order->add_order_note("Awaiting payment of " . number_format((float)$btcPrice, 7, '.', '') . " " . $this->lndCon->getCoin() . "@ 1 " . $this->lndCon->getCoin() . " ~ " . $livePrice ." USD. <br> Invoice ID: " . $invoiceResponse->payment_request);
status_header(410);
wp_send_json(false);
return;
}
if(!property_exists( $callResponse, 'settled' )){
status_header(402);
wp_send_json(false);
return;
}
if ($callResponse->settled) {
$order->payment_complete();
$order->add_order_note('Lightning Payment received on ' . $invoiceRep->settle_date);
status_header(200);
wp_send_json(true);
return;
}
}
/**
* Hooks into the checkout page to display Lightning-related payment info.
*/
public function show_payment_info($order_id) {
global $wp;
$order = wc_get_order($order_id);
if (!empty($wp->query_vars['order-received']) && $order->needs_payment()) {
// thankyou page requested, but order is still unpaid
wp_redirect($order->get_checkout_payment_url(true));
exit;
}
if ($order->has_status('cancelled')) {
// invoice expired, reload page to display expiry message
wp_redirect($order->get_checkout_payment_url(true));
exit;
}
if ($order->needs_payment()) {
//Prepare information for payment page
$qr_uri = $this->lndCon->generateQr( get_post_meta( $order_id, 'LN_INVOICE', true ) );
$payHash = get_post_meta( $order_id, 'LN_HASH', true );
$callResponse = $this->lndCon->getInvoiceInfoFromHash( bin2hex(base64_decode($payHash)) );
require __DIR__.'/templates/payment.php';
} elseif ($order->has_status(array('processing', 'completed'))) {
require __DIR__.'/templates/completed.php';
}
}
/**
* Register as a WooCommerce gateway.
*/
public function register_gateway($methods) {
$methods[] = $this;
return $methods;
}
protected static function format_msat($msat, $coin) {
return rtrim(rtrim(number_format($msat/100000000, 8), '0'), '.') . ' ' . $coin;
}
}
new WC_Gateway_Lightning();
}
add_action('plugins_loaded', 'init_wc_lightning');
}