public function testGetInvoice() { $response = $this->getMockResponse(); $response->method('getBody')->willReturn(file_get_contents(__DIR__ . '/../../DataFixtures/invoices/5NxFkXcJbCSivtQRJa4kHP.json')); $adapter = $this->getMockAdapter(); $adapter->method('sendRequest')->willReturn($response); $this->client->setAdapter($adapter); $token = new \Bitpay\Token(); $token->setToken('asdfsds'); // No token/public facade $invoice = $this->client->getInvoice('5NxFkXcJbCSivtQRJa4kHP'); $this->assertSame('invoices/5NxFkXcJbCSivtQRJa4kHP', $this->client->getRequest()->getPath()); $this->assertInstanceOf('Bitpay\\InvoiceInterface', $invoice); // pos token/public facade $this->client->setToken($token->setFacade('pos')); $invoice = $this->client->getInvoice('5NxFkXcJbCSivtQRJa4kHP'); $this->assertSame('invoices/5NxFkXcJbCSivtQRJa4kHP', $this->client->getRequest()->getPath()); $this->assertInstanceOf('Bitpay\\InvoiceInterface', $invoice); // merchant token/merchant facade $this->client->setToken($token->setFacade('merchant')); $invoice = $this->client->getInvoice('5NxFkXcJbCSivtQRJa4kHP'); $this->assertSame('invoices/5NxFkXcJbCSivtQRJa4kHP?token=asdfsds', $this->client->getRequest()->getPath()); $this->assertInstanceOf('Bitpay\\InvoiceInterface', $invoice); }
/** * @inheritdoc */ public function getInvoice($invoiceId) { $this->request = $this->createNewRequest(); $this->request->setMethod(Request::METHOD_GET); if ($this->token->getFacade() === 'merchant') { $this->request->setPath(sprintf('invoices/%s?token=%s', $invoiceId, $this->token->getToken())); $this->addIdentityHeader($this->request); $this->addSignatureHeader($this->request); } else { $this->request->setPath(sprintf('invoices/%s', $invoiceId)); } $this->response = $this->sendRequest($this->request); $body = json_decode($this->response->getBody(), true); if (isset($body['error'])) { throw new \Exception($body['error']); } $data = $body['data']; $invoice = new \Bitpay\Invoice(); $invoiceToken = new \Bitpay\Token(); $invoice->setToken($invoiceToken->setToken($data['token']))->setUrl($data['url'])->setPosData($data['posData'])->setStatus($data['status'])->setBtcPrice($data['btcPrice'])->setPrice($data['price'])->setCurrency(new \Bitpay\Currency($data['currency']))->setOrderId($data['orderId'])->setInvoiceTime($data['invoiceTime'] / 1000)->setExpirationTime($data['expirationTime'] / 1000)->setCurrentTime($data['currentTime'] / 1000)->setId($data['id'])->setBtcPaid($data['btcPaid'])->setRate($data['rate'])->setExceptionStatus($data['exceptionStatus']); return $invoice; }
public function getToken() { if (true === empty($this->_autoloaderRegistered)) { $this->registerAutoloader(); } $token = new Bitpay\Token(); if (false === isset($token) || true === empty($token)) { $this->debugData('[ERROR] In Bitpay_Core_Helper_Data::getToken(): could not create new BitPay Token object. Cannot continue!'); throw new \Exception('In Bitpay_Core_Helper_Data::getToken(): could not create new BitPay Token object. Cannot continue!'); } else { $this->debugData('[INFO] In Bitpay_Core_Helper_Data::getToken(): successfully created new BitPay Token object.'); } $token->setToken(\Mage::getStoreConfig('payment/bitpay/token')); return $token; }
/** * @When /^the user creates an invoice for "([^"]*)" "([^"]*)"$/ */ public function theUserCreatesAnInvoiceFor($price, $currency) { try { // Load keys list($privateKey, $publicKey, $token_id) = loadKeys(); $network = $this->network; $client = createClient($network, $privateKey, $publicKey); $token = new \Bitpay\Token(); $token->setToken($token_id); $client->setToken($token); $invoice = new \Bitpay\Invoice(); $item = new \Bitpay\Item(); $item->setCode('skuNumber')->setDescription('General Description of Item')->setPrice($price); $invoice->setItem($item); $invoice->setCurrency(new \Bitpay\Currency($currency)); $client->createInvoice($invoice); $this->response = $client->getResponse(); $body = $this->response->getBody(); $json = json_decode($body, true); $this->invoiceId = $json['data']['id']; } catch (\Exception $e) { $this->error = $e; } finally { return true; } }
/** * * Method used by payment gateway. * * If this method return a \Thelia\Core\HttpFoundation\Response instance, this response is send to the * browser. * * In many cases, it's necessary to send a form to the payment gateway. On your response you can return this form already * completed, ready to be sent * * @param \Thelia\Model\Order $order processed order * @return null|\Thelia\Core\HttpFoundation\Response */ public function pay(Order $order) { $this->loadBitpayKeys(); $client = new \Bitpay\Client\Client(); $adapter = new \Bitpay\Client\Adapter\CurlAdapter(); $config = new BitpayPaymentsConfig(); $config->pushValues(); if ($config->getSandbox()) { $pairingKey = $config->getPairingKeySandbox(); $apiKey = $config->getApiKeySandbox(); $network = new \Bitpay\Network\Testnet(); $environment = "Sandbox"; } else { $pairingKey = $config->getPairingKey(); $apiKey = $config->getApiKey(); $network = new \Bitpay\Network\Livenet(); $environment = "Live"; } $client->setPrivateKey($this->privateKey); $client->setPublicKey($this->publicKey); $client->setNetwork($network); $client->setAdapter($adapter); if (!isset($apiKey) || $apiKey == '') { // must create API key if (!isset($pairingKey) || $pairingKey == '') { // error: no pairing key $error = "Thelia BitpayPayments error: No API key or pairing key for environment {$environment} provided."; Tlog::getInstance()->error($error); throw new \Exception($error); } else { // pairing key available, now trying to get an API key $sin = \Bitpay\SinKey::create()->setPublicKey($this->publicKey)->generate(); try { $token = $client->createToken(array('pairingCode' => $pairingKey, 'label' => 'Thelia BitpayPayments', 'id' => (string) $sin)); } catch (\Exception $e) { $request = $client->getRequest(); $response = $client->getResponse(); $error = 'Thelia BitpayPayments error:' . PHP_EOL . PHP_EOL . $request . PHP_EOL . PHP_EOL . $response . PHP_EOL . PHP_EOL; Tlog::getInstance()->error($error); throw new \Exception($error); } $config->setApiKeyCurrentEnvironment($token->getToken()); $config->setPairingKeyCurrentEnvironment(''); } } // token should be available now $token = new \Bitpay\Token(); $token->setToken($config->getApiKeyCurrentEnvironment()); $client->setToken($token); $invoice = new \Bitpay\Invoice(); $item = new \Bitpay\Item(); $item->setCode('testCode'); $item->setDescription('Purchase'); $item->setPrice($order->getTotalAmount()); $invoice->setItem($item); $invoice->setCurrency(new \Bitpay\Currency($order->getCurrency()->getCode())); try { $client->createInvoice($invoice); } catch (\Exception $e) { $request = $client->getRequest(); $response = $client->getResponse(); $error = 'Thelia BitpayPayments error:' . PHP_EOL . PHP_EOL . $request . PHP_EOL . PHP_EOL . $response . PHP_EOL . PHP_EOL; Tlog::getInstance()->error($error); throw new \Exception($error); } }
/** * Retrieves a BitPay Invoice by ID * @param string $invoice_id * @param string $network Optional network identifier * @return Invoice */ public function getInvoice($invoice_id, $network = null) { $this->log('info', 'Attempting to retrieve invoice for ' . $invoice_id . '...'); $token = new \Bitpay\Token(); $token->setToken($this->setting('token')); $client = $this->getClient($network); $client->setToken($token); return $client->getInvoice($invoice_id); }
if (empty($pairingCode)) { throw new \Exception('Please set a pairing code to a value.'); } $token = $bitpay->get('client')->createToken( array( 'pairingCode' => $pairingCode, 'label' => 'Tutorial 004', 'id' => (string) $sin, ) ); echo 'Token Obtained "'.$token->getToken().'"'.PHP_EOL; //exit(0); */ /** * If you already have a token, uncomment this code * */ $token = new \Bitpay\Token(); $token->setToken($tokenString); /** * Code that makes the invoice */ $invoice = new \Bitpay\Invoice(); $item = new \Bitpay\Item(); $item->setCode('skuNumber')->setDescription('General Description of Item')->setPrice('1.99'); $invoice->setCurrency(new \Bitpay\Currency('USD')); $invoice->setItem($item); $client = $bitpay->get('client'); $client->setToken($token); try { $client->createInvoice($invoice); } catch (\Exception $e) { $request = $client->getRequest();
/** * @inheritdoc */ public function createToken(array $payload = array()) { if (isset($payload['pairingCode']) && 1 !== preg_match('/^[a-zA-Z0-9]{7}$/', $payload['pairingCode'])) { throw new ArgumentException("pairing code is not legal"); } $this->request = $this->createNewRequest(); $this->request->setMethod(Request::METHOD_POST); $this->request->setPath('tokens'); $payload['guid'] = Util::guid(); $this->request->setBody(json_encode($payload)); $this->response = $this->sendRequest($this->request); $body = json_decode($this->response->getBody(), true); if (isset($body['error'])) { throw new \Bitpay\Client\BitpayException($this->response->getStatusCode() . ": " . $body['error']); } $tkn = $body['data'][0]; $createdAt = new \DateTime(); $pairingExpiration = new \DateTime(); $token = new \Bitpay\Token(); $token->setPolicies($tkn['policies'])->setToken($tkn['token'])->setFacade($tkn['facade'])->setCreatedAt($createdAt->setTimestamp(floor($tkn['dateCreated'] / 1000))); if (isset($tkn['resource'])) { $token->setResource($tkn['resource']); } if (isset($tkn['pairingCode'])) { $token->setPairingCode($tkn['pairingCode']); $token->setPairingExpiration($pairingExpiration->setTimestamp(floor($tkn['pairingExpiration'] / 1000))); } return $token; }
<?php /** * Copyright (c) 2014-2015 BitPay */ /** * WARNING - This example will NOT work until you have generated your public * keys and also see the documentation on how to save those keys. * * Also please be aware that you CANNOT create an invoice until you have paired * the keys and received a token back. The token is usesd with the request. */ require __DIR__ . '/../vendor/autoload.php'; $time = gmdate("Y-m-d\\TH:i:s\\.", 1414691179) . "000Z"; $token = new \Bitpay\Token(); $token->setFacade('payroll')->setToken('<your payroll facade-enable token>'); //this is a special api that requires a explicit payroll relationship with BitPay $instruction1 = new \Bitpay\PayoutInstruction(); $instruction1->setAmount(100)->setAddress('2NA5EVH9HHHhM5RxSEWf54gP4v397EmFTxi')->setLabel('Paying Chris'); $payout = new \Bitpay\Payout(); $payout->setEffectiveDate($time)->setAmount(100)->setCurrency(new \Bitpay\Currency('USD'))->setPricingMethod('bitcoinbestbuy')->setReference('a reference, can be json')->setNotificationEmail('*****@*****.**')->setNotificationUrl('https://example.com/ipn.php')->setToken($token)->addInstruction($instruction1); $private = new \Bitpay\PrivateKey(); $private->setHex('662be90968bc659873d723374213fa5bf7a30c24f0f0713aa798eb7daa7230fc'); //this is your private key in some form (see GetKeys.php) $public = new \Bitpay\PublicKey(); $public->generate($private); $network = new \Bitpay\Network\Testnet(); $adapter = new \Bitpay\Client\Adapter\CurlAdapter(); $bitpay = new \Bitpay\Bitpay(); $client = new \Bitpay\Client\Client(); $client->setPrivateKey($private);
// Add the buyers info to invoice $invoice->setBuyer($buyer); // Configure the rest of the invoice $invoice->setOrderId('OrderIdFromYourSystem')->setNotificationUrl('https://store.example.com/bitpay/callback'); /** * BitPay offers services for many different currencies. You will need to * configure the currency in which you are selling products with. */ $currency = new \Bitpay\Currency(); $currency->setCode('USD'); // Set the invoice currency $invoice->setCurrency($currency); /** * Create a new client. You can see the example of how to configure this using * a yml file as well. */ $bitpay = new \Bitpay\Bitpay(array('bitpay' => array('network' => 'testnet', 'public_key' => getenv('HOME') . '/.bitpay/api.pub', 'private_key' => getenv('HOME') . '/.bitpay/api.key', 'key_storage' => 'Bitpay\\Storage\\EncryptedFilesystemStorage', 'key_storage_password' => 'TopSecret'))); /** * Create the client that will be used to send requests to BitPay's API */ $client = $bitpay->get('client'); /** * You will need to set the token that was returned when you paired your * keys. */ $token = new \Bitpay\Token(); $token->setToken('Put your token here'); $client->setToken($token); // Send invoice $client->createInvoice($invoice); var_dump((string) $client->getRequest(), (string) $client->getResponse(), $invoice);
<?php /** * Copyright (c) 2014-2015 BitPay */ /** * WARNING - This example will NOT work until you have generated your public * and private keys. Please see the example documentation on generating your * keys and also see the documentation on how to save those keys. * * Also please be aware that you CANNOT create an invoice until you have paired * the keys and received a token back. The token is usesd with the request. */ require __DIR__ . '/../vendor/autoload.php'; $time = gmdate("Y-m-d\\TH:i:s\\.", 1414691179) . "000Z"; $token = new \Bitpay\Token(); $token->setFacade('payroll')->setToken('your token here'); $instruction1 = new \Bitpay\PayoutInstruction(); $instruction1->setAmount(990)->setAddress('n3Sx4askJeykUYk24sS5rQoCEm8BpwVrNg')->setLabel('Paying Tom'); $instruction2 = new \Bitpay\PayoutInstruction(); $instruction2->setAmount(1490)->setAddress('mxRN6AQJaDi5R6KmvMaEmZGe3n5ScV9u33')->setLabel('Paying Harry'); $payout = new \Bitpay\Payout(); $payout->setEffectiveDate($time)->setCurrency(new \Bitpay\Currency('USD'))->setPricingMethod('bitcoinbestbuy')->setReference('a reference, can be json')->setNotificationEmail('*****@*****.**')->setNotificationUrl('https://yoursite.com/callback')->setToken($token)->addInstruction($instruction1)->addInstruction($instruction2); /** * Create a new client. You can see the example of how to configure this using * a yml file as well. */ $bitpay = new \Bitpay\Bitpay(array('bitpay' => array('network' => 'testnet', 'public_key' => getenv('HOME') . '/.bitpayphp/api.pub', 'private_key' => getenv('HOME') . '/.bitpayphp/api.key', 'key_storage' => 'Bitpay\\Storage\\FilesystemStorage'))); /** * Create the client that will be used to send requests to BitPay's API */
$storageEngine = new \Bitpay\Storage\EncryptedFilesystemStorage('YourTopSecretPassword'); // Password may need to be updated if you changed it $privateKey = $storageEngine->load('/tmp/bitpay.pri'); $publicKey = $storageEngine->load('/tmp/bitpay.pub'); $client = new \Bitpay\Client\Client(); $network = new \Bitpay\Network\Testnet(); $adapter = new \Bitpay\Client\Adapter\CurlAdapter(); $client->setPrivateKey($privateKey); $client->setPublicKey($publicKey); $client->setNetwork($network); $client->setAdapter($adapter); // --------------------------- /** * The last object that must be injected is the token object. */ $token = new \Bitpay\Token(); $token->setToken('UpdateThisValue'); // UPDATE THIS VALUE /** * Token object is injected into the client */ $client->setToken($token); /** * This is where we will start to create an Invoice object, make sure to check * the InvoiceInterface for methods that you can use. */ $invoice = new \Bitpay\Invoice(); /** * Item is used to keep track of a few things */ $item = new \Bitpay\Item();