public function testSerializeDeserialize() { $a1 = $this->address; $a2 = new ShippingAddress(); $a2->fromJson($a1->toJson()); $this->assertEquals($a1, $a2); }
private function createPayment($details) { $payment = new Payment(); $payer = new Payer(); $payer->payment_method = "paypal"; $amount = new Amount(); $amount->currency = $details['PAYMENTREQUEST_CURRENCYCODE']; $amount->total = $details['PAYMENTREQUEST_AMT']; $transaction = new Transaction(); $transaction->amount = $amount; $transaction->description = $details['PAYMENTREQUEST_DESCRIPTION']; $itemList = new ItemList(); foreach ($details['PAYMENTREQUEST_ITEMS'] as $itemInfo) { $item = new Item(); $item->setQuantity($itemInfo['quantity']); $item->setName($itemInfo['name']); $item->setDescription($itemInfo['description']); $item->setPrice($itemInfo['price']); $item->setCategory($itemInfo['category']); $item->setCurrency($itemInfo['currency']); $item->setTax($itemInfo['tax']); $item->setSku($itemInfo['sku']); $itemList->addItem($item); } $addressInfo = $details['PAYMENTREQUEST_SHIPPING_ADDRESS']; $shippingAddress = new ShippingAddress(); $shippingAddress->setRecipientName($addressInfo['recipient_name']); $shippingAddress->setLine1($addressInfo['line1']); $shippingAddress->setPostalCode($addressInfo['postal_code']); $shippingAddress->setCity($addressInfo['city']); $shippingAddress->setCountryCode($addressInfo['country_code']); $itemList->setShippingAddress($shippingAddress); $transaction->setItemList($itemList); $redirectUrls = new RedirectUrls(); $redirectUrls->return_url = $details['RETURN_URL']; $redirectUrls->cancel_url = $details['CANCEL_URL']; $payment->intent = "sale"; $payment->payer = $payer; $payment->redirect_urls = $redirectUrls; $payment->transactions = [$transaction]; if (false == isset($details['response']) && false == isset($details['response']['state']) && isset($payment->payer->payment_method) && 'paypal' == $payment->payer->payment_method) { $paymentResponse = $payment->create($this->api); $details->replace(['response' => $paymentResponse->toArray()]); foreach ($paymentResponse->links as $link) { if ($link->rel == 'approval_url') { $details->replace(['approval_url' => $link->href]); } } } }
// Please note that the plan Id should be only set in this case. $plan = new Plan(); $plan->setId($createdPlan->getId()); $agreement->setPlan($plan); // Add Payer $payer = new Payer(); $payer->setPaymentMethod('credit_card')->setPayerInfo(new PayerInfo(array('email' => '*****@*****.**'))); // Add Credit Card to Funding Instruments $creditCard = new CreditCard(); $creditCard->setType('visa')->setNumber('4491759698858890')->setExpireMonth('12')->setExpireYear('2017')->setCvv2('128'); $fundingInstrument = new FundingInstrument(); $fundingInstrument->setCreditCard($creditCard); $payer->setFundingInstruments(array($fundingInstrument)); //Add Payer to Agreement $agreement->setPayer($payer); // Add Shipping Address $shippingAddress = new ShippingAddress(); $shippingAddress->setLine1('111 First Street')->setCity('Saratoga')->setState('CA')->setPostalCode('95070')->setCountryCode('US'); $agreement->setShippingAddress($shippingAddress); // For Sample Purposes Only. $request = clone $agreement; // ### Create Agreement try { // Please note that as the agreement has not yet activated, we wont be receiving the ID just yet. $agreement = $agreement->create($apiContext); } catch (Exception $ex) { ResultPrinter::printError("Created Billing Agreement.", "Agreement", $agreement->getId(), $request, $ex); exit(1); } ResultPrinter::printResult("Created Billing Agreement.", "Agreement", $agreement->getId(), $request, $agreement); return $agreement;
/** * @depends testSerializationDeserialization * @param ShippingAddress $obj */ public function testGetters($obj) { $this->assertEquals($obj->getId(), "TestSample"); $this->assertEquals($obj->getRecipientName(), "TestSample"); $this->assertEquals($obj->getDefaultAddress(), true); }
function complete_cart($order_exists = true) { global $insert_id; // check $check_query = xtc_db_query("SELECT * \n FROM " . TABLE_PAYPAL_PAYMENT . "\n WHERE payment_id = '" . xtc_db_input($_SESSION['paypal']['paymentId']) . "'"); if (xtc_db_num_rows($check_query) > 0) { $status_id = $this->order_status_tmp; if ($status_id < 0) { $check_query = xtc_db_query("SELECT orders_status\n FROM " . TABLE_ORDERS . " \n WHERE orders_id = '" . (int) $insert_id . "'"); $check = xtc_db_fetch_array($check_query); $status_id = $check['orders_status']; } $this->update_order('duplicate call, cancel', $status_id, $insert_id); return; } // auth $apiContext = $this->apiContext(); try { // Get the payment Object by passing paymentId $payment = Payment::get($_SESSION['paypal']['paymentId'], $apiContext); } catch (Exception $ex) { $this->LoggingManager->log(print_r($ex, true), 'DEBUG'); $this->remove_order($insert_id); unset($_SESSION['paypal']); unset($_SESSION['tmp_oID']); xtc_redirect(xtc_href_link(FILENAME_SHOPPING_CART, 'payment_error=' . $this->code, 'NONSSL')); } // set order $order = new order($insert_id); $patches_array = array(); $patchRequest = new PatchRequest(); $payment_address = new Address(); $payment_address->setLine1($this->encode_utf8($order->billing['street_address']))->setCity($this->encode_utf8($order->billing['city']))->setState($this->encode_utf8($order->billing['state'] != '' ? xtc_get_zone_code($order->billing['country_id'], $order->billing['zone_id'], $order->billing['state']) : ''))->setPostalCode($this->encode_utf8($order->billing['postcode']))->setCountryCode($this->encode_utf8(isset($order->billing['country_iso_2']) ? $order->billing['country_iso_2'] : $order->billing['country']['iso_code_2'])); if ($order->billing['suburb'] != '') { $payment_address->setLine2($this->encode_utf8($order->billing['suburb'])); } $patch_payment = new Patch(); $patch_payment->setOp('add')->setPath('/potential_payer_info/billing_address')->setValue($payment_address); $patches_array[] = $patch_payment; // set address $shipping_address = new ShippingAddress(); $shipping_address->setRecipientName($this->encode_utf8($order->delivery['firstname'] . ' ' . $order->delivery['lastname']))->setLine1($this->encode_utf8($order->delivery['street_address']))->setCity($this->encode_utf8($order->delivery['city']))->setCountryCode($this->encode_utf8(isset($order->delivery['country_iso_2']) ? $order->delivery['country_iso_2'] : $order->delivery['country']['iso_code_2']))->setPostalCode($this->encode_utf8($order->delivery['postcode']))->setState($this->encode_utf8($order->delivery['state'] != '' ? xtc_get_zone_code($order->delivery['country_id'], $order->delivery['zone_id'], $order->delivery['state']) : '')); if ($order->delivery['suburb'] != '') { $shipping_address->setLine2($this->encode_utf8($order->delivery['suburb'])); } $patch_shipping = new Patch(); $patch_shipping->setOp('add')->setPath('/transactions/0/item_list/shipping_address')->setValue($shipping_address); $patches_array[] = $patch_shipping; $patch_invoice = new Patch(); $patch_invoice->setOp('replace')->setPath('/transactions/0/invoice_number')->setValue($this->get_config('PAYPAL_CONFIG_INVOICE_PREFIX') . $insert_id); $patches_array[] = $patch_invoice; // set details $this->details = new Details(); // set amount $this->amount = new Amount(); // set totals $this->get_totals($order->totals); $this->amount->setCurrency($order->info['currency'])->setDetails($this->details); $patch_amount = new Patch(); $patch_amount->setOp('replace')->setPath('/transactions/0/amount')->setValue($this->amount); $patches_array[] = $patch_amount; // set ItemList if ($this->get_config('PAYPAL_ADD_CART_DETAILS') == '0' || $this->check_discount() === true) { $item = array(); $item[0] = new Item(); $item[0]->setName($this->encode_utf8(MODULE_PAYMENT_PAYPAL_TEXT_ORDER))->setCurrency($order->info['currency'])->setQuantity(1)->setPrice($this->details->getSubtotal()); } else { for ($i = 0, $n = sizeof($order->products); $i < $n; $i++) { $item[$i] = new Item(); $item[$i]->setName($this->encode_utf8($order->products[$i]['name']))->setCurrency($order->info['currency'])->setQuantity($order->products[$i]['qty'])->setPrice($order->products[$i]['price'])->setSku($order->products[$i]['model'] != '' ? $order->products[$i]['model'] : $order->products[$i]['id']); } } $patch_items = new Patch(); $patch_items->setOp('replace')->setPath('/transactions/0/item_list/items')->setValue($item); $patches_array[] = $patch_items; $patchRequest->setPatches($patches_array); try { // update payment $payment->update($patchRequest, $apiContext); } catch (Exception $ex) { $this->LoggingManager->log(print_r($ex, true), 'DEBUG'); if ($order_exists === false) { unset($_SESSION['paypal']); xtc_redirect(xtc_href_link(FILENAME_CHECKOUT_PAYMENT, 'payment_error=' . $this->code, 'SSL')); } $this->remove_order($insert_id); unset($_SESSION['paypal']); unset($_SESSION['tmp_oID']); xtc_redirect(xtc_href_link(FILENAME_SHOPPING_CART, 'payment_error=' . $this->code, 'NONSSL')); } $payment = Payment::get($_SESSION['paypal']['paymentId'], $apiContext); // PaymentExecution $execution = new PaymentExecution(); $execution->setPayerId($_SESSION['paypal']['PayerID']); try { // Execute the payment $payment->execute($execution, $apiContext); } catch (Exception $ex) { $this->LoggingManager->log(print_r($ex, true), 'DEBUG'); $this->remove_order($insert_id); unset($_SESSION['paypal']); unset($_SESSION['tmp_oID']); xtc_redirect(xtc_href_link(FILENAME_SHOPPING_CART, 'payment_error=' . $this->code, 'NONSSL')); } // capture if (($this->transaction_type == 'order' || $this->transaction_type == 'authorize') && $this->get_config('PAYPAL_CAPTURE_MANUELL') == '0') { $this->capture_payment($payment); } $sql_data_array = array('orders_id' => $insert_id, 'payment_id' => $_SESSION['paypal']['paymentId'], 'payer_id' => $_SESSION['paypal']['PayerID']); xtc_db_perform(TABLE_PAYPAL_PAYMENT, $sql_data_array); try { // Get the payment Object by passing paymentId $payment = Payment::get($_SESSION['paypal']['paymentId'], $apiContext); } catch (Exception $ex) { $this->LoggingManager->log(print_r($ex, true), 'DEBUG'); $this->remove_order($insert_id); unset($_SESSION['paypal']); unset($_SESSION['tmp_oID']); xtc_redirect(xtc_href_link(FILENAME_SHOPPING_CART, 'payment_error=' . $this->code, 'NONSSL')); } $status = $this->get_orders_status($payment); if ($status['status_id'] < 0) { $check_query = xtc_db_query("SELECT orders_status\n FROM " . TABLE_ORDERS . " \n WHERE orders_id = '" . (int) $insert_id . "'"); $check = xtc_db_fetch_array($check_query); $status['status_id'] = $check['orders_status']; } $this->update_order($status['comment'], $status['status_id'], $insert_id); }
/** * @return Transaction */ private function buildTransaction() { $clientInfo = ClientHelper::getClientInfo(); $priceIncludesTax = $clientInfo->business_settings->tax->price_includes_tax; $paypalItems = []; $subTotal = 0; foreach ($this->order->getItems() as $item) { /* @var $item OrderItem */ // don't add shipping row if ($item->isShipping()) { continue; } $subTotal += $item->getPrice(); $newItem = new Item(); $newItem->setName($item->getProductName())->setCurrency($clientInfo->currency->currency_iso)->setQuantity($item->getQuantity())->setSku($item->getProductSku())->setPrice($item->getPrice() / 100); $paypalItems[] = $newItem; } $shippingBeforeTax = $this->order->getShipping() / 100; $tax = $this->order->getTax() / 100; $subTotal = $subTotal / 100; $total = $this->order->getTotalPrice() / 100; $orderShippingAddress = $this->order->getShippingAddress()->getArray(); $shippingAddress = new ShippingAddress(); $shippingAddress->setCity($orderShippingAddress['city']); $shippingAddress->setCountryCode(CountryHelper::getCountryCode($orderShippingAddress['countryId'])); $shippingAddress->setPostalCode($orderShippingAddress['postcode']); $shippingAddress->setLine1($orderShippingAddress['address1']); $shippingAddress->setState($orderShippingAddress['state']); $shippingAddress->setRecipientName($this->order->getCustomer()->fullName()); $itemList = new ItemList(); if (!$priceIncludesTax) { $itemList->setItems($paypalItems); } $itemList->setShippingAddress($shippingAddress); $details = new Details(); $details->setShipping($shippingBeforeTax)->setTax($tax)->setSubtotal($subTotal); $amount = new Amount(); $amount->setCurrency($clientInfo->currency->currency_iso)->setTotal($total)->setDetails($details); $transaction = new Transaction(); $transaction->setAmount($amount)->setItemList($itemList)->setDescription("Order from " . $clientInfo->name)->setInvoiceNumber($this->order->getId()); return $transaction; }
public function postPayment(Request $request) { $payer = new Payer(); $payer->setPaymentMethod('paypal'); $item_listArr = []; $totalAmount = 0; if ($request->session()->has('member')) { $memberID = $request->session()->get('member'); $memberInfo = DB::select("select * from members where email = '{$memberID}'")[0]; $shoppingCart = DB::select("select * from shopping_cart where member_id = '{$memberID}'")[0]->shopping_cart; $shoppingCart = json_decode($shoppingCart, true); if (sizeof($shoppingCart) == 0) { return Redirect::to('/shoppingCart'); } $shoppingCartItemsFinal = DB::table('products')->whereIn('product_id', array_keys($shoppingCart))->get(); foreach ($shoppingCartItemsFinal as $key => $value) { $value->num = $shoppingCart[$value->product_id]; $priceList = json_decode($value->price, true); $eachPrice = $value->single_price; krsort($priceList); foreach ($priceList as $packageNum => $price) { if ($value->num >= $packageNum) { $eachPrice = $price; break; } } $value->eachPrice = $eachPrice; $item = new Item(); $item->setName($value->name)->setCurrency('AUD')->setQuantity($value->num * 1)->setPrice($eachPrice); // unit price array_push($item_listArr, $item); $totalAmount += $eachPrice * $value->num; } } else { $shoppingCart = json_decode($request->cookie('shoppingCart'), true); if (sizeof($shoppingCart) == 0) { return Redirect::to('/shoppingCart'); } $shoppingCartItemsFinal = DB::table('products')->whereIn('product_id', array_keys($shoppingCart))->get(); foreach ($shoppingCartItemsFinal as $key => $value) { $value->num = $shoppingCart[$value->product_id]; $priceList = json_decode($value->price, true); $eachPrice = $value->single_price; krsort($priceList); foreach ($priceList as $packageNum => $price) { if ($value->num >= $packageNum) { $eachPrice = $price; break; } } $value->eachPrice = $eachPrice; $item = new Item(); $item->setName($value->name)->setCurrency('AUD')->setQuantity($value->num * 1)->setPrice($eachPrice); // unit price array_push($item_listArr, $item); $totalAmount += $eachPrice * $value->num; } } $item_list = new ItemList(); $item_list->setItems($item_listArr); $shipping_address = new ShippingAddress(); $payerInfo = Session::get('payment_shopping_payer_info'); $shipping_address->setCountryCode('AU'); $shipping_address->setCity($payerInfo['suburb']); $shipping_address->setPostalCode($payerInfo['postcode']); $shipping_address->setLine1($payerInfo['address']); $shipping_address->setState($payerInfo['state']); $shipping_address->setRecipientName($payerInfo['name']); $item_list->setShippingAddress($shipping_address); $amount = new Amount(); $amount->setCurrency('AUD')->setTotal($totalAmount); $transaction = new Transaction(); $transaction->setAmount($amount)->setItemList($item_list)->setDescription('Your transaction description'); $redirect_urls = new RedirectUrls(); $redirect_urls->setReturnUrl(URL::route('payment.status'))->setCancelUrl(URL::route('payment.status')); $payment = new Payment(); $payment->setIntent('Sale')->setPayer($payer)->setRedirectUrls($redirect_urls)->setTransactions(array($transaction)); try { $payment->create($this->_api_context); } catch (\PayPal\Exception\PPConnectionException $ex) { if (\Config::get('app.debug')) { echo "Exception: " . $ex->getMessage() . PHP_EOL; $err_data = json_decode($ex->getData(), true); exit; } else { die('Some error occur, sorry for inconvenient'); } } foreach ($payment->getLinks() as $link) { if ($link->getRel() == 'approval_url') { $redirect_url = $link->getHref(); break; } } // add payment ID to session Session::put('paypal_payment_id', $payment->getId()); if (isset($redirect_url)) { // redirect to paypal return Redirect::away($redirect_url); } else { return Redirect::to('/check-out'); // return Redirect::route('original.route')->with('error', 'Unknown error occurred'); } }
function generateShippingAddress($addressee, $address) { $address = new ShippingAddress(); $address->setRecipientName($addressee); $address->setLine1($address->line1); $address->setLine2($address->line2); $address->setCity($address->city); $address->setState($address->province->name); $address->setCountryCode($address->country->name); $address->setPostalCode($address->zip); return $address; }