/** * Submit a payment using Advanced Integration Method * * @param array $params assoc array of input parameters for this transaction * * @return array the result in a nice formatted array (or an error object) * @public */ function doDirectPayment(&$params) { $requestArray = $this->formRequestArray($params); $result = Braintree_Transaction::sale($requestArray); if ($result->success) { $params['trxn_id'] = $result->transaction->id; $params['gross_amount'] = $result->transaction->amount; } else { if ($result->transaction) { $errormsg = 'Transactions is not approved'; return self::error($result->transaction->processorResponseCode, $result->message); } else { $error = "Validation errors:<br/>"; foreach ($result->errors->deepAll() as $e) { $error .= $e->message; } return self::error(9001, $error); } } return $params; }
public function send() { $this->load->model('checkout/order'); $order_info = $this->model_checkout_order->getOrder($this->session->data['order_id']); $amount = $this->currency->format($order_info['total'], $order_info['currency_code'], 1.0, false); //Load Braintree Library require_once './vendor/braintree/braintree_php/lib/Braintree.php'; Braintree_Configuration::environment($this->config->get('simple_braintree_payments_mode')); Braintree_Configuration::merchantId($this->config->get('simple_braintree_payments_merchant')); Braintree_Configuration::publicKey($this->config->get('simple_braintree_payments_public_key')); Braintree_Configuration::privateKey($this->config->get('simple_braintree_payments_private_key')); // Payment nonce received from the client js side $nonce = $_POST["payment_method_nonce"]; //create object to use as json $json = array(); $result = null; try { // Perform the transaction $result = Braintree_Transaction::sale(array('amount' => $amount, 'paymentMethodNonce' => $nonce, 'orderId' => $this->session->data['order_id'])); } catch (Exception $e) { $json['phperror'] = $e->getMessage(); } $json['details'] = $result; if ($result->success) { $this->model_checkout_order->confirm($this->session->data['order_id'], $this->config->get('simple_braintree_payments_order_status_id')); $json['success'] = $this->url->link('checkout/success', '', 'SSL'); } else { $json['error'] = $result->_attributes['message']; } $this->response->setOutput(json_encode($json)); }
function braintree($data) { foreach ($data as $k => $v) { ${$k} = $v; } try { include_once 'config.braintree.php'; $customer = Braintree_Customer::create(['firstName' => $first_name, 'lastName' => $last_name]); if (!isset($nonce) || empty($nonce)) { throw new Exception("An unknown error has occurred"); } if ($customer->success) { $transaction = Braintree_Transaction::sale(['amount' => $price, 'customerId' => $customer->customer->id, 'paymentMethodNonce' => $nonce]); if ($transaction->success) { $this->save($data, __FUNCTION__, $transaction->transaction, 1); return json_encode(["status" => true, "msg" => sprintf("Your payment has been %s", $transaction->transaction->status)]); } else { throw new Exception($transaction->message); } } } catch (Exception $e) { $this->save($data, __FUNCTION__, (string) $e, 0); return json_encode(["status" => false, "msg" => $e->getMessage()]); } }
public function directpay($var = array()) { $payment = array("amount" => $var['postVal']['amount'], "creditCard" => array("number" => $var['postVal']['ccNum'], "cvv" => $var['postVal']['ccCCV'], "cardholderName" => $var['postVal']['ccHolder'], "expirationMonth" => $var['postVal']['ccExpMM'], "expirationYear" => $var['postVal']['ccExpYY']), "merchantAccountId" => $var['postVal']['cur'], "options" => array("submitForSettlement" => true)); $sale = Braintree_Transaction::sale($payment); $result = array(); if ($sale->success) { $result['status'] = "200"; $result['detail']['id'] = $sale->transaction->id; $result['detail']['sales_id'] = $sale->transaction->id; $result['detail']['state'] = $sale->transaction->status; $result['detail']['create_time'] = $sale->transaction->createdAt->format("Y-m-d H:i:s"); $result['detail']['update_time'] = $sale->transaction->updatedAt->format("Y-m-d H:i:s"); $result['detail']['currency'] = $sale->transaction->currencyIsoCode; $result['detail']['amount'] = $sale->transaction->amount; $result['detail']['gateway'] = "Braintree"; } else { if ($sale->transaction) { $result['status'] = $sale->transaction->processorResponseCode; $result['errMsg'] = $sale->message; } else { $result['status'] = "400"; $errMsg = ""; foreach ($sale->errors->deepAll() as $error) { $errMsg .= "- " . $error->message . "<br/>"; } $result['errMsg'] = $errMsg; } } return $result; }
function donate($nonce, $info) { $result = Braintree_Transaction::sale(['amount' => $info['amount'], 'paymentMethodNonce' => $nonce, 'options' => ['submitForSettlement' => True]]); if (!isset($result->transaction) || !$result->transaction) { return $this->processErrors('donation', $result->errors->deepAll()); } return $this->retrieveTransactioResults($result->success, $result->transaction, $info); }
function braintreepay(){ $nonce = $_POST["payment_method_nonce"]; $amount = $_POST["amount"]; $result = Braintree_Transaction::sale([ 'amount'=>''.$amount, 'paymentMethodNonce' => 'fake-valid-nonce' ]); echo $result->success; }
private function _sale($postFormData, $nonce) { $amount = $postFormData['Order']['amount']; $currencyModelObj = ClassRegistry::init('Currency'); $currency = $currencyModelObj->getCurrencyByAbbreviation($postFormData['Order']['currency_abbr']); $convertedAmount = (double) round($amount / $currency['Currency']['rate'], 2); $sale = Braintree_Transaction::sale(['amount' => $convertedAmount, 'paymentMethodNonce' => $nonce]); return $sale; }
public function pay($data) { global $_SESSION; $this->debug($_SESSION); $billingAddress = $this->getAddress($data['billingAddress'], true)[0]; $shippingAddress = $this->getAddress($data['shippingAddress'], true)[0]; $sale = Braintree_Transaction::sale(['amount' => '10.00', 'paymentMethodNonce' => $data['payment_method_nonce'], 'shipping' => ['firstName' => $shippingAddress['address_first_name'], 'lastName' => $shippingAddress['address_last_name'], 'company' => $shippingAddress['address_company_name'], 'streetAddress' => $shippingAddress['address_street'], 'extendedAddress' => $shippingAddress['address_apartment'], 'locality' => $shippingAddress['address_city'], 'region' => $shippingAddress['address_county'], 'postalCode' => $shippingAddress['address_postcode'], 'countryCodeAlpha2' => $shippingAddress['address_country']], 'billing' => ['firstName' => $billingAddress['address_first_name'], 'lastName' => $billingAddress['address_last_name'], 'company' => $billingAddress['address_company_name'], 'streetAddress' => $billingAddress['address_street'], 'extendedAddress' => $billingAddress['address_apartment'], 'locality' => $billingAddress['address_city'], 'region' => $billingAddress['address_county'], 'postalCode' => $billingAddress['address_postcode'], 'countryCodeAlpha2' => $billingAddress['address_country']], 'options' => ['submitForSettlement' => true]]); return $sale; }
/** * Authorizes specified amount * * @param Varien_Object $payment * @param decimal $amount * @param boolean $capture * @return Braintree_Payments_Model_Paymentmethod */ protected function _authorize(Varien_Object $payment, $amount, $capture, $token = false) { try { $order = $payment->getOrder(); $orderId = $order->getIncrementId(); $billing = $order->getBillingAddress(); $shipping = $order->getShippingAddress(); $transactionParams = array('channel' => $this->_getChannel(), 'orderId' => $orderId, 'amount' => $amount, 'customer' => array('firstName' => $billing->getFirstname(), 'lastName' => $billing->getLastname(), 'company' => $billing->getCompany(), 'phone' => $billing->getTelephone(), 'fax' => $billing->getFax(), 'email' => $order->getCustomerEmail())); $customerId = Mage::helper('braintree_payments')->generateCustomerId($order->getCustomerId(), $order->getCustomerEmail()); if ($order->getCustomerId() && $this->exists($customerId)) { $transactionParams['customerId'] = $customerId; unset($transactionParams['customer']); } else { $transactionParams['customer']['id'] = $customerId; } if ($capture) { $transactionParams['options']['submitForSettlement'] = true; } if ($this->_merchantAccountId) { $transactionParams['merchantAccountId'] = $this->_merchantAccountId; } $token = $this->_getMethodSpecificAuthorizeTransactionToken($token); if ($token) { $nonce = Mage::helper('braintree_payments')->getNonceForVaultedToken($token); $transactionParams['customerId'] = $customerId; } else { $transactionParams['billing'] = $this->_toBraintreeAddress($billing); $transactionParams['shipping'] = $this->_toBraintreeAddress($shipping); $transactionParams['options']['addBillingAddressToPaymentMethod'] = true; $nonce = $payment->getAdditionalInformation('nonce'); } $transactionParams['paymentMethodNonce'] = $nonce; $transactionParams = array_merge_recursive($transactionParams, $this->_addMethodSpecificAuthorizeTransactionParams($payment)); if (isset($transactionParams['options']['storeInVault']) && !$transactionParams['options']['storeInVault']) { $transactionParams['options']['addBillingAddressToPaymentMethod'] = false; } $this->_debug($transactionParams); try { $result = Braintree_Transaction::sale($transactionParams); $this->_debug($result); } catch (Exception $e) { Mage::logException($e); Mage::throwException(Mage::helper('braintree_payments')->__('Please try again later')); } if ($result->success) { $this->setStore($payment->getOrder()->getStoreId()); $payment = $this->_processSuccessResult($payment, $result, $amount); } else { Mage::throwException(Mage::helper('braintree_payments/error')->parseBraintreeError($result)); } } catch (Exception $e) { $this->_processMethodSpecificAuthorizeTransactionError(); throw new Mage_Payment_Model_Info_Exception($e->getMessage()); } return $this; }
function quick_transaction($cust_id, $token, $amount) { $result = Braintree_Transaction::sale(array('amount' => $amount, 'customerId' => $cust_id, 'paymentMethodToken' => $token)); if ($result->success) { $this->_log_transaction($result->transaction); return true; } // func still running means errors! $this->_parse_errors($result); return false; }
public function createTransaction($data) { Braintree_Configuration::environment($this->config->item('braintree_environment')); Braintree_Configuration::merchantId($this->config->item('braintree_merchant_id')); Braintree_Configuration::publicKey($this->config->item('braintree_public_key')); Braintree_Configuration::privateKey($this->config->item('braintree_private_key')); $transaction = Braintree_Transaction::sale($data); if ($transaction) { return $transaction; } else { return false; } }
function charge(&$order) { //create a code for the order if (empty($order->code)) { $order->code = $order->getRandomCode(); } //what amount to charge? $amount = $order->InitialPayment; //tax $order->subtotal = $amount; $tax = $order->getTax(true); $amount = round((double) $order->subtotal + (double) $tax, 2); //create a customer $this->getCustomer($order); if (empty($this->customer)) { //failed to create customer return false; } //charge try { $response = Braintree_Transaction::sale(array('amount' => $amount, 'customerId' => $this->customer->id)); } catch (Exception $e) { //$order->status = "error"; $order->errorcode = true; $order->error = "Error: " . $e->getMessage(); $order->shorterror = $order->error; return false; } if ($response->success) { //successful charge $transaction_id = $response->transaction->id; $response = Braintree_Transaction::submitForSettlement($transaction_id); if ($response->success) { $order->payment_transaction_id = $transaction_id; $order->updateStatus("success"); return true; } else { $order->errorcode = true; $order->error = __("Error during settlement:", "pmpro") . " " . $response->message; $order->shorterror = $response->message; return false; } } else { //$order->status = "error"; $order->errorcode = true; $order->error = __("Error during charge:", "pmpro") . " " . $response->message; $order->shorterror = $response->message; return false; } }
/** * Braintree sale function * @param bool|true $submitForSettlement * @param bool|true $storeInVaultOnSuccess * @return array */ public function singleCharge($submitForSettlement = true, $storeInVaultOnSuccess = true) { $this->options['options']['submitForSettlement'] = $submitForSettlement; $this->options['options']['storeInVaultOnSuccess'] = $storeInVaultOnSuccess; $result = \Braintree_Transaction::sale($this->options); if ($result->success) { return ['status' => true, 'result' => $result]; } else { if ($result->transaction) { return ['status' => false, 'result' => $result]; } else { return ['status' => false, 'result' => $result]; } } }
/** * After form has been submitted, send CC details to Braintree and ensure the card is going to work * If not, void the validation result (processed elsewhere) and have the submit the form again * * @param $feed - Current configured payment feed * @param $submission_data - Contains form field data submitted by the user as well as payment information (i.e. payment amount, setup fee, line items, etc...) * @param $form - Current form array containing all form settings * @param $entry - Current entry array containing entry information (i.e data submitted by users). NOTE: the entry hasn't been saved to the database at this point, so this $entry object does not have the "ID" property and is only a memory representation of the entry. * @return array - Return an $authorization array in the following format: * [ * "is_authorized" => true|false, * "error_message" => "Error message", * "transaction_id" => "XXX", * * //If the payment is captured in this method, return a "captured_payment" array with the following information about the payment * "captured_payment" => ["is_success"=>true|false, "error_message" => "error message", "transaction_id" => "xxx", "amount" => 20] * ] * @since 1.0 * @return void */ protected function authorize($feed, $submission_data, $form, $entry) { // Prepare authorization response payload $authorization = array('is_authorized' => false, 'error_message' => apply_filters('gform_braintree_credit_card_failure_message', __('Your card could not be billed. Please ensure the details you entered are correct and try again.', 'gravity-forms-braintree')), 'transaction_id' => '', 'captured_payment' => array('is_success' => false, 'error_message' => '', 'transaction_id' => '', 'amount' => $submission_data['payment_amount'])); // Perform capture in this function. For this version, we won't authorize and then capture later // at least, not in this version if ($settings = $this->get_plugin_settings()) { // Sanitize card number, removing dashes and spaces $card_number = str_replace(array('-', ' '), '', $submission_data['card_number']); // Prepare Braintree payload $args = array('amount' => $submission_data['payment_amount'], 'creditCard' => array('number' => $card_number, 'expirationDate' => sprintf('%s/%s', $submission_data['card_expiration_date'][0], $submission_data['card_expiration_date'][1]), 'cardholderName' => $submission_data['card_name'], 'cvv' => $submission_data['card_security_code'])); try { // Configure Braintree environment Braintree_Configuration::environment(strtolower($settings['environment'])); Braintree_Configuration::merchantId($settings['merchant-id']); Braintree_Configuration::publicKey($settings['public-key']); Braintree_Configuration::privateKey($settings['private-key']); // Set to auto settlemt if applicable if ($settings['settlement'] == 'Yes') { $args['options']['submitForSettlement'] = 'true'; } // Send transaction to Braintree $result = Braintree_Transaction::sale($args); // Update response to reflect successful payment if ($result->success == '1') { $authorization['is_authorized'] = true; $authorization['error_message'] = ''; $authorization['transaction_id'] = $result->transaction->_attributes['id']; $authorization['captured_payment'] = array('is_success' => true, 'transaction_id' => $result->transaction->_attributes['id'], 'amount' => $result->transaction->_attributes['amount'], 'error_message' => '', 'payment_method' => 'Credit Card'); } else { // Append gateway response text to error message if it exists. If it doesn't exist, a more hardcore // failure has occured and it won't do the user any good to see it other than a general error message if (isset($result->_attributes['transaction']->_attributes['processorResponseText'])) { $authorization['error_message'] .= sprintf('. Your bank said: %s.', $result->_attributes['transaction']->_attributes['processorResponseText']); } } } catch (Exception $e) { // Do nothing with exception object, just fallback to generic failure } return $authorization; } return false; }
/** * Purchase * @param $payment * @param $device_data * @return Braintree_Result_Successful */ public function purchase($payment, $device_data) { $this->payment_data = ['amount' => (string) $payment['amount'], 'merchantAccountId' => $payment['merchantAccountId'], 'orderId' => $payment['orderId'], 'paymentMethodNonce' => $payment['payment_nonce'], 'customer' => $payment['customer'], 'shipping' => $payment['shipping'], 'billing' => $payment['billing'], 'options' => $payment['options'], 'deviceData' => $device_data]; /** * Custom fields */ if (!empty($payment['party_id'])) { $this->payment_data['customFields'] = ['party_id' => $payment['party_id']]; } /** * 5 digit zip code for US */ if ($this->payment_data['billing']['countryCodeAlpha2'] == 'us' && strpos($this->payment_data['billing']['postalCode'], '-')) { $zip = explode('-', $this->payment_data['billing']['postalCode']); $this->payment_data['billing']['postalCode'] = $zip[0]; } if ($this->payment_data['shipping']['countryCodeAlpha2'] == 'us' && strpos($this->payment_data['shipping']['postalCode'], '-')) { $s_zip = explode('-', $this->payment_data['shipping']['postalCode']); $this->payment_data['shipping']['postalCode'] = $s_zip[0]; } return Braintree_Transaction::sale($this->payment_data); }
public function __construct($config, $price = 0) { // DO NOT store .ini files in public web root! to bypass figuring that out (if you're hella lazy) // remove $config as a parameter and hardcode your values into this short section $parsed = parse_ini_file($config, TRUE); Braintree_Configuration::environment($parsed['environment']); Braintree_Configuration::merchantId($parsed['merchantId']); Braintree_Configuration::publicKey($parsed['publicKey']); Braintree_Configuration::privateKey($parsed['privateKey']); if ($price > 0) { // angular doesnt like php's $_POST something something // http://stackoverflow.com/questions/19254029/angularjs-http-post-does-not-send-data $post_inputs = json_decode(file_get_contents('php://input'), true); $result = Braintree_Transaction::sale(array('amount' => $price, 'paymentMethodNonce' => $post_inputs['nonce'], 'customer' => ['firstName' => $post_inputs['first_name'], 'lastName' => $post_inputs['last_name'], 'email' => $post_inputs['email'], 'company' => $post_inputs['company']], 'creditCard' => ['cardholderName' => $post_inputs['cardholderName'], 'cvv' => $post_inputs['cvv'], 'expirationDate' => $post_inputs['expirationDate']], 'orderId' => $post_inputs['orderId'], 'options' => ['submitForSettlement' => True])); if ($result->success) { $response['success'] = true; $response['message'] = "Success"; $response['id'] = $result->transaction->id; } else { if ($result->transaction) { $response['success'] = false; $response['message'] = "Error processing transaction"; $response['code'] = $result->transaction->processorResponseCode; $response['text'] = $result->transaction->processorResponseText; } else { $response['success'] = false; $response['message'] = "Validation errors"; $response['errors'] = $result->errors->deepAll(); } } $this->response = json_encode($response); } else { // price not provided, create client token $this->client_token = Braintree_ClientToken::generate(); } }
function test_rangeNode_canSearchOnMulitpleStatuses() { $transaction = Braintree_Transaction::sale(array('amount' => '1000.00', 'creditCard' => array('number' => '4111111111111111', 'expirationDate' => '05/12'), 'options' => array('submitForSettlement' => true)))->transaction; $twenty_min_ago = date_create("now -20 minutes", new DateTimeZone("UTC")); $ten_min_ago = date_create("now -10 minutes", new DateTimeZone("UTC")); $ten_min_from_now = date_create("now +10 minutes", new DateTimeZone("UTC")); $collection = Braintree_Transaction::search(array(Braintree_TransactionSearch::id()->is($transaction->id), Braintree_TransactionSearch::authorizedAt()->between($twenty_min_ago, $ten_min_ago), Braintree_TransactionSearch::submittedForSettlementAt()->between($twenty_min_ago, $ten_min_ago))); $this->assertEquals(0, $collection->maximumCount()); $collection = Braintree_Transaction::search(array(Braintree_TransactionSearch::id()->is($transaction->id), Braintree_TransactionSearch::authorizedAt()->between($ten_min_ago, $ten_min_from_now), Braintree_TransactionSearch::submittedForSettlementAt()->between($ten_min_ago, $ten_min_from_now))); $this->assertEquals(1, $collection->maximumCount()); $this->assertEquals($transaction->id, $collection->firstItem()->id); }
public static function processPayment() { require_once osc_plugins_path() . osc_plugin_folder(__FILE__) . 'lib/Braintree.php'; Braintree_Configuration::environment(osc_get_preference('braintree_sandbox', 'payment')); Braintree_Configuration::merchantId(payment_decrypt(osc_get_preference('braintree_merchant_id', 'payment'))); Braintree_Configuration::publicKey(payment_decrypt(osc_get_preference('braintree_public_key', 'payment'))); Braintree_Configuration::privateKey(payment_decrypt(osc_get_preference('braintree_private_key', 'payment'))); $data = payment_get_custom(Params::getParam('extra')); $tmp = explode('x', $data['product']); if (count($tmp) > 1) { $amount = $tmp[1]; } else { return PAYMENT_FAILED; } $result = Braintree_Transaction::sale(array('amount' => $amount, 'creditCard' => array('number' => Params::getParam('braintree_number'), 'cvv' => Params::getParam('braintree_cvv'), 'expirationMonth' => Params::getParam('braintree_month'), 'expirationYear' => Params::getParam('braintree_year')), 'options' => array('submitForSettlement' => true))); print_r($result); if ($result->success == 1) { Params::setParam('braintree_transaction_id', $result->transaction->id); $exists = ModelPayment::newInstance()->getPaymentByCode($result->transaction->id, 'BRAINTREE'); if (isset($exists['pk_i_id'])) { return PAYMENT_ALREADY_PAID; } $product_type = explode('x', $data['product']); // SAVE TRANSACTION LOG $payment_id = ModelPayment::newInstance()->saveLog($data['concept'], $result->transaction->id, $result->transaction->amount, $result->transaction->currencyIsoCode, $data['email'], $data['user'], $data['itemid'], $product_type[0], 'BRAINTREE'); //source if ($product_type[0] == '101') { ModelPayment::newInstance()->payPublishFee($product_type[2], $payment_id); } else { if ($product_type[0] == '201') { ModelPayment::newInstance()->payPremiumFee($product_type[2], $payment_id); } else { ModelPayment::newInstance()->addWallet($data['user'], $result->transaction->amount); } } return PAYMENT_COMPLETED; } else { return PAYMENT_FAILED; } }
public function doBraintreePayment() { if (Input::get('payment_method_nonce')) { $result = Braintree_Transaction::sale(array('amount' => '10.00', 'paymentMethodNonce' => Input::get('payment_method_nonce'))); return View::make('dev.braintree', array('result' => $result)); } }
function submitTransaction($request) { return Braintree_Transaction::sale($request); }
public function sale($array = []) { if (empty($array)) { throw new Exception(__('Transaction information missing. Please see the documentation')); } if (!isset($array['merchantAccountId']) && $this->merchantAccountId) { $array['merchantAccountId'] = $this->merchantAccountId; } return Braintree_Transaction::sale($array); }
public function add_payment($billing_payment_id, $amount, $token) { $result = Braintree_Transaction::sale(['orderId' => $billing_payment_id, 'amount' => $amount, 'paymentMethodToken' => $token, 'options' => ['submitForSettlement' => True]]); return $result; }
/** * create a new sale for the current card * * @param string $token * @param array $transactionAttribs * @return object Braintree_Result_Successful or Braintree_Result_Error * @see Braintree_Transaction::sale() */ public static function sale($token, $transactionAttribs) { self::_validateId($token); return Braintree_Transaction::sale(array_merge($transactionAttribs, array('paymentMethodToken' => $token))); }
/** * create a new sale for a customer * * @param string $customerId * @param array $transactionAttribs * @return object Braintree_Result_Successful or Braintree_Result_Error * @see Braintree_Transaction::sale() */ public function sale($customerId, $transactionAttribs) { $this->_validateId($customerId); return Braintree_Transaction::sale(array_merge($transactionAttribs, array('customerId' => $customerId))); }
public function braintree_success() { $result = Braintree_Transaction::sale(array('amount' => get_currency_value_lys(get_currency_code(), 'USD', $this->session->userdata('list_commission')), "paymentMethodNonce" => $_POST['payment_method_nonce'], 'options' => array('submitForSettlement' => true))); $transaction = $result->transaction; /* if($result->success == 1) { if($result->message == "Amount must be greater than zero.") { $this->session->set_flashdata('flash_message', $this->Common_model->flash_message('error',$result->message)); redirect('rooms/'.$this->input->post('custom',true), "refresh"); } */ if (!$this->dx_auth->is_logged_in() || !$this->facebook_lib->logged_in()) { //$this->session->set_flashdata('flash_message', $this->Common_model->flash_message('error',translate('Session expired, please try again.'))); //redirect('users/signin'); } if ($transaction->status == "authorized" || $transaction->status == "submitted_for_settlement") { $listId = $this->input->post('custom', true); $condition = array('id' => $listId); $data['status'] = 1; $data['list_pay'] = 1; $data['is_enable'] = 1; $data['payment'] = 1; $this->Common_model->updateTableData('list', NULL, $condition, $data); if (!$this->dx_auth->is_logged_in() || !$this->facebook_lib->logged_in()) { //$this->session->set_flashdata('flash_message', $this->Common_model->flash_message('error',translate('Session expired, please try again.'))); //redirect('users/signin'); } $query_user = $this->Common_model->getTableData('users', array('id' => $this->dx_auth->get_user_id()))->row(); $username = $query_user->username; $insertData = array('list_id' => $listId, 'conversation_id' => $listId, 'userby' => $this->dx_auth->get_user_id(), 'userto' => 1, 'message' => "{$username} created a new list.", 'created' => time(), 'message_type ' => 10); $this->Message_model->sentMessage($insertData); $host_email = $query_user->email; $admin_email = $this->dx_auth->get_site_sadmin(); $admin_name = $this->dx_auth->get_site_title(); $admin_to_email = $this->Common_model->getTableData('users', array('id' => 1))->row()->email; $query_list = $this->Common_model->getTableData('list', array('id' => $listId))->row(); $currency = $query_list->currency; $price = $query_list->price; $title = $query_list->title; $link = base_url() . 'rooms/' . $listId; $email_name = 'list_create_host'; $splVars = array("{host_name}" => $username, "{price}" => $currency . $price, "{link}" => $link, "{list_title}" => $title, "{site_name}" => $this->dx_auth->get_site_title()); $this->Email_model->sendMail($host_email, $admin_email, ucfirst($admin_name), $email_name, $splVars); $email_name = 'list_create_admin'; $splVars = array("{host_name}" => $username, "{price}" => $currency . $price, "{link}" => $link, "{list_title}" => $title, "{site_name}" => $this->dx_auth->get_site_title()); $this->Email_model->sendMail($admin_to_email, $admin_email, ucfirst($admin_name), $email_name, $splVars); $data_listpay['list_id'] = $listId; $data_listpay['amount'] = $this->session->userdata('list_commission'); $data_listpay['currency'] = get_currency_code(); $data_listpay['created'] = time(); $this->db->insert('list_pay', $data_listpay); $data['title'] = "Payment Success !"; $data['message_element'] = "payments/paypal_success"; $this->load->view('template', $data); //redirect('rooms/edit/'.$listId, 'refresh'); //$this->session->set_flashdata('flash_message', $this->Common_model->flash_message('success',translate('Rooms added successfully.'))); //redirect('rooms/'.$listId, 'refresh'); } else { $data['title'] = "Payment Cancelled !"; $data['message_element'] = "payments/paypal_cancel"; $this->load->view('template', $data); } /* } else { $data['title']="Payment Cancelled !"; $data['message_element'] = "payments/paypal_cancel"; $this->load->view('template',$data); } */ }
function _send_payment_request_callback() { Braintree_Configuration::environment('sandbox'); Braintree_Configuration::merchantId('4r57w2h7hgyqk52g'); Braintree_Configuration::publicKey('4y98n9vt93pvqpgj'); Braintree_Configuration::privateKey('32d966b730def400269d835b030fd109'); /*$amount = 10.30; $card = '4111111111111111'; $padDateMonth = '10'; $expDateYear = '20'; $cvv = '911'; */ $card_detail = explode('/', $_POST['expire_card']); $amount = $_POST['amount']; $card = $_POST['credit_card']; $padDateMonth = $card_detail[0]; $expDateYear = $card_detail[1]; $cvv = $_POST['cvv']; $result = Braintree_Transaction::sale(array('amount' => round(floatval($amount)), 'creditCard' => array('number' => $card, 'expirationMonth' => $padDateMonth, 'expirationYear' => $expDateYear, 'cvv' => $cvv))); if ($result->success == 1) { $trans_id = $result->transaction->_attributes['id']; $donatorData = array('trans_id' => $trans_id, 'team_id' => $_POST['team_id'], 'payment_type' => 'Online', 'amount' => $amount, 'donator_name' => $_POST['donator_name'], 'donator_email' => $_POST['donator_email'], 'trans_detail' => serialize($result->transaction->_attributes)); $objDonator = new tblDonator(); $objDonator->insert($donatorData); echo 1; } else { echo 0; } die; }
<?php include_once 'braintree-init.php'; $nonce = $_POST['payment_method_nonce']; $total = $_POST['total']; print_r($_POST); echo $nonce; $result = Braintree_Transaction::sale(['amount' => $total, 'paymentMethodNonce' => $nonce]); echo $result;
public function providerTripChangeState() { $date = date("Y-m-d H:i:s"); $time_limit = date("Y-m-d H:i:s", strtotime($date) - 3 * 60 * 60); $walker_id = Session::get('walker_id'); $state = $request_id = Request::segment(4); $current_request = Requests::where('confirmed_walker', $walker_id)->where('is_cancelled', 0)->where('is_dog_rated', 0)->where('created_at', '>', $time_limit)->orderBy('created_at', 'desc')->where(function ($query) { $query->where('status', 0)->orWhere(function ($query_inner) { $query_inner->where('status', 1)->where('is_dog_rated', 0); }); })->first(); if ($current_request && $state) { if ($state == 2) { $current_request->is_walker_started = 1; $owner = Owner::find($current_request->owner_id); $walker = Walker::find($walker_id); $location = get_location($owner->latitude, $owner->longitude); $latitude = $location['lat']; $longitude = $location['long']; $angle = get_angle($walker->latitude, $walker->longitude, $latitude, $longitude); $walker->old_latitude = $walker->latitude; $walker->old_longitude = $walker->longitude; $walker->latitude = $latitude; $walker->longitude = $longitude; $walker->bearing = $angle; $walker->save(); $walk_location = new WalkLocation(); $walk_location->request_id = $current_request->id; $walk_location->latitude = $latitude; $walk_location->longitude = $longitude; $walk_location->distance = 0; $walk_location->save(); } if ($state == 3) { $current_request->is_walker_arrived = 1; } if ($state == 4) { $current_request->is_started = 1; } if ($state == 6) { $rating = 0; if (Input::has('rating')) { $rating = Input::get('rating'); } $current_request->is_dog_rated = 1; $current_request->save(); $review_dog = new DogReview(); $review_dog->walker_id = $current_request->confirmed_walker; $review_dog->comment = Input::get('review'); $review_dog->rating = $rating; $review_dog->owner_id = $current_request->owner_id; $review_dog->request_id = $current_request->id; $review_dog->save(); if ($rating) { if ($owner = Owner::find($current_request->owner_id)) { $old_rate = $owner->rate; $old_rate_count = $owner->rate_count; $new_rate_counter = $owner->rate_count + 1; $new_rate = ($owner->rate * $owner->rate_count + $rating) / $new_rate_counter; $owner->rate_count = $new_rate_counter; $owner->rate = $new_rate; $owner->save(); } } $message = "You has successfully rated the owner."; $type = "success"; return Redirect::to('/provider/trips')->with('message', $message)->with('type', $type); } if ($state == 5) { $request_services = RequestServices::where('request_id', $current_request->id)->first(); $request_typ = ProviderType::where('id', '=', $request_services->req_typ)->first(); $address = urlencode(Input::get('address')); $end_address = json_decode(file_get_contents("https://maps.googleapis.com/maps/api/geocode/json?address={$address}"), TRUE); $end_location = $end_address['results'][0]['geometry']; $latitude = $end_location['location']['lat']; $longitude = $end_location['location']['lng']; $location = get_location($latitude, $longitude); $latitude = $location['lat']; $longitude = $location['long']; $request_id = $current_request->id; $walk_location_last = WalkLocation::where('request_id', $request_id)->orderBy('created_at', 'desc')->first(); if ($walk_location_last) { $distance_old = $walk_location_last->distance; $distance_new = distanceGeoPoints($walk_location_last->latitude, $walk_location_last->longitude, $latitude, $longitude); $distance = $distance_old + $distance_new; $settings = Settings::where('key', 'default_distance_unit')->first(); //$unit = $settings->value; $distance = $distance; } else { $distance = 0; } $walker = Walker::find($walker_id); $angle = get_angle($walker->latitude, $walker->longitude, $latitude, $longitude); $walker->old_latitude = $walker->latitude; $walker->old_longitude = $walker->longitude; $walker->latitude = $latitude; $walker->longitude = $longitude; $walker->bearing = $angle; $walker->save(); $walk_location = new WalkLocation(); $walk_location->request_id = $request_id; $walk_location->latitude = $latitude; $walk_location->longitude = $longitude; $walk_location->distance = $distance; $walk_location->save(); Walker::where('id', '=', $walker_id)->update(array('is_available' => 1)); // Calculate Rerquest Stats $time = 0; $time_query = "SELECT TIMESTAMPDIFF(SECOND,MIN(created_at),MAX(created_at)) as diff\n\t\t\t\tFROM walk_location where request_id = {$current_request->id}\n\t\t\t\tGROUP BY request_id limit 1 "; $time_data = DB::select(DB::raw($time_query)); foreach ($time_data as $time_diff) { $time = $time_diff->diff; } $time = $time / 60; /* TIME CALCULATION REDIRECTED */ $time = 0; /* TIME CALCULATION REDIRECTED END */ $walker_data = Walker::find($current_request->confirmed_walker); $provider_type = ProviderServices::where('type', $walker_data->type)->where('provider_id', $walker_id)->first(); if ($provider_type == NULL) { /* $settings = Settings::where('key', 'price_per_unit_distance')->first(); $price_per_unit_distance = $settings->value; $settings = Settings::where('key', 'price_per_unit_time')->first(); $price_per_unit_time = $settings->value; $settings = Settings::where('key', 'base_price')->first(); $base_price = $settings->value; */ $setbase_distance = $request_typ->base_distance; $base_price = $request_typ->base_price; $price_per_unit_distance = $request_typ->price_per_unit_distance; $price_per_unit_time = $request_typ->price_per_unit_time; } else { // $setbase_distance = $request_typ->base_distance; $setbase_distance = ""; $provider_type = ProviderServices::where('type', $walker_data->type)->where('provider_id', $walker_id)->first(); $base_price = $provider_type->base_price; $price_per_unit_distance = $provider_type->price_per_unit_distance; $price_per_unit_time = $provider_type->price_per_unit_time; } $settings = Settings::where('key', 'default_charging_method_for_users')->first(); $pricing_type = $settings->value; $settings = Settings::where('key', 'default_distance_unit')->first(); //$unit = $settings->value; $distance = convert($distance); if ($pricing_type == 1) { if ($distance <= $setbase_distance) { $distance_cost = 0; } else { $distance_cost = $price_per_unit_distance * ($distance - $setbase_distance); } $time_cost = $price_per_unit_time * $time; $total = $base_price + $distance_cost + $time_cost; } else { $distance_cost = 0; $time_cost = 0; $total = $base_price; } $current_request->is_completed = 1; $current_request->distance = $distance; $current_request->time = $time; $request_services->base_price = $base_price; $request_services->distance_cost = $distance_cost; $request_services->time_cost = $time_cost; $request_services->total = $total; $current_request->total = $total; $request_services->save(); // charge client // charge client $ledger = Ledger::where('owner_id', $current_request->owner_id)->first(); if ($ledger) { $balance = $ledger->amount_earned - $ledger->amount_spent; if ($balance > 0) { if ($total > $balance) { $ledger_temp = Ledger::find($ledger->id); $ledger_temp->amount_spent = $ledger_temp->amount_spent + $balance; $ledger_temp->save(); $total = $total - $balance; } else { $ledger_temp = Ledger::find($ledger->id); $ledger_temp->amount_spent = $ledger_temp->amount_spent + $total; $ledger_temp->save(); $total = 0; } } } $promo_discount = 0; if ($pcode = PromoCodes::where('id', $current_request->promo_code)->where('type', 1)->first()) { $discount = $pcode->value / 100; $promo_discount = $total * $discount; $total = $total - $promo_discount; if ($total < 0) { $total = 0; } } $current_request->total = $total; $current_request->save(); $cod_sett = Settings::where('key', 'cod')->first(); $allow_cod = $cod_sett->value; if ($current_request->payment_mode == 1 and $allow_cod == 1) { // Pay by Cash $current_request->is_paid = 1; Log::info('allow_cod'); } elseif ($current_request->payment_mode == 2) { // paypal Log::info('paypal payment'); } else { Log::info('normal payment. Stored cards'); // stored cards if ($total == 0) { $current_request->is_paid = 1; } else { $payment_data = Payment::where('owner_id', $current_request->owner_id)->where('is_default', 1)->first(); if (!$payment_data) { $payment_data = Payment::where('owner_id', $current_request->owner_id)->first(); } if ($payment_data) { $customer_id = $payment_data->customer_id; $setransfer = Settings::where('key', 'transfer')->first(); $transfer_allow = $setransfer->value; if (Config::get('app.default_payment') == 'stripe') { //dd($customer_id); Stripe::setApiKey(Config::get('app.stripe_secret_key')); try { $charge = Stripe_Charge::create(array("amount" => ceil($total * 100), "currency" => "usd", "customer" => $customer_id)); Log::info($charge); } catch (Stripe_InvalidRequestError $e) { // Invalid parameters were supplied to Stripe's API $ownr = Owner::find($current_request->owner_id); $ownr->debt = $total; $ownr->save(); $message = array('error' => $e->getMessage()); $type = "success"; Log::info($message); return Redirect::to('/provider/tripinprogress')->with('message', $message)->with('type', $type); } $current_request->is_paid = 1; $settng = Settings::where('key', 'service_fee')->first(); $settng_mode = Settings::where('key', 'payment_mode')->first(); if ($settng_mode->value == 2 and $transfer_allow == 1) { $transfer = Stripe_Transfer::create(array("amount" => ($total - $settng->value * $total / 100) * 100, "currency" => "usd", "recipient" => $walker_data->merchant_id)); $current_request->transfer_amount = $total - $settng->value * $total / 100; } } else { try { Braintree_Configuration::environment(Config::get('app.braintree_environment')); Braintree_Configuration::merchantId(Config::get('app.braintree_merchant_id')); Braintree_Configuration::publicKey(Config::get('app.braintree_public_key')); Braintree_Configuration::privateKey(Config::get('app.braintree_private_key')); if ($settng_mode->value == 2 and $transfer_allow == 1) { $sevisett = Settings::where('key', 'service_fee')->first(); $service_fee = $sevisett->value * $total / 100; $result = Braintree_Transaction::sale(array('amount' => $total - $service_fee, 'paymentMethodNonce' => $customer_id, 'merchantAccountId' => $walker_data->merchant_id, 'options' => array('submitForSettlement' => true, 'holdInEscrow' => true), 'serviceFeeAmount' => $service_fee)); } else { $result = Braintree_Transaction::sale(array('amount' => $total, 'paymentMethodNonce' => $customer_id)); } if ($result->success) { $request->is_paid = 1; } else { $request->is_paid = 0; } } catch (Exception $e) { $message = "Something went wrong in the payment. Please try again."; $type = "success"; return Redirect::to('/provider/tripinprogress')->with('message', $message)->with('type', $type); } } $current_request->card_payment = $total; $current_request->ledger_payment = $current_request->total - $total; } } } $current_request->save(); } $current_request->save(); } return Redirect::to('/provider/tripinprogress'); }
/** * Attempt to make a sale using the Braintree PHP SDK * * @param $saleArray * * @return stdClass */ public function makeSale($saleArray) { // Call the braintree library return Braintree_Transaction::sale($saleArray); }
public function form() { $result = Braintree_Transaction::sale(array("amount" => "1000.00", "creditCard" => array("number" => $_POST["number"], "cvv" => $_POST["cvv"], "expirationMonth" => $_POST["month"], "expirationYear" => $_POST["year"]), "options" => array("submitForSettlement" => true))); if ($result->success) { echo "Success! Transaction ID: " . $result->transaction->id; } else { if ($result->transaction) { echo "Error: " . $result->message; echo "<br/>"; echo "Code: " . $result->transaction->processorResponseCode; } else { echo "Validation errors:<br/>"; foreach ($result->errors->deepAll() as $error) { echo "- " . $error->message . "<br/>"; } } } pr($result); die; ?> <html> <head> <title>Braintree Transparent Redirect</title> </head> <body> <?php if (isset($_GET["id"])) { echo "id: " . $_GET["id"]; $result = Braintree_TransparentRedirect::confirm($_SERVER['QUERY_STRING']); pr($result); } if (isset($result) && $result->success) { ?> <h1>Braintree Transparent Redirect Response</h1> <?php $transaction = $result->transaction; ?> <table> <tr><td>transaction id</td><td><?php echo htmlentities($transaction->id); ?> </td></tr> <tr><td>transaction status</td><td><?php echo htmlentities($transaction->status); ?> </td></tr> <tr><td>transaction amount</td><td><?php echo htmlentities($transaction->amount); ?> </td></tr> <tr><td>customer first name</td><td><?php echo htmlentities($transaction->customerDetails->firstName); ?> </td></tr> <tr><td>customer last name</td><td><?php echo htmlentities($transaction->customerDetails->lastName); ?> </td></tr> <tr><td>customer email</td><td><?php echo htmlentities($transaction->customerDetails->email); ?> </td></tr> <tr><td>credit card number</td><td><?php echo htmlentities($transaction->creditCardDetails->maskedNumber); ?> </td></tr> <tr><td>expiration date</td><td><?php echo htmlentities($transaction->creditCardDetails->expirationDate); ?> </td></tr> </table> <?php } else { if (!isset($result)) { echo "gagal"; $result = null; } ?> <h1>Braintree Transparent Redirect Example</h1> <?php if (isset($result)) { ?> <div style="color: red;"><?php echo $result->errors->deepSize(); ?> error(s)</div> <?php } ?> <form method="POST" action="<?php echo Braintree_TransparentRedirect::url(); ?> " autocomplete="off"> <fieldset> <legend>Customer</legend> <?php $this->braintree_text_field('First Name', 'transaction[customer][first_name]', $result); ?> <?php $this->braintree_text_field('Last Name', 'transaction[customer][last_name]', $result); ?> <?php $this->braintree_text_field('Email', 'transaction[customer][email]', $result); ?> </fieldset> <fieldset> <legend>Payment Information</legend> <?php $this->braintree_text_field('Credit Card Number', 'transaction[credit_card][number]', $result); ?> <?php $this->braintree_text_field('Expiration Date (MM/YY)', 'transaction[credit_card][expiration_date]', $result); ?> <?php $this->braintree_text_field('CVV', 'transaction[credit_card][cvv]', $result); ?> </fieldset> <?php $tr_data = Braintree_TransparentRedirect::transactionData(array('redirectUrl' => "http://" . $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH), 'transaction' => array('amount' => '10.00', 'type' => 'sale'))); ?> <input type="hidden" name="tr_data" value="<?php echo $tr_data; ?> " /> <br /> <input type="submit" value="Submit" /> </form> <?php } ?> </body> </html> <?php }