forked from todordev/CrowdFundingPayment-Blockchain
-
Notifications
You must be signed in to change notification settings - Fork 0
/
blockchain.php
391 lines (310 loc) · 14.5 KB
/
blockchain.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
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
<?php
/**
* @package Crowdfunding
* @subpackage Plugins
* @author Todor Iliev
* @copyright Copyright (C) 2015 Todor Iliev <todor@itprism.com>. All rights reserved.
* @license http://www.gnu.org/licenses/gpl-3.0.en.html GNU/GPL
*/
// no direct access
defined('_JEXEC') or die;
jimport("Prism.init");
jimport("Crowdfunding.init");
jimport("EmailTemplates.init");
/**
* Crowdfunding Blockchain payment plugin
*
* @package Crowdfunding
* @subpackage Plugins
*/
class plgCrowdfundingPaymentBlockchain extends Crowdfunding\Payment\Plugin
{
protected $extraDataKeys = array('value', 'input_address', 'confirmations', 'transaction_hash', 'input_transaction_hash', 'destination_address', 'anonymous');
public function __construct(&$subject, $config = array())
{
parent::__construct($subject, $config);
$this->serviceProvider = 'Blockchain';
$this->serviceAlias = 'blockchain';
$this->textPrefix .= '_' . \JString::strtoupper($this->serviceAlias);
$this->debugType .= '_' . \JString::strtoupper($this->serviceAlias);
}
/**
* This method prepare and return address to Blockchain,
* where the user have to go to make a donation.
*
* @param string $context
* @param stdClass $item
*
* @return null|string
*/
public function onProjectPayment($context, &$item)
{
if (strcmp('com_crowdfunding.payment', $context) !== 0) {
return null;
}
if ($this->app->isAdmin()) {
return null;
}
$doc = JFactory::getDocument();
/** @var $doc JDocumentHtml */
// Check document type
$docType = $doc->getType();
if (strcmp('html', $docType) !== 0) {
return null;
}
// This is a URI path to the plugin folder
$pluginURI = 'plugins/crowdfundingpayment/blockchain';
$html = array();
$html[] = '<div class="well">'; // Open "well".
$html[] = '<h4><img src="' . $pluginURI . '/images/blockchain_icon.png" width="38" height="32" /> ' . JText::_($this->textPrefix . '_TITLE') . '</h4>';
// Check for valid data.
$receivingAddress = JString::trim($this->params->get('receiving_address'));
$callbackUrl = $this->getCallbackUrl();
if (!$receivingAddress or !$callbackUrl) {
$html[] = '<div class="bg-warning mtb-10"><span class="glyphicon glyphicon-warning-sign"></span> ' . JText::_($this->textPrefix . '_ERROR_PLUGIN_NOT_CONFIGURED') . '</div>';
$html[] = '</div>'; // Close "well".
return implode("\n", $html);
}
// Get payment session
$paymentSessionContext = Crowdfunding\Constants::PAYMENT_SESSION_CONTEXT . $item->id;
$paymentSessionLocal = $this->app->getUserState($paymentSessionContext);
$paymentSession = $this->getPaymentSession(array(
'session_id' => $paymentSessionLocal->session_id
));
// Prepare transaction ID.
$txnId = Prism\Utilities\StringHelper::generateRandomString();
$txnId = JString::strtoupper($txnId);
// Store the unique key.
$paymentSession->setUniqueKey($txnId);
$paymentSession->storeUniqueKey();
// Prepare callback URL data.
$callbackUrl .= '&payment_session_id='.(int)$paymentSession->getId().'&txn_id='.$txnId;
// DEBUG DATA
JDEBUG ? $this->log->add(JText::_($this->textPrefix . '_DEBUG_CALLBACK_URL'), $this->debugType, $callbackUrl) : null;
// Send request for button
jimport('Prism.libs.Blockchain.Blockchain');
$blockchain = new Blockchain();
$response = $blockchain->Receive->generate($receivingAddress, $callbackUrl);
// DEBUG DATA
$responseResult = @var_export($response, true);
JDEBUG ? $this->log->add(JText::_($this->textPrefix . '_DEBUG_RECEIVE_GENERATE_RESPONSE'), $this->debugType, $responseResult) : null;
// Check for test mode.
if ($this->params->get('test_mode', 1)) {
$html[] = '<div class="bg-info p-10-5"><span class="glyphicon glyphicon-info-sign"></span> ' . JText::_($this->textPrefix . '_ERROR_TEST_MODE') . '</div>';
$html[] = '<label for="blockchain_callback_url">'.JText::_($this->textPrefix . '_CALLBACK_URL').'</label>';
$html[] = '<textarea name="callback_url" id="blockchain_callback_url" class="form-control">'.$callbackUrl.'</textarea>';
} else {
$html[] = '<div class="form-group">';
$html[] = '<label for="blockchain_receiving_address">' . JText::_($this->textPrefix . "_RECEIVING_ADDRESS") . '</label>';
$html[] = '<input class="form-control input-lg" type="text" value="' . $response->address . '" id="blockchain_receiving_address"/>';
$html[] = '</div>';
$html[] = '<p class="bg-info p-10-5 mt-10"><span class="glyphicon glyphicon-info-sign"></span> ' . JText::sprintf($this->textPrefix . '_SEND_COINS_TO_ADDRESS', $item->amountFormated) . '</p>';
$html[] = '<a class="btn btn-primary" href="'.JRoute::_(CrowdfundingHelperRoute::getBackingRoute($item->slug, $item->catslug, 'share')).'"><span class="glyphicon glyphicon-chevron-right"></span> ' . JText::_($this->textPrefix . '_CONTINUE_NEXT_STEP') . '</a>';
}
$html[] = '</div>'; // Close "well".
return implode("\n", $html);
}
/**
* This method processes transaction.
*
* @param string $context This string gives information about that where it has been executed the trigger.
* @param Joomla\Registry\Registry $params The parameters of the component
*
* @return null|array
*/
public function onPaymentNotify($context, &$params)
{
if (strcmp('com_crowdfunding.notify.blockchain', $context) !== 0) {
return null;
}
if ($this->app->isAdmin()) {
return null;
}
$doc = JFactory::getDocument();
/** @var $doc JDocumentHtml */
// Check document type
$docType = $doc->getType();
if (strcmp('raw', $docType) !== 0) {
return null;
}
// DEBUG DATA
JDEBUG ? $this->log->add(JText::_($this->textPrefix . '_DEBUG_RESPONSE'), $this->debugType, $_GET) : null;
$result = array(
'project' => null,
'reward' => null,
'transaction' => null,
'payment_session' => null,
'service_provider' => $this->serviceProvider,
'service_alias' => $this->serviceAlias,
'response' => '' // Response to the payment service.
);
// Get extension parameters
$currencyId = $params->get('project_currency');
$currency = Crowdfunding\Currency::getInstance(JFactory::getDbo(), $currencyId);
// Get payment session data
$paymentSessionId = $this->app->input->get->get('payment_session_id');
$paymentSession = $this->getPaymentSession(array('id' => $paymentSessionId));
// DEBUG DATA
JDEBUG ? $this->log->add(JText::_($this->textPrefix . '_DEBUG_PAYMENT_SESSION'), $this->debugType, $paymentSession->getProperties()) : null;
// Validate transaction data
$validData = $this->validateData($_GET, $currency->getCode(), $paymentSession);
if ($validData === null) {
return $result;
}
// DEBUG DATA
JDEBUG ? $this->log->add(JText::_($this->textPrefix . '_DEBUG_VALID_DATA'), $this->debugType, $validData) : null;
// Get project
$projectId = Joomla\Utilities\ArrayHelper::getValue($validData, 'project_id');
$project = Crowdfunding\Project::getInstance(JFactory::getDbo(), $projectId);
// DEBUG DATA
JDEBUG ? $this->log->add(JText::_($this->textPrefix . '_DEBUG_PROJECT_OBJECT'), $this->debugType, $project->getProperties()) : null;
// Check for valid project
if (!$project->getId()) {
// Log data in the database
$this->log->add(
JText::_($this->textPrefix . '_ERROR_INVALID_PROJECT'),
$this->debugType,
$validData
);
return $result;
}
// Set the receiver of funds
$validData['receiver_id'] = $project->getUserId();
// Save transaction data.
// If it is not completed, return empty results.
// If it is complete, continue with process transaction data
$transactionData = $this->storeTransaction($validData, $project);
if ($transactionData === null) {
return $result;
}
// Update the number of distributed reward.
$rewardId = Joomla\Utilities\ArrayHelper::getValue($transactionData, 'reward_id', 0, 'int');
$reward = null;
if ($rewardId > 0) {
$reward = $this->updateReward($transactionData);
// Validate the reward.
if (!$reward) {
$transactionData['reward_id'] = 0;
}
}
// Prepare the data that will be returned
$result['transaction'] = Joomla\Utilities\ArrayHelper::toObject($transactionData);
// Generate object of data based on the project properties
$properties = $project->getProperties();
$result['project'] = Joomla\Utilities\ArrayHelper::toObject($properties);
// Generate object of data based on the reward properties
if ($reward !== null and ($reward instanceof Crowdfunding\Reward)) {
$properties = $reward->getProperties();
$result['reward'] = Joomla\Utilities\ArrayHelper::toObject($properties);
}
// Generate data object, based on the payment session properties.
$properties = $paymentSession->getProperties();
$result['payment_session'] = Joomla\Utilities\ArrayHelper::toObject($properties);
// DEBUG DATA
JDEBUG ? $this->log->add(JText::_($this->textPrefix . '_DEBUG_RESULT_DATA'), $this->debugType, $result) : null;
// Remove payment session.
$txnStatus = (isset($result['transaction']->txn_status)) ? $result['transaction']->txn_status : null;
$this->closePaymentSession($paymentSession, $txnStatus);
if (strcmp('completed', $result['transaction']->txn_status) === 0) {
$result['response'] = '*ok*';
}
return $result;
}
/**
* Validate transaction data.
*
* @param array $data
* @param string $currency
* @param Crowdfunding\Payment\Session $paymentSession
*
* @return null|array
*/
protected function validateData($data, $currency, $paymentSession)
{
// Get transaction ID.
$txnId = Joomla\Utilities\ArrayHelper::getValue($data, 'txn_id');
// Prepare transaction amount.
$amount = Joomla\Utilities\ArrayHelper::getValue($data, 'value', 0.000, 'float');
$amount /= 100000000;
// Transaction date.
$date = new JDate();
// Get transaction status
$status = 'pending';
$confirmations = Joomla\Utilities\ArrayHelper::getValue($data, 'confirmations', 0, 'int');
if ($confirmations >= 6) {
$status = 'completed';
}
// If the transaction has been made by anonymous user, reset reward. Anonymous users cannot select rewards.
$rewardId = ($paymentSession->isAnonymous()) ? 0 : (int)$paymentSession->getRewardId();
// Get additional information from transaction.
$extraData = $this->prepareExtraData($data);
// Prepare transaction data
$transaction = array(
'investor_id' => (int)$paymentSession->getUserId(),
'project_id' => (int)$paymentSession->getProjectId(),
'reward_id' => (int)$rewardId,
'service_provider' => $this->serviceProvider,
'service_alias' => $this->serviceAlias,
'txn_id' => $txnId,
'txn_amount' => (float)$amount,
'txn_currency' => $currency,
'txn_status' => $status,
'txn_date' => $date->toSql(),
'extra_data' => $extraData
);
// Check User Id, Project ID and Transaction ID
if (!$transaction['txn_amount']) {
// Log data in the database
$this->log->add(
JText::_($this->textPrefix . '_ERROR_INVALID_TRANSACTION_DATA'),
$this->debugType,
$transaction
);
return null;
}
return $transaction;
}
/**
* Save transaction
*
* @param array $transactionData The data about transaction from the payment gateway.
* @param Crowdfunding\Project $project
*
* @return null|array
*/
public function storeTransaction($transactionData, $project)
{
// Get transaction by txn ID
$keys = array(
'txn_id' => Joomla\Utilities\ArrayHelper::getValue($transactionData, 'txn_id')
);
$transaction = new Crowdfunding\Transaction(JFactory::getDbo());
$transaction->load($keys);
// DEBUG DATA
JDEBUG ? $this->log->add(JText::_($this->textPrefix . '_DEBUG_TRANSACTION_OBJECT'), $this->debugType, $transaction->getProperties()) : null;
// Check for existed transaction
// If the current status if completed, stop the process.
if ($transaction->getId() and $transaction->isCompleted()) {
return null;
}
// Store the transaction data
$transaction->bind($transactionData, array('extra_data'));
$transaction->addExtraData($transactionData['extra_data']);
$transaction->store();
// DEBUG DATA
JDEBUG ? $this->log->add(JText::_($this->textPrefix . '_DEBUG_TRANSACTION_OBJECT_AFTER_STORED_DATA'), $this->debugType, $transaction->getProperties()) : null;
// If it is not completed (it might be pending or other status),
// stop the process. Only completed transaction will continue
// and will process the project, rewards,...
if (!$transaction->isCompleted()) {
return null;
}
// Set transaction ID.
$transactionData['id'] = $transaction->getId();
// Update project funded amount
$amount = Joomla\Utilities\ArrayHelper::getValue($transactionData, 'txn_amount');
$project->addFunds($amount);
$project->storeFunds();
return $transactionData;
}
}