Step 3 - Shipping method
 @route GET /checkout/shipping/json
167053
def shipping_json
      render :json => { :error => 'Not logged in.'          } and return if !logged_in?
      render :json => { :error => 'No shippable items.'     } and return if !@invoice.has_shippable_items?
      render :json => { :error => 'Empty shipping address.' } and return if @invoice.shipping_address.nil?      
      
      @invoice.calculate
      
      #ops = @invoice.invoice_packages      
      #if params[:recalculate_invoice_packages] || ops.count == 0
      #  # Remove any invoice packages      
      #  LineItem.where(:invoice_id => @invoice.id).update_all(:invoice_package_id => nil)
      #  InvoicePackage.where(:invoice_id => @invoice.id).destroy_all      
      #    
      #  # Calculate what shipping packages we'll need            
      #  InvoicePackage.create_for_invoice(@invoice)
      #end

      # Now get the rates for those packages            
      rates = ShippingCalculator.rates(@invoice)      
      render :json => rates                  
    end
1350141
public function route()
	{
		$content = $this->_controller->{$this->_actionMethod}();

		if ($this->_controller->isJson()) {
			Request::setHeader(Request::HEADER_JSON);
			echo json_encode($content);
		} else {
			echo $content;
		}
	}
717938
def admin_update
      return if !user_is_allowed('orders', 'edit')
      
      resp = Caboose::StdClass.new({'attributes' => {}})
      order = Order.find(params[:id])    
      
      save = true    
      params.each do |name,value|
        case name
          when 'tax'
            order.tax = value          
          when 'shipping'
            order.shipping = value
          when 'handling'
            order.handling = value
          when 'discount'
            order.discount = value        
          when 'status'
            order.status = value
            resp.attributes['status'] = {'text' => value}
        end
      end
      order.calculate_total    
      resp.success = save && order.save
      render :json => resp
    end
553871
public function getJson()
    {
        $response = [
            'status' => $this->status,
        ];

        switch ($this->status) {
            case self::STATUS_SUCCESS:
            case self::STATUS_FAIL:
                $response = array_merge(
                    $response,
                    [
                        'data' => $this->data,
                    ]
                );
                break;
            case self::STATUS_ERROR;
                $code     = $this->code ? ['code' => $this->code] : [];
                $data     = $this->data ? ['data' => $this->data] : [];
                $response = array_merge(
                    $response,
                    [
                        'message' => $this->message,
                    ],
                    $code,
                    $data
                );
                break;
            default:
                // because of the check in setStatus, this should never occur
                $response = [
                    'status'  => self::STATUS_ERROR,
                    'code'    => 500,
                    'message' => 'JSend response was built illegally',
                    'data'    => [
                        'original-data' => [
                            'status'  => $this->status,
                            'code'    => $this->code,
                            'message' => $this->message,
                            'data'    => $this->data,
                        ],
                    ],
                ];
                break;
        }

        return json_encode($response);
    }
56591
public function deliveryInfoAction(Request $request)
    {
        if (!$this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
            return $this->redirect($this->generateUrl('index'));
        }
        
        /** @var CheckoutManager $checkoutManager */
        $checkoutManager = $this->get('checkout_manager');
        //ere create a transaction
        $checkoutManager->updateTransaction();
        
        $transaction = $checkoutManager->getCurrentTransaction();
        $delivery = $checkoutManager->getDelivery($transaction);

        $options = array(
            'securityContext' =>  $this->get('security.token_storage'),
            'manager' => $this->get('doctrine')->getManager(), 
            'session' => $this->get('session')
        );
                
        $form = $this->createForm(DeliveryType::class, $delivery, $options);

        if ($request->isMethod('POST')) {
            $form->handleRequest($request);

            if ($form->isValid()) {
                $cart = $this->getCurrentCart();
                $this->get('checkout_manager')->saveDelivery($delivery, $request->get('delivery'), $cart);

                $url = $this->container->get('router')->generate('ecommerce_checkout_summary');

                return new RedirectResponse($url);
            }
        }

        return array(
            'form' => $form->createView(),
        );
    }
180123
public function process()
	{
		$view = $this->getView();
		$context = $this->getContext();

		if( $view->param( 'c_step' ) !== 'process'
			|| $view->get( 'standardErrorList', [] ) !== []
			|| $view->get( 'standardStepActive' ) !== null
		) {
			return;
		}

		try
		{
			$orderCntl = \Aimeos\Controller\Frontend::create( $context, 'order' );
			$basketCntl = \Aimeos\Controller\Frontend::create( $context, 'basket' );


			if ( $view->param( 'cs_order', null ) !== null )
			{
				parent::process();

				$basket = $basketCntl->store();
				$orderItem = $orderCntl->add( $basket->getId(), ['order.type' => 'web'] )->store();

				$context->getSession()->set( 'aimeos/orderid', $orderItem->getId() );
			}
			elseif ( $view->param( 'cp_payment', null ) !== null )
			{
				$parts = \Aimeos\MShop\Order\Item\Base\Base::PARTS_ALL;
				$orderItem = $orderCntl->get( $context->getSession()->get( 'aimeos/orderid' ), false );
				$basket = $basketCntl->load( $orderItem->getBaseId(), $parts, false );
			}
			else
			{
				return;
			}

			$total = $basket->getPrice()->getValue() + $basket->getPrice()->getCosts();
			$services = $basket->getService( \Aimeos\MShop\Order\Item\Base\Service\Base::TYPE_PAYMENT );

			if( $services === [] || $total <= 0 && $this->isSubscription( $basket->getProducts() ) === false )
			{
				$orderCntl->save( $orderItem->setPaymentStatus( \Aimeos\MShop\Order\Item\Base::PAY_AUTHORIZED ) );
			}
			elseif( ( $form = $this->processPayment( $basket, $orderItem ) ) !== null )
			{
				$view->standardUrlNext = $form->getUrl();
				$view->standardMethod = $form->getMethod();
				$view->standardProcessParams = $form->getValues();
				$view->standardUrlExternal = $form->getExternal();
				$view->standardHtml = $form->getHtml();

				return;
			}

			$view->standardUrlNext = $this->getUrlConfirm( $view, [], [] );
			$view->standardMethod = 'POST';
		}
		catch( \Aimeos\Client\Html\Exception $e )
		{
			$error = array( $context->getI18n()->dt( 'client', $e->getMessage() ) );
			$view->standardErrorList = $view->get( 'standardErrorList', [] ) + $error;
		}
		catch( \Aimeos\Controller\Frontend\Exception $e )
		{
			$error = array( $context->getI18n()->dt( 'controller/frontend', $e->getMessage() ) );
			$view->standardErrorList = $view->get( 'standardErrorList', [] ) + $error;
		}
		catch( \Aimeos\MShop\Exception $e )
		{
			$error = array( $context->getI18n()->dt( 'mshop', $e->getMessage() ) );
			$view->standardErrorList = $view->get( 'standardErrorList', [] ) + $error;
		}
		catch( \Exception $e )
		{
			$error = array( $context->getI18n()->dt( 'client', 'A non-recoverable error occured' ) );
			$view->standardErrorList = $view->get( 'standardErrorList', [] ) + $error;
			$this->logException( $e );
		}
	}
257421
function shipping($module = '') {
    global $PHP_SELF, $messageStack;

    if (defined('MODULE_SHIPPING_INSTALLED') && zen_not_null(MODULE_SHIPPING_INSTALLED)) {
      $this->modules = explode(';', MODULE_SHIPPING_INSTALLED);

      $include_modules = array();

      if ( (zen_not_null($module)) && is_array($module) && (in_array(substr($module['id'], 0, strpos($module['id'], '_')) . '.' . substr($PHP_SELF, (strrpos($PHP_SELF, '.')+1)), $this->modules)) ) {
        $include_modules[] = array('class' => substr($module['id'], 0, strpos($module['id'], '_')), 'file' => substr($module['id'], 0, strpos($module['id'], '_')) . '.' . substr($PHP_SELF, (strrpos($PHP_SELF, '.')+1)));
      } else {
        reset($this->modules);
        while (list(, $value) = each($this->modules)) {
          $class = substr($value, 0, strrpos($value, '.'));
          $include_modules[] = array('class' => $class, 'file' => $value);
        }
      }

      for ($i=0, $n=sizeof($include_modules); $i<$n; $i++) {
        //          include(DIR_WS_LANGUAGES . $_SESSION['language'] . '/modules/shipping/' . $include_modules[$i]['file']);
        $lang_file = zen_get_file_directory(DIR_WS_LANGUAGES . $_SESSION['language'] . '/modules/shipping/', $include_modules[$i]['file'], 'false');
        if (@file_exists($lang_file)) {
          include_once($lang_file);
        } else {
          if (IS_ADMIN_FLAG === false && is_object($messageStack)) {
            $messageStack->add('checkout_shipping', WARNING_COULD_NOT_LOCATE_LANG_FILE . $lang_file, 'caution');
          } else {
            $messageStack->add_session(WARNING_COULD_NOT_LOCATE_LANG_FILE . $lang_file, 'caution');
          }
        }
        $this->enabled = TRUE;
        $this->notify('NOTIFY_SHIPPING_MODULE_ENABLE', $include_modules[$i]['class']);
        if ($this->enabled)
        {
          include_once(DIR_WS_MODULES . 'shipping/' . $include_modules[$i]['file']);
          $GLOBALS[$include_modules[$i]['class']] = new $include_modules[$i]['class'];
        }
      }
    }
  }
789431
public function shipmentAction(Request $request)
    {
        if (null !== $redirect = $this->validateStep('shipment')) {
            return $redirect;
        }

        $cart = $this->getCart();

        // Go to payment page if no shipment required
        if (!$cart->requiresShipment()) {
            return $this->redirect($this->generateUrl('ekyna_cart_payment'));
        }

        /* TODO
        $form = $this->createForm('ekyna_cart_shipment', $cart);

        $form->handleRequest($request);
        if ($form->isValid()) {
            $event = new OrderEvent($cart);
            $this->getDispatcher()->dispatch(OrderEvents::CONTENT_CHANGE, $event);
            if (!$event->isPropagationStopped()) {
                return $this->redirect($this->generateUrl('ekyna_cart_payment'));
            } else {
                $event->toFlashes($this->getFlashBag());
            }
            return $this->redirect($this->generateUrl('ekyna_cart_shipment'));
        }*/

        return $this->render('EkynaCartBundle:Cart:shipment.html.twig', [
//           'form' => $form->createView(),
//           'cart' => $cart,
//         	 'user' => $user,
        ]);
    }
282349
function () {
        var json = ItemGroup.prototype.toJSON.apply(this);

        // move ids and stuff from root level to `info` object
        json.info = {
            _postman_id: this.id,
            name: this.name,
            version: this.version,
            schema: SCHEMA_URL
        };

        delete json.id;
        delete json.name;
        delete json.version;

        if (json.hasOwnProperty('description')) {
            json.info.description = this.description;
            delete json.description;
        }

        return json;
    }
299664
final function action() {return $this->_m->action(function() {
		$m = $this->_m; /** @var M $m */
		$this->preorder();
		$p = $this->redirectParams(); /** @var array(string => mixed) $p */
		if ($url = dfp_url_api($m, $this->redirectUrl())) { /** @var string|null $url */
			PO::setRedirectData($m, $url, $p, $this->forceGet());
			// 2016-12-20
			if ($this->s()->log()) {
				dfp_report($m, ['Redirect Params' => $p, 'Redirect URL' => $url], 'request');
			}
			// 2016-05-06
			// Postpone sending an order confirmation email to the customer,
			// because the customer should pass 3D Secure validation first.
			// «How is a confirmation email sent on an order placement?» https://mage2.pro/t/1542
			$this->oq()->setCanSendNewEmailFlag(false);
		}
		/**
		 * 2017-03-26
		 * Stripe-подобные платёжные модули типа Omise
		 * (и в перспективе, после надлежащего рефакторинга — Checkout.com),
		 * осуществляют проверку 3D Secure с перенаправлением браузера.
		 * Они записывают первичную транзакцию в методе @see \Df\StripeClone\Method::chargeNew()
		 * https://github.com/mage2pro/core/blob/2.4.0/StripeClone/Method.php#L117-L164
		 * В этом случае мы не попадаем в расположенную ниже ветку,
		 * потому что @uses transId() по умолчанию возвращает null,
		 * а указанные модули этот метод намеренно не перекрывают.
		 * 2017-03-29
		 * Транзакция может записываться и без перенаправления:
		 * например, при выборе опции Bank Transfer модуля Kassa Compleet.
		 */
		if ($id = $this->transId() /** @var string|null $id */) {
			$result = null;
			$m->ii()->setTransactionId($id); // 2016-07-10 Сохраняем информацию о транзакции.
			if (!$this->forceGet()) {
				/**
				 * 2017-03-26
				 * Некоторые модули (Ginger Payments, Kassa Compleet, QIWI Wallet) перенаправляют покупателя
				 * на платёжную страницу ПС без параметров POST: они передают параметры через URL.
				 * В этом случае данный вызов @uses \Df\Payment\Method::iiaSetTRR()
				 * безвреден (он ничего не сделает), а параметры запроса сохраняются в транзакции
				 * каким-то другим методом, например:
				 * @see \Df\GingerPaymentsBase\Init\Action::req()
				 * @see \Df\GingerPaymentsBase\Init\Action::res()
				 * @see \Dfe\Qiwi\Init\Action::preorder()
				 */
				$m->iiaSetTRR($p);
			}
			/**
			 * 2016-07-10
			 * @uses \Magento\Sales\Model\Order\Payment\Transaction::TYPE_PAYMENT —
			 * это единственный транзакция без специального назначения,
			 * и поэтому мы можем безопасно его использовать
			 * для сохранения информации о нашем запросе к платёжной системе.
			 */
			$m->ii()->addTransaction(T::TYPE_PAYMENT);
		}
		/**
		 * 2017-11-11
		 * We return `null` in the redirection case.
		 * The result of this method will be returned
		 * by the @used-by \Df\Payment\Method::getConfigPaymentAction() method
		 * to the @used-by \Magento\Sales\Model\Order\Payment::place() method:
		 *		$orderState = Order::STATE_NEW;
		 *		$orderStatus = $methodInstance->getConfigData('order_status');
		 *		<...>
		 *		$action = $methodInstance->getConfigPaymentAction();
		 *		if ($action) {
		 *			if ($methodInstance->isInitializeNeeded()) {
		 *				$stateObject = new \Magento\Framework\DataObject();
		 *				// For method initialization we have to use original config value for payment action
		 *				$methodInstance->initialize(
		 * 					$methodInstance->getConfigData('payment_action'), $stateObject
		 * 				);
		 *				$orderState = $stateObject->getData('state') ?: $orderState;
		 *				$orderStatus = $stateObject->getData('status') ?: $orderStatus;
		 *				$isCustomerNotified = $stateObject->hasData('is_notified')
		 *					? $stateObject->getData('is_notified')
		 *					: $isCustomerNotified;
		 *			} else {
		 *				$orderState = Order::STATE_PROCESSING;
		 *				$this->processAction($action, $order);
		 *				$orderState = $order->getState() ? $order->getState() : $orderState;
		 *				$orderStatus = $order->getStatus() ? $order->getStatus() : $orderStatus;
		 *			}
		 *		} else {
		 *			$order->setState($orderState)
		 *				->setStatus($orderStatus);
		 *		}
		 * This code is the same in Magento 2.0.0 - 2.2.1:
		 * https://github.com/magento/magento2/blob/2.0.0/app/code/Magento/Sales/Model/Order/Payment.php#L316-L343
		 * https://github.com/magento/magento2/blob/2.2.1/app/code/Magento/Sales/Model/Order/Payment.php#L348-L375
		 * As you can see, if $action is `null`,
		 * then the current order will have the @see \Magento\Sales\Model\Order::STATE_NEW state:
		 * it is what we need in the redirection case.
		 */
		return $url || $id ? null : $this->preconfigured();
	}, false);}
580691
function table() {
    global $order, $db;

    $this->code = 'table';
    $this->title = MODULE_SHIPPING_TABLE_TEXT_TITLE;
    $this->description = MODULE_SHIPPING_TABLE_TEXT_DESCRIPTION;
    $this->sort_order = MODULE_SHIPPING_TABLE_SORT_ORDER;
    $this->icon = '';
    $this->tax_class = MODULE_SHIPPING_TABLE_TAX_CLASS;
    $this->tax_basis = MODULE_SHIPPING_TABLE_TAX_BASIS;
    // disable only when entire cart is free shipping
    if (zen_get_shipping_enabled($this->code)) {
      $this->enabled = ((MODULE_SHIPPING_TABLE_STATUS == 'True') ? true : false);
    }

    if ($this->enabled) {
      // check MODULE_SHIPPING_TABLE_HANDLING_METHOD is in
      $check_query = $db->Execute("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_SHIPPING_TABLE_HANDLING_METHOD'");
      if ($check_query->EOF) {
        $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Handling Per Order or Per Box', 'MODULE_SHIPPING_TABLE_HANDLING_METHOD', 'Order', 'Do you want to charge Handling Fee Per Order or Per Box?', '6', '0', 'zen_cfg_select_option(array(\'Order\', \'Box\'), ', now())");
      }
    }

    if ( ($this->enabled == true) && ((int)MODULE_SHIPPING_TABLE_ZONE > 0) ) {
      $check_flag = false;
      $check = $db->Execute("select zone_id from " . TABLE_ZONES_TO_GEO_ZONES . " where geo_zone_id = '" . MODULE_SHIPPING_TABLE_ZONE . "' and zone_country_id = '" . $order->delivery['country']['id'] . "' order by zone_id");
      while (!$check->EOF) {
        if ($check->fields['zone_id'] < 1) {
          $check_flag = true;
          break;
        } elseif ($check->fields['zone_id'] == $order->delivery['zone_id']) {
          $check_flag = true;
          break;
        }
        $check->MoveNext();
      }

      if ($check_flag == false) {
        $this->enabled = false;
      }
    }
  }
1258851
public function actionIndex()
    {
        $this->requirePostRequest();
        $request = Craft::$app->getRequest();
        $plugin = Plugin::getInstance();
        $settings = $plugin->getSettings();

        $submission = new Submission();
        $submission->fromEmail = $request->getBodyParam('fromEmail');
        $submission->fromName = $request->getBodyParam('fromName');
        $submission->subject = $request->getBodyParam('subject');

        $message = $request->getBodyParam('message');
        if (is_array($message)) {
            $submission->message = array_filter($message, function($value) {
                return $value !== '';
            });
        } else {
            $submission->message = $message;
        }

        if ($settings->allowAttachments && isset($_FILES['attachment']) && isset($_FILES['attachment']['name'])) {
            if (is_array($_FILES['attachment']['name'])) {
                $submission->attachment = UploadedFile::getInstancesByName('attachment');
            } else {
                $submission->attachment = [UploadedFile::getInstanceByName('attachment')];
            }
        }

        if (!$plugin->getMailer()->send($submission)) {
            if ($request->getAcceptsJson()) {
                return $this->asJson(['errors' => $submission->getErrors()]);
            }

            Craft::$app->getSession()->setError(Craft::t('contact-form', 'There was a problem with your submission, please check the form and try again!'));
            Craft::$app->getUrlManager()->setRouteParams([
                'variables' => ['message' => $submission]
            ]);

            return null;
        }

        if ($request->getAcceptsJson()) {
            return $this->asJson(['success' => true]);
        }

        Craft::$app->getSession()->setNotice($settings->successFlashMessage);
        return $this->redirectToPostedUrl($submission);
    }
579327
public function getShipping()
    {
        return new ApiShipping(
            $this->entity->getShipping(),
            $this->locale,
            $this->itemFactory,
            $this->priceFormatter
        );
    }
377218
public function sendHeaders()
    {
        switch ($this->_sOutputFormat) {
            case self::OUTPUT_FORMAT_JSON:
                \OxidEsales\Eshop\Core\Registry::getUtils()->setHeader("Content-Type: application/json; charset=" . $this->_sCharset);
                break;
            case self::OUTPUT_FORMAT_HTML:
            default:
                \OxidEsales\Eshop\Core\Registry::getUtils()->setHeader("Content-Type: text/html; charset=" . $this->_sCharset);
                break;
        }
    }
217339
function api($path, $post_data = array()) {
		// IE: "contact/view"
		$components = explode("/", $path);
		$component = $components[0];

		if (count($components) > 2) {
			// IE: "contact/tag/add?whatever"
			// shift off the first item (the component, IE: "contact").
			array_shift($components);
			// IE: convert to "tag_add?whatever"
			$method_str = implode("_", $components);
			$components = array($component, $method_str);
		}

		if (preg_match("/\?/", $components[1])) {
			// query params appended to method
			// IE: contact/edit?overwrite=0
			$method_arr = explode("?", $components[1]);
			$method = $method_arr[0];
			$params = $method_arr[1];
		}
		else {
			// just a method provided
			// IE: "contact/view
			if ( isset($components[1]) ) {
				$method = $components[1];
				$params = "";
			}
			else {
				return "Invalid method.";
			}
		}

		// adjustments
		if ($component == "list") {
			// reserved word
			$component = "list_";
		}
		elseif ($component == "branding") {
			$component = "design";
		}
		elseif ($component == "sync") {
			$component = "contact";
			$method = "sync";
		}
		elseif ($component == "singlesignon") {
			$component = "auth";
		}

		$class = ucwords($component); // IE: "contact" becomes "Contact"
		$class = "AC_" . $class;
		// IE: new Contact();

		$add_tracking = false;
		if ($class == "AC_Tracking") $add_tracking = true;
		if ($class == "AC_Tags") {
			$class = "AC_Tag";
		}

		$class = new $class($this->version, $this->url_base, $this->url, $this->api_key);

		$class->set_curl_timeout($this->get_curl_timeout());

		if ($add_tracking) {
			$class->track_email = $this->track_email;
			$class->track_actid = $this->track_actid;
			$class->track_key = $this->track_key;
		}

		if ($method == "list") {
			// reserved word
			$method = "list_";
		}

		$class->debug = $this->debug;

		$response = $class->$method($params, $post_data);
		return $response;
	}
334855
public function generatepage_json(){
		$status=200;
		foreach($this->rules as &$c){
			$this->positions[$c->position]=$c->output;
			if($c->status!=200){
				$status=$c->status;
				}
			}
		header('Content-type: text/json');
		if($status==403){
			header($_SERVER['SERVER_PROTOCOL'].' 403 Forbidden');
			}
		if($status==404){
			header($_SERVER['SERVER_PROTOCOL'].' 404 Page Not Found');
			}
		if($status==500){
			header($_SERVER['SERVER_PROTOCOL'].' 500 Server Error!');
			}
		echo $this->positions['content'];	
		}
976678
function () {
        var pkgJson = grunt.file.readJSON("package.json");

        if (pkgJson.jspm && pkgJson.jspm.directories && pkgJson.jspm.directories.baseURL) {
            return pkgJson.jspm.directories.baseURL;
        }

        return "";
    }