public function calculate(Invoice $invoiceBill) { $this->coupon = $invoiceBill->getCoupon(); $this->user = $invoiceBill->getUser(); $isFirstPayment = $invoiceBill->isFirstPayment(); foreach ($invoiceBill->getItems() as $item) { $item->first_discount = $item->second_discount = 0; $item->_calculateTotal(); } if (!$this->coupon) { return; } if ($this->coupon->getBatch()->discount_type == Coupon::DISCOUNT_PERCENT) { foreach ($invoiceBill->getItems() as $item) { if ($this->coupon->isApplicable($item->item_type, $item->item_id, $isFirstPayment)) { $item->first_discount = moneyRound($item->first_total * $this->coupon->getBatch()->discount / 100); } if ($this->coupon->isApplicable($item->item_type, $item->item_id, false)) { $item->second_discount = moneyRound($item->second_total * $this->coupon->getBatch()->discount / 100); } } } else { // absolute discount $discountFirst = $this->coupon->getBatch()->discount; $discountSecond = $this->coupon->getBatch()->discount; $first_discountable = $second_discountable = array(); $first_total = $second_total = 0; $second_total = array_reduce($second_discountable, create_function('$s,$item', 'return $s+=$item->second_total;'), 0); foreach ($invoiceBill->getItems() as $item) { if ($this->coupon->isApplicable($item->item_type, $item->item_id, $isFirstPayment)) { $first_total += $item->first_total; $first_discountable[] = $item; } if ($this->coupon->isApplicable($item->item_type, $item->item_id, false)) { $second_total += $item->second_total; $second_discountable[] = $item; } } if ($first_total) { $k = max(0, min($discountFirst / $first_total, 1)); // between 0 and 1! foreach ($first_discountable as $item) { $item->first_discount = moneyRound($item->first_total * $k); } } if ($second_total) { $k = max(0, min($discountSecond / $second_total, 1)); // between 0 and 1! foreach ($second_discountable as $item) { $item->second_discount = moneyRound($item->second_total * $k); } } } foreach ($invoiceBill->getItems() as $item) { $item->_calculateTotal(); } }
public function _process(Invoice $invoice, Am_Request $request, Am_Paysystem_Result $result) { $a = new Am_Paysystem_Action_Form(self::URL); $vars = array('MERCHANT' => $this->getConfig('merchant'), 'ORDER_REF' => $invoice->public_id, 'ORDER_DATE' => $invoice->tm_added); foreach ($invoice->getItems() as $item) { $vars['ORDER_PNAME[]'] = $item->item_title; $vars['ORDER_PCODE[]'] = $item->item_id; $vars['ORDER_PRICE[]'] = $item->first_price; $vars['ORDER_QTY[]'] = $item->qty; $vars['ORDER_VAT[]'] = $item->first_tax; } $vars['ORDER_SHIPPING'] = 0; $vars['PRICES_CURRENCY'] = strtoupper($invoice->currency); $vars['DISCOUNT'] = $invoice->first_discount; foreach ($vars as $k => $v) { $a->__set($k, $v); } $a->__set('ORDER_HASH', $this->calculateHash($vars)); $a->__set('BILL_FNAME', $invoice->getFirstName()); $a->__set('BILL_LNAME', $invoice->getLastName()); $a->__set('BILL_EMAIL', $invoice->getEmail()); $a->__set('BILL_PHONE', $invoice->getPhone()); $a->__set('BILL_ADDRESS', $invoice->getStreet()); $a->__set('BILL_ZIPCODE', $invoice->getZip()); $a->__set('BILL_CITY', $invoice->getCity()); $a->__set('BILL_STATE', $invoice->getState()); $a->__set('BILL_COUNTRYCODE', $invoice->getCountry()); $a->__set('LANGUAGE', $this->getConfig('language', 'ro')); if ($this->getConfig('testing')) { $a->__set('TESTORDER', 'TRUE'); } $result->setAction($a); }
public function _process(Invoice $invoice, Am_Request $request, Am_Paysystem_Result $result) { $a = new Am_Paysystem_Action_Redirect(self::URL); $a->products = current(array_filter(array($invoice->getItem(0)->getBillingPlanData('paypro_product_id'), $this->getConfig('product_id')))); $id = $this->invoice->getSecureId("THANKS"); $desc = array(); foreach ($invoice->getItems() as $it) { if ($it->first_total > 0) { $desc[] = $it->item_title; } } $desc = implode(',', $desc); $desc .= ". (invoice: {$id})"; $name = $invoice->getLineDescription(); $hash = "price={$invoice->first_total}-{$invoice->currency}^^^name={$name}^^^desc={$desc}"; $a->hash = base64_encode($this->getHash($hash)); $a->CustomField1 = $invoice->public_id; $a->firstname = $invoice->getFirstName(); $a->Lastname = $invoice->getLastName(); $a->Email = $invoice->getEmail(); $a->Address = $invoice->getStreet(); $a->City = $invoice->getCity(); $a->Country = $invoice->getCountry() == 'GB' ? 'united kingdom' : $invoice->getCountry(); $a->State = $invoice->getState(); $a->Zipcode = $invoice->getZip(); $a->Phone = $invoice->getPhone(); //$a->lnk = $this->getCancelUrl(); $result->setAction($a); }
public function _process(Invoice $invoice, Am_Request $request, Am_Paysystem_Result $result) { $items = $invoice->getItems(); if (count($items) > 1) { $exc = new Am_Exception_InternalError("It's impossible purchase " . count($items) . " products at one invoice with Selz-plugin"); $this->getDi()->errorLogTable->logException($exc); throw $exc; } $item = $items[0]; $bp = $this->getDi()->billingPlanTable->load($item->billing_plan_id); $sharedLink = $bp->data()->get(self::SHARED_LINK_FIELD); if (!$sharedLink) { $exc = new Am_Exception_InternalError("Product #{$item->item_id} has no shared link"); $this->getDi()->errorLogTable->logException($exc); throw $exc; } if ($this->getConfig('payment_way', 'redirect') == 'redirect') { $a = new Am_Paysystem_Action_Redirect($sharedLink); } else { $a = new Am_Paysystem_Action_HtmlTemplate_Selz($this->getDir(), 'selz.phtml'); $a->link = $sharedLink; $a->inv = $invoice->public_id; $a->thanks = $this->getReturnUrl(); $a->ipn = $this->getPluginUrl('ipn'); $a->way = $this->getConfig('payment_way'); } $result->setAction($a); }
public function _process(Invoice $invoice, Am_Request $request, Am_Paysystem_Result $result) { $a = new Am_Paysystem_Action_Form(self::URL); $vars = array('MERCHANT' => $this->getConfig('email'), 'COUNTRY_ID' => $this->getConfig('country'), 'PAYMENT_METHOD_AVAILABLE' => 'all', 'TRANSACTION_ID' => $invoice->public_id); $i = '1'; foreach ($invoice->getItems() as $item) { //Creating new format without dot for $item->first_price $price = str_replace('.', '', $item->first_total); $vars['ITEM_NAME_' . $i] = $item->item_title; $vars['ITEM_CODE_' . $i] = $item->item_id; $vars['ITEM_AMMOUNT_' . $i] = $price; $vars['ITEM_QUANTITY_' . $i] = $item->qty; $vars['ITEM_CURRENCY_' . $i] = $item->currency; $i++; } $vars['CURRENCY'] = strtoupper($invoice->currency); foreach ($vars as $k => $v) { $a->__set($k, $v); } $a->__set('BUYER_FNAME', $invoice->getFirstName()); $a->__set('BUYER_LNAME', $invoice->getLastName()); $a->__set('BUYER_EMAIL', $invoice->getEmail()); $a->__set('BUYER_PHONE', $invoice->getPhone()); $a->__set('BUYER_STREET', $invoice->getStreet()); $a->__set('BUYER_STATE', $invoice->getState()); $a->__set('BUYER_CITY', $invoice->getCity()); $a->__set('BUYER_COUNTRY', $invoice->getCountry()); $a->__set('BUYER_ZIP_CODE', $invoice->getZip()); $a->__set('BUYER_CITY', $invoice->getCity()); $a->__set('BUYER_STATE', $invoice->getState()); $a->__set('LANGUAGE', $this->getConfig('language', 'es')); $result->setAction($a); }
public function calculate(Invoice $invoiceBill) { $this->invoiceBill = $invoiceBill; foreach ($invoiceBill->getItems() as $item) { $this->item = $item; foreach (self::$_prefixes as $prefix) { $this->currentPrefix = $prefix; $fields = new stdClass(); foreach (self::$_noPrefixFields as $k) { $fields->{$k} = @$item->{$k}; } foreach (self::$_prefixFields as $k) { $kk = $prefix ? $prefix . $k : $k; if (isset($fields->{$kk})) { throw new Am_Exception_InternalError("Field is already defined [{$k}]"); } $fields->{$k} = @$item->{$kk}; } $this->calculatePiece($fields); foreach (self::$_noPrefixFields as $k) { $item->{$k} = $fields->{$k}; } foreach (self::$_prefixFields as $k) { $kk = $prefix ? $prefix . $k : $k; $item->{$kk} = $fields->{$k}; } } unset($this->item); } }
public function _process(Invoice $invoice, Am_Request $request, Am_Paysystem_Result $result) { $u = $invoice->getUser(); $domain = $this->getConfig('testing') ? Am_Paysystem_Xfers::SANDBOX_DOMAIN : Am_Paysystem_Xfers::LIVE_DOMAIN; $a = new Am_Paysystem_Action_Form('https://' . $domain . '/api/v2/payments'); $a->api_key = $this->getConfig('api_key'); $a->order_id = $invoice->public_id; $a->cancel_url = $this->getCancelUrl(); $a->return_url = $this->getReturnUrl(); $a->notify_url = $this->getPluginUrl('ipn'); if ($invoice->first_tax) { $a->tax = $invoice->first_tax; } /* @var $item InvoiceItem */ $i = 1; foreach ($invoice->getItems() as $item) { $a->{'item_name_' . $i} = $item->item_title; $a->{'item_description_' . $i} = $item->item_description; $a->{'item_quantity_' . $i} = $item->qty; $a->{'item_price_' . $i} = $item->first_price; $i++; } $a->total_amount = $invoice->first_total; $a->currency = $invoice->currency; $a->user_email = $invoice->getUser()->email; $a->signature = sha1($a->api_key . $this->getConfig('api_secret') . $a->order_id . $a->total_amount . $a->currency); $result->setAction($a); }
public function isNotAcceptableForInvoice(Invoice $invoice) { foreach ($invoice->getItems() as $item) { /* @var $item InvoiceItem */ if (!$item->getBillingPlanData('centili_apikey')) { return "item [" . $item->item_title . "] has no related Centili Api Key configured"; } } }
/** * @param Invoice $dataObject * @return \Magento\Sales\Model\Order\Invoice * @throws \Exception */ public function getModel(Invoice $dataObject) { $items = []; /** @var InvoiceItem $item */ foreach ($dataObject->getItems() as $item) { $items[$item->getOrderItemId()] = $item->getQty(); } return $this->invoiceLoader->setOrderId($dataObject->getOrderId())->setInvoiceId($dataObject->getEntityId())->setInvoiceItems($items)->create(); }
public function isNotAcceptableForInvoice(Invoice $invoice) { foreach ($invoice->getItems() as $item) { /* @var $item InvoiceItem */ if (!$item->getBillingPlanData('clickbank_product_id')) { return "item [" . $item->item_title . "] has no related ClickBank product configured"; } } }
public function isNotAcceptableForInvoice(Invoice $invoice) { $items = $invoice->getItems(); if (count($items) > 1) { return 'Justclick can not process invoices with more than one item'; } /* @var $item InvoiceItem */ if (!$items[0]->getBillingPlanData('justclick_id')) { return "item [" . $item->item_title . "] has no related Justclick product configured"; } }
public function _process(Invoice $invoice, Am_Request $request, Am_Paysystem_Result $result) { if (count($invoice->getItems()) > 1) { throw new Am_Exception_InternalError('Only one product at invoice is allowed'); } $bp = $this->getDi()->billingPlanTable->load($invoice->getItem(0)->billing_plan_id); if (!($campaignId = $bp->data()->get(self::JP_CAMPAIGN_ID))) { throw new Am_Exception_InternalError("Product #{$invoice->getItem(0)->item_id} cannot be paid by junglepay - has no Campaign ID"); } $a = new Am_Paysystem_Action_HtmlTemplate_Junglepay($this->getDir(), 'payment-junglepay-iframe.phtml'); $a->wkey = $campaignId; $a->refererId = $invoice->public_id; $result->setAction($a); }
public function encodeInvoice(Invoice $invoice) { $data = ['id' => $invoice->getId(), 'number' => $invoice->getNumber(), 'name' => $invoice->getName(), 'created' => $invoice->getCreated(), 'delivered' => $invoice->getDelivered(), 'due' => $invoice->getDue(), 'status' => $invoice->getStatus(), 'variable_symbol' => $invoice->getVariableSymbol(), 'constant_symbol' => $invoice->getConstantSymbol(), 'description' => $invoice->getDescription(), 'items' => $this->encodeItems($invoice->getItems()), 'price' => $invoice->getPrice(), 'price_total' => $invoice->getPriceTotal(), 'currency' => $invoice->getCurrency()]; if ($invoice->getClient()) { $data['client'] = $this->encodeClient($invoice->getClient()); } if ($invoice->getShippingAddress()) { $data['shipping_address'] = $this->encodeAddress($invoice->getShippingAddress()); } if ($invoice->getDiscount() && $invoice->getDiscount()->getType() != 'none') { $data['discount'] = ['type' => $invoice->getDiscount()->getType(), 'value' => $invoice->getDiscount()->getValue()]; } return json_encode(['invoice' => $data]); }
public function _process(Invoice $invoice, Am_Request $request, Am_Paysystem_Result $result) { $u = $invoice->getUser(); $request = $this->createHttpRequest(); $basket = '<basket>'; foreach ($invoice->getItems() as $item) { $basket .= '<item>'; $basket .= '<description>' . $item->item_title . '</description>'; $basket .= '<productSku>' . $item->item_id . '</productSku>'; $basket .= '<quantity>' . $item->qty . '</quantity>'; $basket .= '<unitNetAmount>' . $item->first_price . '</unitNetAmount>'; $basket .= '<unitTaxAmount>' . $item->first_tax / $item->qty . '</unitTaxAmount>'; $basket .= '<unitGrossAmount>' . $item->first_total / $item->qty . '</unitGrossAmount>'; $basket .= '<totalGrossAmount>' . $item->first_total . '</totalGrossAmount>'; $basket .= '</item>'; } $basket .= '</basket>'; $vars = array('VPSProtocol' => '3.0', 'TxType' => 'PAYMENT', 'Vendor' => $this->getConfig('login'), 'VendorTxCode' => $invoice->public_id . '-AMEMBER', 'Amount' => number_format($invoice->first_total, 2, '.', ''), 'Currency' => $invoice->currency ? $invoice->currency : 'USD', 'Description' => $invoice->getLineDescription(), 'NotificationURL' => $this->getPluginUrl('ipn'), 'SuccessURL' => $this->getReturnUrl(), 'RedirectionURL' => $this->getReturnUrl(), 'BillingFirstnames' => $u->name_f, 'BillingSurname' => $u->name_l, 'BillingAddress1' => $u->street, 'BillingCity' => $u->city, 'BillingPostCode' => $u->zip, 'BillingCountry' => $u->country, 'DeliveryFirstnames' => $u->name_f, 'DeliverySurname' => $u->name_l, 'DeliveryAddress1' => $u->street, 'DeliveryCity' => $u->city, 'DeliveryPostCode' => $u->zip, 'DeliveryCountry' => $u->country, 'CustomerEMail' => $u->email, 'Profile' => 'NORMAL', 'BasketXML' => $basket); if ($u->country == 'US') { $vars['BillingState'] = $u->state; $vars['DeliveryState'] = $u->state; } $request->addPostParameter($vars); $request->setUrl($this->getConfig('testing') ? self::TEST_URL : self::LIVE_URL); $request->setMethod(Am_HttpRequest::METHOD_POST); $this->logRequest($request); $response = $request->send(); $this->logResponse($response); if (!$response->getBody()) { throw new Am_Exception_InputError("An error occurred while payment request"); } $res = array(); foreach (split(PHP_EOL, $response->getBody()) as $line) { list($l, $r) = explode('=', $line, 2); $res[trim($l)] = trim($r); } if ($res['Status'] == 'OK') { $invoice->data()->set('sagepay_securitykey', $res['SecurityKey']); $invoice->update(); $a = new Am_Paysystem_Action_Form($res['NextURL']); $result->setAction($a); } else { throw new Am_Exception_InputError($res['StatusDetail']); } }
public function _process(Invoice $invoice, Am_Request $request, Am_Paysystem_Result $result) { $a = new Am_Paysystem_Action_Redirect($this->getConfig('testing') ? self::SANDBOX_URL : self::LIVE_URL); $a->merchant_id = $this->getConfig('merchant_id'); $a->merchant_site_id = $this->getConfig('merchant_site_id'); $a->currency = $invoice->currency; $a->version = '3.0.0'; $a->merchant_unique_id = $invoice->public_id; $a->first_name = $invoice->getFirstName(); $a->last_name = $invoice->getLastName(); $a->email = $invoice->getEmail(); $a->address1 = $invoice->getStreet(); $a->address2 = $invoice->getStreet1(); $a->city = $invoice->getCity(); $a->country = $invoice->getCountry(); $a->state = $invoice->getState(); $a->zip = $invoice->getZip(); $a->phone1 = $invoice->getPhone(); $a->time_stamp = date("Y-m-d.h:i:s"); if ($invoice->rebill_times && ($gate2shop_id = $invoice->getItem(0)->getBillingPlanData('gate2shop_id')) && ($gate2shop_template_id = $invoice->getItem(0)->getBillingPlanData('gate2shop_template_id'))) { $a->productId = $invoice->getItem(0)->item_id; $a->rebillingProductId = $gate2shop_id; $a->rebillingTemplateId = $gate2shop_template_id; if ($invoice->rebill_times) { $a->isRebilling = 'true'; } $a->checksum = md5($this->getConfig('secret_key') . $this->getConfig('merchant_id') . $gate2shop_id . $gate2shop_template_id . $a->time_stamp); } else { $a->total_amount = $invoice->first_total; $a->discount = $invoice->first_discount; $a->total_tax = $invoice->first_tax; $a->numberofitems = count($invoice->getItems()); for ($i = 0; $i < $a->numberofitems; $i++) { $item = $invoice->getItem($i); $a->addParam('item_name_' . ($i + 1), $item->item_title); $a->addParam('item_number_' . ($i + 1), $i + 1); $a->addParam('item_amount_' . ($i + 1), $item->first_price); $a->addParam('item_discount_' . ($i + 1), $item->first_discount); $a->addParam('item_quantity_' . ($i + 1), $item->qty); } $a->checksum = $this->calculateOutgoingHash($a, $invoice); } $a->filterEmpty(); $result->setAction($a); }
/** * @param Invoice $invoice * @return array of ProductUpgrade */ function findUpgrades(Invoice $invoice) { $items = $invoice->getItems(); if (!$items) { return array(); } static $cache; if (empty($cache)) { foreach ($this->_db->select("SELECT * FROM {$this->_table}") as $row) { $cache[$row['from_billing_plan_id']][] = $row; } } $ret = array(); foreach ((array) @$cache[$items[0]->billing_plan_id] as $row) { $ret[] = $this->createRecord($row); } return $ret; }
public function _process(Invoice $invoice, Am_Request $request, Am_Paysystem_Result $result) { $a = new Am_Paysystem_Action_Form(self::URL_LIVE); $result->setAction($a); $sequence = rand(1, 1000); $vars = array('x_version' => '1.0', 'x_login' => $this->getConfig('login'), 'x_invoice_num' => $invoice->public_id, 'x_method' => $this->getConfig('testmode') ? 'TEST' : 'NONE', 'x_name' => $invoice->getName(), 'x_address' => $invoice->getStreet(), 'x_address2' => $invoice->getStreet2(), 'x_city' => $invoice->getCity(), 'x_country' => $invoice->getCountry(), 'x_state' => $invoice->getState(), 'x_zip' => $invoice->getZip(), 'x_email' => $invoice->getEmail(), 'x_currency_code' => $invoice->currency, 'x_amount' => $price = sprintf('%.2f', $invoice->first_total), 'x_tax_amount' => $tprice = sprintf('%.2f', $invoice->first_tax), 'x_fp_sequence' => $sequence, 'x_fp_arg_list' => 'x_login^x_fp_arg_list^x_fp_sequence^x_amount^x_currency_code', 'x_fp_hash' => '', 'x_fp_hash' => md5($q = $this->getConfig('login') . "^x_login^x_fp_arg_list^x_fp_sequence^x_amount^x_currency_code^" . $sequence . "^" . $price . "^" . $invoice->currency . "^" . $this->getConfig('key'))); foreach ($invoice->getItems() as $kk => $item) { $k = $kk + 1; $vars['x_product_sku_' . $k] = $item->item_id; $vars['x_product_title_' . $k] = $item->item_title; $vars['x_product_quantity_' . $k] = $item->qty; $vars['x_product_unitprice_' . $k] = $item->first_total; $vars['x_product_url_' . $k] = ROOT_URL; } foreach ($vars as $k => $v) { $a->addParam($k, $v); } $result->setAction($a); }
public function _process(Invoice $invoice, Am_Request $request, Am_Paysystem_Result $result) { $a = new Am_Paysystem_Action_Redirect(self::GATEWAY); $result->setAction($a); $a->mer_id = $this->getConfig('mer_id'); $a->pageid = $this->getConfig('pageid'); $a->next_phase = 'paydata'; $a->valuta_code = $invoice->currency; $user = $invoice->getUser(); $a->cust_name = $user->getName(); $a->cust_email = $user->email; $a->cust_phone = $user->phone; $a->cust_address1 = $user->street; $a->cust_address2 = $user->street2; $a->cust_city = $user->city; $a->cust_state = $user->state ? $user->state : 'N/A'; $a->cust_zip = $user->zip ? $user->zip : '99999'; $a->cust_country_code = $user->country; $num = 0; foreach ($invoice->getItems() as $item) { $num++; $a->{"item{$num}_desc"} = $item->item_title; $a->{"item{$num}_price"} = $item->first_price; $a->{"item{$num}_qty"} = $item->qty; } $a->num_items = $num; if ((double) $invoice->first_discount) { $a->sales_discount_amout = $invoice->first_discount; } if ((double) $invoice->first_tax) { $a->sales_tax_amout = $invoice->first_tax; } $a->user1 = $invoice->public_id; if ((double) $invoice->second_total) { $a->rebill_type = $this->getRebillType($invoice); $a->rebill_desc = $invoice->getLineDescription(); if ($invoice->rebill_times != IProduct::RECURRING_REBILLS) { $a->rebill_count = $invoice->rebill_times; } } }
public function _process(Invoice $invoice, Am_Request $request, Am_Paysystem_Result $result) { $req = new Am_HttpRequest('https://' . $this->getWsHost() . '/v2/checkout', Am_HttpRequest::METHOD_POST); $p = array(); $p['email'] = $this->getConfig('merchant'); $p['token'] = $this->getConfig('token'); $p['currency'] = strtoupper($invoice->currency); $p['reference'] = $invoice->public_id; $p['receiverEmail'] = $this->getConfig('merchant'); $i = 1; foreach ($invoice->getItems() as $item) { $p['itemId' . $i] = $item->item_id; $p['itemDescription' . $i] = $item->item_title; $p['itemAmount' . $i] = $item->first_total; $p['itemQuantity' . $i] = $item->qty; $i++; } $p['senderEmail'] = $invoice->getUser()->email; $p['senderName'] = $invoice->getUser()->getName(); $p['redirectURL'] = $this->getReturnUrl(); $p['notificationURL'] = $this->getPluginUrl('ipn'); $p['maxUses'] = 1; $p['maxAge'] = 180; $req->addPostParameter($p); $this->logRequest($req); $res = $req->send(); $this->logResponse($res); if (!($xml = simplexml_load_string($res->getBody()))) { throw new Am_Exception('Incorrect XML recieved'); } if ($xml->getName() == 'errors') { throw new Am_Exception(sprintf('%s: %s', $xml->errors[0]->code, $xml->errors[0]->message)); } if ($res->getStatus() != 200) { throw new Am_Exception_FatalError(sprintf('Incorrect Responce Status From Paysystem [%s]', $res->getStatus())); } $code = (string) $xml->code; $a = new Am_Paysystem_Action_Redirect('https://' . $this->getHost() . '/v2/checkout/payment.html?code=' . $code); $result->setAction($a); }
public function _process(Invoice $invoice, Am_Request $request, Am_Paysystem_Result $result) { $a = new Am_Paysystem_Action_Redirect($this->getConfig('multi_page') ? self::mURL : self::URL); $a->sid = $this->getConfig('seller_id'); $a->mode = '2CO'; $i = 0; foreach ($invoice->getItems() as $item) { $a->{"li_{$i}_type"} = 'product'; $a->{"li_{$i}_name"} = $item->item_title; $a->{"li_{$i}_quantity"} = $item->qty; $a->{"li_{$i}_price"} = moneyRound(($item->rebill_times ? $item->second_total : $item->first_total) / $item->qty); $a->{"li_{$i}_tangible"} = $item->is_tangible ? 'Y' : 'N'; $a->{"li_{$i}_product_id"} = $item->item_id; if ($item->rebill_times) { $a->{"li_{$i}_recurrence"} = $this->period2Co($item->first_period); if ($item->rebill_times != IProduct::RECURRING_REBILLS) { $a->{"li_{$i}_duration"} = $this->period2Co($item->first_period, $item->rebill_times + 1); } else { $a->{"li_{$i}_duration"} = 'Forever'; } $a->{"li_{$i}_startup_fee"} = $item->first_total - $item->second_total; } $i++; } $a->currency_code = $invoice->currency; $a->skip_landing = 1; $a->x_Receipt_Link_URL = $this->getReturnUrl(); $a->lang = $this->getConfig('lang', 'en'); $a->merchant_order_id = $invoice->public_id; $a->first_name = $invoice->getFirstName(); $a->last_name = $invoice->getLastName(); $a->city = $invoice->getCity(); $a->street_address = $invoice->getStreet(); $a->state = $invoice->getState(); $a->zip = $invoice->getZip(); $a->country = $invoice->getCountry(); $a->email = $invoice->getEmail(); $a->phone = $invoice->getPhone(); $result->setAction($a); }
public function _process(Invoice $invoice, Am_Request $request, Am_Paysystem_Result $result) { $u = $invoice->getUser(); $a = new Am_Paysystem_Action_Redirect($this->getConfig('testing') ? self::SANDBOX_URL : self::LIVE_URL); $a->ps_store_id = $this->getConfig('ps_store_id'); $a->hpp_key = $this->getConfig('hpp_key'); $a->charge_total = sprintf('%.2f', $invoice->first_total); $a->cust_id = $invoice->public_id; $a->email = $u->email; $a->shipping_cost = sprintf('%.2f', $invoice->first_shipping); $i = 1; foreach ($invoice->getItems() as $item) { $a->{'id' . $i} = $item->item_id; $a->{'description' . $i} = $item->item_title; $a->{'quantity' . $i} = $item->qty; $a->{'price' . $i} = $item->first_price; $a->{'subtotal' . $i} = $item->first_total; $i++; } $a->bill_first_name = $u->name_f; $a->bill_last_name = $u->name_l; $a->bill_address_one = $u->street; $a->bill_city = $u->city; $a->bill_state_or_province = $u->state; $a->bill_postal_code = $u->zip; $a->bill_country = $u->country; if ($invoice->second_total > 0) { $periods = array('m' => 'month', 'y' => 'year', 'd' => 'day', 'w' => 'week'); $second_period = new Am_Period($invoice->second_period); $a->recurUnit = $periods[$second_period->getUnit()]; $a->recurPeriod = $second_period->getCount(); $a->recurStartNow = $invoice->first_total > 0 ? 'true' : 'false'; $a->doRecur = 1; $a->recurStartDate = date('Y/m/d', strtotime($invoice->calculateRebillDate(1))); $a->recurAmount = sprintf('%.2f', $invoice->second_total); $a->recurNum = $invoice->rebill_times; } $result->setAction($a); }
public function _process(Invoice $invoice, Am_Request $request, Am_Paysystem_Result $result) { $u = $invoice->getUser(); $msp = $this->createMSP(); $msp->merchant['notification_url'] = $this->getPluginUrl('ipn'); $msp->merchant['cancel_url'] = $this->getCancelUrl(); $msp->merchant['redirect_url'] = $this->getReturnUrl(); $msp->customer['locale'] = 'en'; $msp->customer['firstname'] = $u->name_f; $msp->customer['lastname'] = $u->name_l; $msp->customer['zipcode'] = $u->zip; $msp->customer['city'] = $u->city; $msp->customer['country'] = $u->country; $msp->customer['email'] = $u->email; $msp->parseCustomerAddress($member['street']); /* * Transaction Details */ $msp->transaction['id'] = $invoice->public_id; // generally the shop's order ID is used here $msp->transaction['currency'] = $invoice->currency; $msp->transaction['amount'] = $invoice->first_total * 100; // cents $msp->transaction['description'] = $invoice->getLineDescription(); $out = ''; foreach ($invoice->getItems() as $item) { $out .= sprintf('<li>%s</li>', htmlspecialchars($item->item_title)); } $msp->transaction['items'] = sprintf('<br/><ul>%s</ul>', $out); $url = $msp->startTransaction(); if ($msp->error) { $result->setFailed(___('Error happened during payment process. ') . ' (' . $msp->error_code . ": " . $msp->error . ')'); return; } $a = new Am_Paysystem_Action_Redirect($url); $result->setAction($a); }
/** * Draws table rows * * @param null * @return null */ function drawItemsTableRows() { $rgb = $this->convertHTMLColorToDec($this->getBodyFontColor()); $this->SetTextColor($rgb['R'], $rgb['G'], $rgb['B']); // remember starting coordinates $starting_y = $this->GetY(); $starting_x = $this->GetX(); $this->SetFont('', '', $this->font_size); if (is_foreachable($this->invoice->getItems())) { $row_id = 1; foreach ($this->invoice->getItems() as $item) { $height = ceil($this->GetStringWidth($item->getDescription()) / $this->getItemsTableColumnWidth(1)) * $this->line_height; if ($this->GetY() + $height > $this->PageHeight()) { $this->AddPage(); } // if $temp_y = $this->GetY(); $rel_height = $this->GetY(); $this->SetX($this->getItemsTableColumnWidth(0) + $starting_x); $this->MultiCell($this->getItemsTableColumnWidth(1), $this->line_height, $item->getDescription(), 1, 'L', false); $rel_height = $this->GetY() - $rel_height; $this->SetY($temp_y); $this->SetX($starting_x); $this->MultiCell($this->getItemsTableColumnWidth(0), $rel_height, $row_id . '.', 1, 'R', false, false); $this->SetX($this->getItemsTableColumnWidth(0) + $this->getItemsTableColumnWidth(1) + $this->lMargin); $this->MultiCell($this->getItemsTableColumnWidth(2), $rel_height, $item->getQuantity(), 1, 'R', false, false); $this->MultiCell($this->getItemsTableColumnWidth(3), $rel_height, number_format($item->getUnitCost(), 2, NUMBER_FORMAT_DEC_SEPARATOR, NUMBER_FORMAT_THOUSANDS_SEPARATOR), 1, 'R', false, false); $this->MultiCell($this->getItemsTableColumnWidth(4), $rel_height, number_format($item->getTax(), 2, NUMBER_FORMAT_DEC_SEPARATOR, NUMBER_FORMAT_THOUSANDS_SEPARATOR), 1, 'R', false, false); $this->MultiCell($this->getItemsTableColumnWidth(5), $rel_height, number_format($item->getTotal(), 2, NUMBER_FORMAT_DEC_SEPARATOR, NUMBER_FORMAT_THOUSANDS_SEPARATOR), 1, 'R', false, false); $this->Ln(); $row_id++; } // foreach } // if }
protected function createXml(Invoice $invoice) { $user = $invoice->getUser(); $xml = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><CreateAccessCodeRequest></CreateAccessCodeRequest>'); $xml->addChild('RedirectUrl', $this->plugin->getPluginUrl('ipn')); $xml->addChild('TransactionType', 'Purchase'); $xml->addChild('Method', 'TokenPayment'); $xml->addChild('Customer'); $xml->Customer->addChild('Reference', $user->user_id); $xml->Customer->addChild('FirstName', $user->name_f); $xml->Customer->addChild('LastName', $user->name_l); $xml->Customer->addChild('Street1', $user->street); $xml->Customer->addChild('City', $user->city); $xml->Customer->addChild('State', $user->state); $xml->Customer->addChild('PostalCode', $user->zip); $xml->Customer->addChild('Country', strtolower($user->country)); $xml->Customer->addChild('Email', $user->email); $xml->Customer->addChild('Phone', $user->phone); $xml->addChild('Items'); foreach ($invoice->getItems() as $item) { $xml->Items->addChild('LineItem'); $xml->Items->LineItem->addChild('Description', $item->item_title); } $xml->addChild('Payment'); $xml->Payment->addChild('TotalAmount', $invoice->first_total * 100); $xml->Payment->addChild('InvoiceNumber', $invoice->public_id); $xml->Payment->addChild('CurrencyCode', $invoice->currency); $xml->Payment->addChild('InvoiceDescription', $invoice->getLineDescription()); $xml->Payment->addChild('InvoiceReference', $invoice->public_id); return utf8_encode($xml->asXML()); }
/** * Update existing invoice * * @param void * @return null */ function edit() { $this->wireframe->print_button = false; if ($this->active_invoice->isNew()) { $this->httpError(HTTP_ERR_NOT_FOUND); } // if if (!$this->active_invoice->canEdit($this->logged_user)) { $this->httpError(HTTP_ERR_FORBIDDEN); } // if $invoice_data = $this->request->post('invoice'); if (!is_array($invoice_data)) { $invoice_data = array('number' => $this->active_invoice->getNumber(), 'due_on' => $this->active_invoice->getDueOn(), 'issued_on' => $this->active_invoice->getIssuedOn(), 'currency_id' => $this->active_invoice->getCurrencyId(), 'comment' => $this->active_invoice->getComment(), 'company_id' => $this->active_invoice->getCompanyId(), 'company_address' => $this->active_invoice->getCompanyAddress(), 'project_id' => $this->active_invoice->getProjectId(), 'note' => $this->active_invoice->getNote(), 'language_id' => $this->active_invoice->getLanguageId()); if (is_foreachable($this->active_invoice->getItems())) { $invoice_data['items'] = array(); foreach ($this->active_invoice->getItems() as $item) { $invoice_data['items'][] = array('description' => $item->getDescription(), 'unit_cost' => $item->getUnitCost(), 'quantity' => $item->getQuantity(), 'tax_rate_id' => $item->getTaxRateId(), 'total' => $item->getTotal(), 'subtotal' => $item->getSubtotal(), 'time_record_ids' => $item->getTimeRecordIds()); } // foreach } // if } // if $invoice_notes = InvoiceNoteTemplates::findAll(); $invoice_item_templates = InvoiceItemTemplates::findAll(); $this->smarty->assign(array('invoice_data' => $invoice_data, 'invoice_item_templates' => $invoice_item_templates, 'tax_rates' => TaxRates::findAll(), 'invoice_notes' => $invoice_notes, 'original_note' => $this->active_invoice->getNote())); $cleaned_notes = array(); if (is_foreachable($invoice_notes)) { foreach ($invoice_notes as $invoice_note) { $cleaned_notes[$invoice_note->getId()] = $invoice_note->getContent(); } // foreach } // if js_assign('invoice_notes', $cleaned_notes); js_assign('original_note', $this->active_invoice->getNote()); $cleaned_item_templates = array(); if (is_foreachable($invoice_item_templates)) { foreach ($invoice_item_templates as $invoice_item_template) { $cleaned_item_templates[$invoice_item_template->getId()] = array('description' => $invoice_item_template->getDescription(), 'unit_cost' => $invoice_item_template->getUnitCost(), 'quantity' => $invoice_item_template->getQuantity(), 'tax_rate_id' => $invoice_item_template->getTaxRateId()); } // foreach } // if js_assign('invoice_item_templates', $cleaned_item_templates); js_assign('company_details_url', assemble_url('invoice_company_details')); js_assign('move_icon_url', get_image_url('move.gif')); if ($this->request->isSubmitted()) { $this->active_invoice->setAttributes($invoice_data); $invoice_company = Companies::findById(array_var($invoice_data, 'company_id', null)); $this->active_invoice->setCompanyName($invoice_company->getName()); $save = $this->active_invoice->save(); if ($save && !is_error($save)) { InvoiceItems::deleteByInvoice($this->active_invoice); $counter = 1; if (is_foreachable($invoice_data['items'])) { foreach ($invoice_data['items'] as $invoice_item_data) { $invoice_item = new InvoiceItem(); $invoice_item->setAttributes($invoice_item_data); $invoice_item->setInvoiceId($this->active_invoice->getId()); $invoice_item->setPosition($counter); $item_save = $invoice_item->save(); if ($item_save && !is_error($item_save)) { $invoice_item->setTimeRecordIds(array_var($invoice_item_data, 'time_record_ids', null)); $counter++; } else { $this->smarty->assign('errors', new ValidationErrors(array('items' => lang('Invoice items data is not valid. All descriptions are required and there need to be at least one unit with cost set per item!')))); } // if } // foreach flash_success('":number" has been updated', array('number' => $this->active_invoice->getName())); if ($this->active_invoice->isIssued()) { $invoice_company = $this->active_invoice->getCompany(); if (instance_of($invoice_company, 'Company') && $invoice_company->hasManagers()) { $this->redirectTo('invoice_notify', array('invoice_id' => $this->active_invoice->getId())); } // if } // if $this->redirectToUrl($this->active_invoice->getViewUrl()); } else { $this->smarty->assign('errors', $save); } // if } // if } // if }
/** * Process invoice and insert necessary commissions for it * * External code should guarantee that this method with $payment = null will be called * only once for each user for First user invoice */ public function processPayment(Invoice $invoice, InvoicePayment $payment = null) { $aff_id = $invoice->aff_id; /* @var $coupon Coupon */ try { if (!$aff_id && ($coupon = $invoice->getCoupon())) { // try to find affiliate by coupon $aff_id = $coupon->aff_id ? $coupon->aff_id : $coupon->getBatch()->aff_id; } } catch (Am_Exception_Db_NotFound $e) { //coupon not found } if (empty($aff_id)) { $aff_id = $invoice->getUser()->aff_id; } if ($aff_id && empty($invoice->aff_id)) { // set aff_id to invoice for quick access next time $invoice->updateQuick('aff_id', $aff_id); } // run event to get plugins chance choose another affiliate $event = new Am_Event(Bootstrap_Aff::AFF_FIND_AFFILIATE, array('invoice' => $invoice, 'payment' => $payment)); $event->setReturn($aff_id); $this->getDi()->hook->call($event); $aff_id = $event->getReturn(); if (empty($aff_id)) { return; } // no affiliate id registered if ($aff_id == $invoice->getUser()->pk()) { return; } //strange situation // load affiliate and continue $aff = $this->getDi()->userTable->load($aff_id, false); if (!$aff || !$aff->is_affiliate) { return; } // affiliate not found $user = $invoice->getUser(); if (!$user->aff_id) { $user->aff_id = $aff->pk(); $user->aff_added = sqlTime('now'); $user->data()->set('aff-source', 'invoice-' . $invoice->pk()); $user->save(); } // try to load other tier affiliate $aff_tier = $aff; $aff_tiers = array(); $aff_tiers_exists = array($aff->pk()); for ($tier = 1; $tier <= $this->getMaxTier(); $tier++) { if (!$aff_tier->aff_id || $aff_tier->pk() == $invoice->getUser()->pk()) { break; } $aff_tier = $this->getDi()->userTable->load($aff_tier->aff_id, false); if (!$aff_tier || !$aff_tier->is_affiliate || $aff_tier->pk() == $invoice->getUser()->pk() || in_array($aff_tier->pk(), $aff_tiers_exists)) { //already in chain break; } $aff_tiers[$tier] = $aff_tier; $aff_tiers_exists[] = $aff_tier->pk(); } $isFirst = !$payment || $payment->isFirst(); //to define price field $paymentNumber = is_null($payment) ? 0 : $invoice->getPaymentsCount(); if (!$payment) { $tax = 0; } else { $tax = $this->getDi()->config->get('aff.commission_include_tax', false) ? 0 : doubleval($payment->tax); } $amount = $payment ? $payment->amount - $tax : 0; $date = $payment ? $payment->dattm : 'now'; // now calculate commissions $items = is_null($payment) ? array_slice($invoice->getItems(), 0, 1) : $invoice->getItems(); foreach ($items as $item) { //we do not calculate commission for free items in invoice $prefix = $isFirst ? 'first' : 'second'; if (!is_null($payment) && !(double) $item->get("{$prefix}_total")) { continue; } $comm = $this->getDi()->affCommissionRecord; $comm->date = sqlDate($date); $comm->record_type = AffCommission::COMMISSION; $comm->invoice_id = $invoice->invoice_id; $comm->invoice_item_id = $item->invoice_item_id; $comm->invoice_payment_id = $payment ? $payment->pk() : null; $comm->receipt_id = $payment ? $payment->receipt_id : null; $comm->product_id = $item->item_id; $comm->is_first = $paymentNumber <= 1; $comm->_setPayment($payment); $comm->_setInvoice($invoice); $comm_tier = clone $comm; $rules = array(); $topay_this = $topay = $this->calculate($invoice, $item, $aff, $paymentNumber, 0, $amount, $date, $rules); if ($topay > 0) { $comm->aff_id = $aff->pk(); $comm->amount = $topay; $comm->tier = 0; $comm->_setAff($aff); $comm->insert(); $comm->setCommissionRules(array_map(create_function('$el', 'return $el->pk();'), $rules)); } foreach ($aff_tiers as $tier => $aff_tier) { $rules = array(); $topay_this = $this->calculate($invoice, $item, $aff_tier, $paymentNumber, $tier, $topay_this, $date, $rules); if ($topay_this > 0) { $comm_this = clone $comm_tier; $comm_this->aff_id = $aff_tier->pk(); $comm_this->amount = $topay_this; $comm_this->tier = $tier; $comm_this->_setAff($aff_tier); $comm_this->insert(); $comm_this->setCommissionRules(array_map(create_function('$el', 'return $el->pk();'), $rules)); } } } }
public function calculate(Invoice $invoiceBill) { foreach ($invoiceBill->getItems() as $item) { $item->_calculateTotal(); } }
function getSaleCode(Invoice $invoice, InvoicePayment $payment) { if ($this->getDi()->config->get('analytics_version', 'google') == 'universal') { $out = <<<CUT <script type="text/javascript"> ga('create', '{$this->id}', 'auto'); ga('send', 'pageview'); </script> CUT; } else { $out = <<<CUT <script type="text/javascript"> if (typeof(_gaq)=='object') { // sometimes google-analytics can be blocked and we will avoid error _gaq.push(['_setAccount', '{$this->id}']); _gaq.push(['_trackPageview']); } </script> CUT; } if (empty($payment->amount) && !$this->getDi()->config->get('google_analytics_track_free_signups')) { return $out; } elseif (empty($payment->amount)) { $a = array($invoice->public_id, $this->getDi()->config->get('site_title'), 0, 0, 0, $invoice->getCity(), $invoice->getState(), $invoice->getCountry()); } else { $a = array($payment->transaction_id, $this->getDi()->config->get('site_title'), $payment->amount - $payment->tax - $payment->shipping, (double) $payment->tax, (double) $payment->shipping, $invoice->getCity(), $invoice->getState(), $invoice->getCountry()); } $a = implode(",\n", array_map('json_encode', $a)); $items = ""; foreach ($invoice->getItems() as $item) { if ($this->getDi()->config->get('analytics_version', 'google') == 'universal') { $it = json_encode(array('id' => $payment->transaction_id, 'name' => $item->item_title, 'sku' => $item->item_id, 'price' => moneyRound($item->first_total / $item->qty), 'quantity' => $item->qty)); $items .= "ga('ecommerce:addItem', {$it});\n"; } else { $items .= "['_addItem', '{$payment->transaction_id}', '{$item->item_id}', '{$item->item_title}','', {$item->first_total}, {$item->qty}],"; } } if ($this->getDi()->config->get('analytics_version', 'google') == 'universal') { $tr = json_encode(array('id' => $payment->transaction_id, 'affiliation' => $this->getDi()->config->get("site_title"), 'revenue' => empty($payment->amount) ? 0 : $payment->amount - $payment->tax - $payment->shipping, 'shipping' => empty($payment->amount) ? 0 : $payment->shipping, 'tax' => empty($payment->amount) ? 0 : $payment->tax)); return $out . <<<CUT <script type="text/javascript"> ga('require', 'ecommerce'); ga('ecommerce:addTransaction', {$tr}); {$items} ga('ecommerce:send'); </script> <!-- end of GA code --> CUT; } return $out . <<<CUT <script type="text/javascript"> if (typeof(_gaq)=='object') { // sometimes google-analytics can be blocked and we will avoid error _gaq.push( ['_addTrans', {$a}], {$items} ['_trackTrans'] ); } </script> <!-- end of GA code --> CUT; }
/** * Process invoice and insert necessary commissions for it */ public function processPayment(Invoice $invoice, InvoicePayment $payment) { $user = $invoice->getUser(); if (empty($user->aff_id)) { return; } // no affiliate id registered $aff = $this->getDi()->userTable->load($user->aff_id, false); if (!$aff || !$aff->is_affiliate) { return; } // affiliate not found // try to load second tier affiliate if ($aff->aff_id) { $aff2 = $this->getDi()->userTable->load($aff->aff_id, false); } else { $aff2 = null; } $isFirst = !$payment || $payment->isFirst(); $amount = $payment ? $payment->amount : 0; $date = $payment ? $payment->dattm : 'now'; // now calculate commissions foreach ($invoice->getItems() as $item) { $comm = $this->getDi()->affCommissionRecord; $comm->date = sqlDate($date); $comm->record_type = AffCommission::COMMISSION; $comm->invoice_id = $invoice->invoice_id; $comm->invoice_payment_id = $payment ? $payment->pk() : null; $comm->receipt_id = $payment ? $payment->receipt_id : null; $comm->product_id = $item->item_id; $comm->is_first = $isFirst; $comm->_setPayment($payment); $comm->_setInvoice($invoice); $comm2 = clone $comm; $topay = $this->calculate($invoice, $item, $aff, $isFirst ? 0 : 1, 0, $amount, $date); if ($topay) { $comm->aff_id = $aff->pk(); $comm->amount = $topay; $comm->tier = 0; $comm->_setAff($aff); $comm->insert(); } if ($aff2) { $topay2 = $this->calculate($invoice, $item, $aff, $isFirst ? 0 : 1, 1, $topay, $date); if ($topay2) { $comm2->aff_id = $aff2->pk(); $comm2->amount = $topay2; $comm2->tier = 1; $comm->_setAff($aff2); $comm2->insert(); } } } }
} if ($_POST['action'] == 'get_employer_info') { $criteria = array('columns' => "employers.id, employers.name, employers.contact_person, employers.email_addr", 'joins' => "employers ON employers.id = invoices.employer", 'match' => "invoices.id = " . $_POST['id'], 'limit' => "1"); $result = Invoice::find($criteria); if ($result === false || is_null($result) || count($result) <= 0) { echo '0'; exit; } $response = array('employer' => $result); header('Content-type: text/xml'); echo $xml_dom->get_xml_from_array($response); exit; } if ($_POST['action'] == 'resend') { $invoice = Invoice::get($_POST['id']); $invoice[0]['items'] = Invoice::getItems($_POST['id']); $employer = new Employer($invoice[0]['employer']); $recipients = $employer->getEmailAddress(); if (isset($_POST['recipients'])) { if (!empty($_POST['recipients'])) { $recipients = str_replace(';', ',', $_POST['recipients']); } } $branch = $employer->getAssociatedBranch(); $sales = 'sales.' . strtolower($branch[0]['country']) . '@yellowelevator.com'; $branch[0]['address'] = str_replace(array("\r\n", "\r"), "\n", $branch[0]['address']); $branch['address_lines'] = explode("\n", $branch[0]['address']); $currency = Currency::getSymbolFromCountryCode($branch[0]['country']); $amount_payable = 0.0; foreach ($invoice[0]['items'] as $i => $item) { $amount_payable += $item['amount'];