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 gateway_bitpay($seperator, $sessionid) { global $wpdb; global $wpsc_cart; try { // Protect your data! $mcrypt_ext = new \Bitpay\Crypto\McryptExtension(); $fingerprint = substr(sha1(sha1(__DIR__)), 0, 24); //Use token that is in_use and with facade = pos for generating invoices $is_a_token_paired = $wpdb->get_var("SELECT COUNT(*) FROM " . $wpdb->prefix . "bitpay_keys WHERE `in_use` = 'true' AND `facade` = 'pos' LIMIT 1"); if ($is_a_token_paired < 1) { debuglog('[Error] In Bitpay plugin, bitpay.merchant.php::gateway_bitpay(): No tokens are paired so no transactions can be done!'); var_dump("Error Processing Transaction. Please try again later. If the problem persists, please contact us at " . get_option('admin_email')); } $row = $wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "bitpay_keys WHERE `in_use` = 'true' AND `facade` = 'pos' LIMIT 1"); $token = unserialize(base64_decode($mcrypt_ext->decrypt($row[0]->token, $fingerprint, '00000000'))); $public_key = unserialize(base64_decode($mcrypt_ext->decrypt($row[0]->public_key, $fingerprint, '00000000'))); $private_key = unserialize(base64_decode($mcrypt_ext->decrypt($row[0]->private_key, $fingerprint, '00000000'))); $network = $row[0]->network === 'Livenet' ? new \Bitpay\Network\Livenet() : new \Bitpay\Network\Testnet(); $row_id = $row[0]->id; $adapter = new \Bitpay\Client\Adapter\CurlAdapter(); // This grabs the purchase log id from // the database that refers to the $sessionid $purchase_log = $wpdb->get_row("SELECT * FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `sessionid`= " . $sessionid . " LIMIT 1", ARRAY_A); // This grabs the users info using the // $purchase_log from the previous SQL query $usersql = "SELECT `" . WPSC_TABLE_SUBMITED_FORM_DATA . "`.value," . "`" . WPSC_TABLE_CHECKOUT_FORMS . "`.`name`," . "`" . WPSC_TABLE_CHECKOUT_FORMS . "`.`unique_name` FROM " . "`" . WPSC_TABLE_CHECKOUT_FORMS . "` LEFT JOIN " . "`" . WPSC_TABLE_SUBMITED_FORM_DATA . "` ON " . "`" . WPSC_TABLE_CHECKOUT_FORMS . "`.id = " . "`" . WPSC_TABLE_SUBMITED_FORM_DATA . "`.`form_id` WHERE " . "`" . WPSC_TABLE_SUBMITED_FORM_DATA . "`.`log_id`='" . $purchase_log['id'] . "'"; $userinfo = $wpdb->get_results($usersql, ARRAY_A); // convert from awkward format $ui = array(); foreach ((array) $userinfo as $value) { if (strlen($value['value'])) { $ui[$value['unique_name']] = $value['value']; } } $userinfo = $ui; /** * Create Buyer object that will be used later. */ $buyer = new \Bitpay\Buyer(); // name if (true === isset($userinfo['billingfirstname'])) { $buyer->setFirstName($userinfo['billingfirstname']); } if (true === isset($userinfo['billinglastname'])) { $buyer->setLastName($userinfo['billinglastname']); } // address -- remove newlines if (true === isset($userinfo['billingaddress'])) { $newline = strpos($userinfo['billingaddress'], "\n"); $address2 = ''; if ($newline !== FALSE) { $address_line1 = substr($userinfo['billingaddress'], 0, $newline); $address_line2 = substr($userinfo['billingaddress'], $newline + 1); $address_line2 = preg_replace('/\\r\\n/', ' ', $address_line2, -1, $count); } else { $address_line1 = $userinfo['billingaddress']; } $buyer->setAddress(array($address_line1, $address_line2)); } // state if (true === isset($userinfo['billingstate'])) { // check if State is a number code used when Selecting country as US if (true === ctype_digit($userinfo['billingstate'])) { $buyer->setState(wpsc_get_state_by_id($userinfo['billingstate'], 'code')); } else { $buyer->setState($userinfo['billingstate']); } } // country if (true === isset($userinfo['billingcountry'])) { $buyer->setCountry($userinfo['billingcountry']); } // city if (true === isset($userinfo['billingcity'])) { $buyer->setCity($userinfo['billingcity']); } // postal code if (true === isset($userinfo['billingpostcode'])) { $buyer->setZip($userinfo['billingpostcode']); } // email if (true === isset($userinfo['billingemail'])) { $buyer->setEmail($userinfo['billingemail']); } // phone if (true === isset($userinfo['billingphone'])) { $buyer->setPhone($userinfo['billingphone']); } // more user info foreach (array('billingphone' => 'buyerPhone', 'billingemail' => 'buyerEmail', 'billingcity' => 'buyerCity', 'billingcountry' => 'buyerCountry', 'billingpostcode' => 'buyerZip') as $f => $t) { if ($userinfo[$f]) { $options[$t] = $userinfo[$f]; } } /** * Create an Item object that will be used later */ $item = new \Bitpay\Item(); // itemDesc, Sku, and Quantity if (count($wpsc_cart->cart_items) == 1) { $item_incart = $wpsc_cart->cart_items[0]; $item_id = $item_incart->product_id; $item_sku = wpsc_product_sku($item_id); $item_description = $item_incart->quantity > 1 ? $item_incart->quantity . ' x ' . $item_incart->product_name : $item_incart->product_name; } else { foreach ($wpsc_cart->cart_items as $item_incart) { $quantity += $item_incart->quantity; $item_id = $item_incart->product_id; $item_sku_individual = wpsc_product_sku($item_id); $item_sku .= $item_incart->quantity . ' x ' . $item_sku_individual . ' '; } $item_description = $quantity . ' items'; } // price $price = number_format($wpsc_cart->total_price, 2, '.', ''); $item->setDescription($item_description)->setCode($item_sku)->setPrice($price); // Create new BitPay invoice $invoice = new \Bitpay\Invoice(); // Add the item to the invoice $invoice->setItem($item); // Add the buyers info to invoice $invoice->setBuyer($buyer); // Configure the rest of the invoice $purchase_log = $wpdb->get_row("SELECT * FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `sessionid`= " . $sessionid . " LIMIT 1", ARRAY_A); $invoice->setOrderId($purchase_log['id'])->setNotificationUrl(get_option('siteurl') . '/?bitpay_callback=true'); /** * 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(); $currencyId = get_option('currency_type'); $currency_code = $wpdb->get_var($wpdb->prepare("SELECT `code` FROM `" . WPSC_TABLE_CURRENCY_LIST . "` WHERE `id` = %d LIMIT 1", $currencyId)); $currency->setCode($currency_code); // Set the invoice currency $invoice->setCurrency($currency); // Transaction Speed $invoice->setTransactionSpeed(get_option('bitpay_transaction_speed')); // Redirect URL $separator = get_option('permalink_structure') != '' ? '?' : '&'; if (true === is_null(get_option('bitpay_redirect'))) { update_option('bitpay_redirect', get_site_url()); } $redirect_url = get_option('bitpay_redirect'); $invoice->setRedirectUrl($redirect_url); // PosData $invoice->setPosData($sessionid); // Full Notifications $invoice->setFullNotifications(true); /** * Create the client that will be used * to send requests to BitPay's API */ $client = new \Bitpay\Client\Client(); $client->setAdapter($adapter); $client->setNetwork($network); $client->setPrivateKey($private_key); $client->setPublicKey($public_key); /** * You will need to set the token that was * returned when you paired your keys. */ $client->setToken($token); $transaction = true; // Send invoice try { $client->createInvoice($invoice); } catch (\Exception $e) { debuglog('[Error] In Bitpay plugin, bitpay.merchant.php::gateway_bitpay(): Call to createInvoice() failed with the message: ' . $e->getMessage()); var_dump("Error Processing Transaction. Please try again later. If the problem persists, please contact us at " . get_option('admin_email')); $transaction = false; } if (true === $transaction) { $sql = "UPDATE `" . WPSC_TABLE_PURCHASE_LOGS . "` SET `notes`= 'The payment has not been received yet.' WHERE `sessionid`=" . $sessionid; $wpdb->query($sql); $wpsc_cart->empty_cart(); unset($_SESSION['WpscGatewayErrorMessage']); header('Location: ' . $invoice->getUrl()); } exit; } 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);