public function testcreate_client() { $network = "Testnet"; $private = $this->getMock('Bitpay\\PrivateKey'); $private->expects($this->any())->method('__toString')->will($this->returnValue('3a1cb093db55fc9cc6f2e1efc3938e4e498d8b2557a975249a49e2aec70ad471')); $public = $this->getMock('Bitpay\\PublicKey'); $public->expects($this->any())->method('__toString')->will($this->returnValue('03bb80b4391db1a7ba344fbe5421d87952a4b8934ca0865ae70591d1614e0f6fc8')); $client = create_client($network, $public, $private); $expected_client = new \Bitpay\Client\Client(); $expected_client->setNetwork(new Bitpay\Network\Testnet()); $expected_client->setPublicKey($public); $expected_client->setPrivateKey($private); $expected_client->setAdapter(new Bitpay\Client\Adapter\CurlAdapter()); $this->assertTrue($expected_client == $client); }
function createClient($network, $privateKey = null, $publicKey = null, $curl_options = null) { if (true === is_null($curl_options)) { $curl_options = array(CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => false); } $adapter = new \Bitpay\Client\Adapter\CurlAdapter($curl_options); $client = new \Bitpay\Client\Client(); if (true === !is_null($privateKey)) { $client->setPrivateKey($privateKey); } if (true === !is_null($publicKey)) { $client->setPublicKey($publicKey); } $client->setNetwork($network); $client->setAdapter($adapter); return $client; }
/** * * 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); } }
function ajax_bitpay_pair_code() { $nonce = $_POST['pairNonce']; if (!wp_verify_nonce($nonce, 'bitpay-pair-nonce')) { die('Unauthorized!'); } if (current_user_can('manage_options')) { if (true === isset($_POST['pairing_code']) && trim($_POST['pairing_code']) !== '') { // Validate the Pairing Code $pairing_code = trim($_POST['pairing_code']); } else { wp_send_json_error("Pairing Code is required"); return; } if (!preg_match('/^[a-zA-Z0-9]{7}$/', $pairing_code)) { wp_send_json_error("Invalid Pairing Code"); return; } // Validate the Network $network = $_POST['network'] === 'livenet' ? 'livenet' : 'testnet'; // Generate Private Key $key = new \Bitpay\PrivateKey(); if (true === empty($key)) { throw new \Exception('The Bitpay payment plugin was called to process a pairing code but could not instantiate a PrivateKey object. Cannot continue!'); } $key->generate(); // Generate Public Key $pub = new \Bitpay\PublicKey(); if (true === empty($pub)) { throw new \Exception('The Bitpay payment plugin was called to process a pairing code but could not instantiate a PublicKey object. Cannot continue!'); } $pub->setPrivateKey($key); $pub->generate(); // Get SIN Format $sin = new \Bitpay\SinKey(); if (true === empty($sin)) { throw new \Exception('The Bitpay payment plugin was called to process a pairing code but could not instantiate a SinKey object. Cannot continue!'); } $sin->setPublicKey($pub); $sin->generate(); // Create an API Client $client = new \Bitpay\Client\Client(); if (true === empty($client)) { throw new \Exception('The Bitpay payment plugin was called to process a pairing code but could not instantiate a Client object. Cannot continue!'); } if ($network === 'livenet') { $client->setNetwork(new \Bitpay\Network\Livenet()); } else { $client->setNetwork(new \Bitpay\Network\Testnet()); } $curlAdapter = new \Bitpay\Client\Adapter\CurlAdapter(); if (true === empty($curlAdapter)) { throw new \Exception('The Bitpay payment plugin was called to process a pairing code but could not instantiate a CurlAdapter object. Cannot continue!'); } $client->setAdapter($curlAdapter); $client->setPrivateKey($key); $client->setPublicKey($pub); // Sanitize label $label = preg_replace('/[^a-zA-Z0-9 \\-\\_\\.]/', '', get_bloginfo()); $label = substr('WooCommerce - ' . $label, 0, 59); try { $token = $client->createToken(array('id' => (string) $sin, 'pairingCode' => $pairing_code, 'label' => $label)); } catch (\Exception $e) { wp_send_json_error($e->getMessage()); return; } update_option('woocommerce_bitpay_key', bitpay_encrypt($key)); update_option('woocommerce_bitpay_pub', bitpay_encrypt($pub)); update_option('woocommerce_bitpay_sin', (string) $sin); update_option('woocommerce_bitpay_token', bitpay_encrypt($token)); update_option('woocommerce_bitpay_label', $label); update_option('woocommerce_bitpay_network', $network); wp_send_json(array('sin' => (string) $sin, 'label' => $label, 'network' => $network)); } exit; }
/** * Retrieves a client to interact with BitPay's API * @param string $network Optional network identifier * @return Client */ public function getClient($network = null) { $network = $this->getNetwork($network); $curl_options = array(); if ($network instanceof Bitpay\Network\Customnet) { //Customize the curl options $curl_options = array(CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => false); } $adapter = new Bitpay\Client\Adapter\CurlAdapter($curl_options); $private_key = $this->getPrivateKey(); $public_key = $this->getPublicKey(); $client = new Bitpay\Client\Client(); $client->setPrivateKey($private_key); $client->setPublicKey($public_key); $client->setNetwork($network); $client->setAdapter($adapter); return $client; }
function bitpay_callback() { global $wpdb; try { if (isset($_GET['bitpay_callback'])) { $post = file_get_contents("php://input"); if (true === empty($post)) { return array('error' => 'No post data'); } $json = json_decode($post, true); if (true === is_string($json)) { return array('error' => $json); } if (false === array_key_exists('posData', $json)) { return array('error' => 'no posData'); } if (false === array_key_exists('id', $json)) { return 'Cannot find invoice ID'; } // Don't trust parameters from the scary internet. // Use invoice ID from the $json in getInvoice($invoice_id) and get status from that. $client = new \Bitpay\Client\Client(); $adapter = new \Bitpay\Client\Adapter\CurlAdapter(); $network = strpos($json['url'], 'test') === false ? new \Bitpay\Network\Livenet() : new \Bitpay\Network\Testnet(); $client->setAdapter($adapter); $client->setNetwork($network); // Checking invoice is valid... $response = $client->getInvoice($json['id']); $sessionid = $response->getPosData(); // get buyer email $sql = "SELECT * FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `sessionid`=" . $sessionid; $purchase_log = $wpdb->get_results($sql, ARRAY_A); $email_form_field = $wpdb->get_var("SELECT `id` FROM `" . WPSC_TABLE_CHECKOUT_FORMS . "` WHERE `type` IN ('email') AND `active` = '1' ORDER BY `checkout_order` ASC LIMIT 1"); $email = $wpdb->get_var($wpdb->prepare("SELECT `value` FROM `" . WPSC_TABLE_SUBMITTED_FORM_DATA . "` WHERE `log_id` = %d AND `form_id` = %d LIMIT 1", $purchase_log[0]['id'], $email_form_field)); // get cart contents $sql = "SELECT * FROM `" . WPSC_TABLE_CART_CONTENTS . "` WHERE `purchaseid`=" . $purchase_log[0]['id']; $cart_contents = $wpdb->get_results($sql, ARRAY_A); // get currency symbol $currency_id = get_option('currency_type'); $sql = "SELECT * FROM `" . WPSC_TABLE_CURRENCY_LIST . "` WHERE `id`=" . $currency_id; $currency_data = $wpdb->get_results($sql, ARRAY_A); $currency_symbol = $currency_data[0]['symbol']; // list products and individual prices in the email $message_product = "\r\n\r\nTransaction Details:\r\n\r\n"; $pnp = 0.0; $subtotal = 0.0; foreach ($cart_contents as $product) { // shipping for each item $pnp += $product['pnp']; $message_product .= 'x' . $product['quantity'] . ' ' . $product['name'] . ' - ' . $currency_symbol . $product['price'] * $product['quantity'] . "\r\n"; $subtotal += $product['price'] * $product['quantity']; } //list subtotal $subtotal = number_format($subtotal, 2, '.', ','); $message_product .= "\r\n" . 'Subtotal: ' . $currency_symbol . $subtotal . "\r\n"; //list total taxes and total shipping costs in the email $message_product .= 'Taxes: ' . $currency_symbol . $purchase_log[0]['wpec_taxes_total'] . "\r\n"; $message_product .= 'Shipping: ' . $currency_symbol . ($purchase_log[0]['base_shipping'] + $pnp) . "\r\n\r\n"; //display total price in the email $message_product .= 'Total Price: ' . $currency_symbol . $purchase_log[0]['totalprice']; switch ($response->getStatus()) { //For low and medium transaction speeds, the order status is set to "Order Received" . The customer receives //an initial email stating that the transaction has been paid. case 'paid': if (true === is_numeric($sessionid)) { $sql = "UPDATE `" . WPSC_TABLE_PURCHASE_LOGS . "` SET `processed`= '2' WHERE `sessionid`=" . $sessionid; $wpdb->query($sql); $message = 'Thank you! Your payment has been received, but the transaction has not been confirmed on the bitcoin network. You will receive another email when the transaction has been confirmed.'; $message .= $message_product; $sql = "UPDATE `" . WPSC_TABLE_PURCHASE_LOGS . "` SET `notes`= 'The payment has been received, but the transaction has not been confirmed on the bitcoin network. This will be updated when the transaction has been confirmed.' WHERE `sessionid`=" . $sessionid; $wpdb->query($sql); if (wp_mail($email, 'Payment Received', $message)) { $mail_sql = "UPDATE `" . WPSC_TABLE_PURCHASE_LOGS . "` SET `email_sent`= '1' WHERE `sessionid`=" . $sessionid; $wpdb->query($mail_sql); } transaction_results($sessionid, false); //false because this is just for email notification } break; //For low and medium transaction speeds, the order status will not change. For high transaction speed, the order //status is set to "Order Received" here. For all speeds, an email will be sent stating that the transaction has //been confirmed. //For low and medium transaction speeds, the order status will not change. For high transaction speed, the order //status is set to "Order Received" here. For all speeds, an email will be sent stating that the transaction has //been confirmed. case 'confirmed': if (true === is_numeric($sessionid)) { $sql = "UPDATE `" . WPSC_TABLE_PURCHASE_LOGS . "` SET `processed`= '2' WHERE `sessionid`=" . $sessionid; $wpdb->query($sql); $mail_sql = "UPDATE `" . WPSC_TABLE_PURCHASE_LOGS . "` SET `email_sent`= '1' WHERE `sessionid`=" . $sessionid; //display initial "thank you" if transaction speed is high, as the 'paid' status is skipped on high speed if (get_option('bitpay_transaction_speed') == 'high') { $message = 'Thank you! Your payment has been received, and the transaction has been confirmed on the bitcoin network. You will receive another email when the transaction is complete.'; $message .= $message_product; $sql = "UPDATE `" . WPSC_TABLE_PURCHASE_LOGS . "` SET `notes`= 'The payment has been received, and the transaction has been confirmed on the bitcoin network. This will be updated when the transaction has been completed.' WHERE `sessionid`=" . $sessionid; $wpdb->query($sql); if (wp_mail($email, 'Payment Received', $message)) { $wpdb->query($mail_sql); } } else { $message = 'Your transaction has now been confirmed on the bitcoin network. You will receive another email when the transaction is complete.'; $sql = "UPDATE `" . WPSC_TABLE_PURCHASE_LOGS . "` SET `notes`= 'The payment has been received, and the transaction has been confirmed on the bitcoin network. This will be updated when the transaction has been completed.' WHERE `sessionid`=" . $sessionid; $wpdb->query($sql); if (wp_mail($email, 'Transaction Confirmed', $message)) { $wpdb->query($mail_sql); } } //false because this is just for email notification transaction_results($sessionid, false); } break; //The purchase receipt email is sent upon the invoice status changing to "complete", and the order //status is changed to Accepted Payment //The purchase receipt email is sent upon the invoice status changing to "complete", and the order //status is changed to Accepted Payment case 'complete': if (true === is_numeric($sessionid)) { $sql = "UPDATE `" . WPSC_TABLE_PURCHASE_LOGS . "` SET `processed`= '3' WHERE `sessionid`=" . $sessionid; $wpdb->query($sql); $message = 'Your transaction is now complete! Thank you for using BitPay!'; $sql = "UPDATE `" . WPSC_TABLE_PURCHASE_LOGS . "` SET `notes`= 'The transaction is now complete.' WHERE `sessionid`=" . $sessionid; $wpdb->query($sql); if (wp_mail($email, 'Transaction Complete', $message)) { $mail_sql = "UPDATE `" . WPSC_TABLE_PURCHASE_LOGS . "` SET `email_sent`= '1' WHERE `sessionid`=" . $sessionid; $wpdb->query($mail_sql); } //false because this is just for email notification transaction_results($sessionid, false); } break; // END OF switch ($response->getStatus()) } } } catch (\Exception $e) { debuglog('[Error] In Bitpay plugin, form_bitpay() function on line ' . $e->getLine() . ', with the error "' . $e->getMessage() . '".'); throw $e; } }
/** * 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); $client->setPublicKey($public); $client->setNetwork($network); $client->setAdapter($adapter); $client->createPayout($payout); print_r($payout);
*/ require __DIR__ . '/../../vendor/autoload.php'; /** * To load up keys that you have previously saved, you need to use the same * storage engine. You also need to tell it the location of the key you want * to load. */ $storageEngine = new \Bitpay\Storage\EncryptedFilesystemStorage('YourTopSecretPassword'); $privateKey = $storageEngine->load('/tmp/bitpay.pri'); $publicKey = $storageEngine->load('/tmp/bitpay.pub'); /** * Create the client, there's a lot to it and there are some easier ways, I am * showing the long form here to show how various things are injected into the * client. */ $client = new \Bitpay\Client\Client(); /** * The network is either livenet or testnet. You can also create your * own as long as it implements the NetworkInterface. In this example * we will use testnet */ $network = new \Bitpay\Network\Testnet(); /** * The adapter is what will make the calls to BitPay and return the response * from BitPay. This can be updated or changed as long as it implements the * AdapterInterface */ $adapter = new \Bitpay\Client\Adapter\CurlAdapter(); /** * Now all the objects are created and we can inject them into the client */
<?php /** * Copyright (c) 2014-2015 BitPay */ require __DIR__ . '/../vendor/autoload.php'; $client = new \Bitpay\Client\Client(); $client->setAdapter(new \Bitpay\Client\Adapter\CurlAdapter()); $client->setNetwork(new \Bitpay\Network\Testnet()); $request = new \Bitpay\Client\Request(); $request->setHost('test.bitpay.com'); $request->setMethod(\Bitpay\Client\Request::METHOD_GET); $request->setPath('rates/USD'); $response = $client->sendRequest($request); $data = json_decode($response->getBody(), true); var_dump($data);
* * 003 - Creating Invoices * * Requirements: * - Account on https://test.bitpay.com * - Baisic PHP Knowledge * - Private and Public keys from 001.php * - Token value obtained from 002.php */ require __DIR__ . '/../../vendor/autoload.php'; // See 002.php for explanation $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