1

I want to get an array as JSON response from POST request to external API for AyMakan carrier (shipping method module), but still OK data posted & saved to AyMakan web server.

Therefore, The problem when data return response (tracking_number, pdf_label, shipping_label, etc...) from AyMakan API then I got the below error:

Fatal error: Uncaught Error: Cannot use object of type Magento\Framework\App\Response\Http\Interceptor as array in /opt/bitnami/apps/magento/htdocs/vendor/vnecoms/module-vendors-shipping/Controller/Vendors/Order/Shipment/Save.php:227 Stack trace: #0 /opt/bitnami/apps/magento/htdocs/vendor/magento/framework/App/Action/Action.php(108): Vnecoms\VendorsShipping\Controller\Vendors\Order\Shipment\Save->execute() #1 /opt/bitnami/apps/magento/htdocs/vendor/vnecoms/module-vendors/App/AbstractAction.php(288): Magento\Framework\App\Action\Action->dispatch(Object(Magento\Framework\App\Request\Http)) #2 /opt/bitnami/apps/magento/htdocs/vendor/magento/framework/Interception/Interceptor.php(58): Vnecoms\Vendors\App\AbstractAction->dispatch(Object(Magento\Framework\App\Request\Http)) #3 /opt/bitnami/apps/magento/htdocs/vendor/magento/framework/Interception/Interceptor.php(138): Vnecoms\VendorsShipping\Controller\Vendors\Order\Shipment\Save\Interceptor->___callParent('dispatch', Array) #4 /opt/bitnami/apps/magento/htdocs/vendor/magento/fr in /opt/bitnami/apps/magento/htdocs/vendor/vnecoms/module-vendors-shipping/Controller/Vendors/Order/Shipment/Save.php on line 227

But in POSTMAN I can get OK response also in the var/log/aymakan.log in Magento as below:

2020-07-15T18:37:31+00:00 "{\"success\":true,\"data\":{\"shipping\":{\"reference\":\"3000000180\",\"tracking_number\":\"AY264217683\",\"customer_tracking\":null,\"customer_name\":\"kaples\",\"requested_by\":\"\\u0641\\u064a\\u0635\\u0644 \\u0627\\u0644\\u0633\\u0628\\u064a\\u0639\\u064a\",\"price_set_amount\":null,\"price_set_amount_incl_tax\":null,\"tax_amount\":null,\"tax_rate\":null,\"cod_amount\":\"37.2000\",\"declared_value\":\"37.2000\",\"declared_value_currency\":\"SAR\",\"currency\":null,\"delivery_name\":\"Fisal \\u0627\\u0644\\u0639\\u0645\\u064a\\u0644 \\u0641\\u064a\\u0635\\u0644\",\"delivery_email\":\"[email protected]\",\"delivery_city\":\"Jeddah\",\"delivery_address\":\"\\u062c\\u062f\\u0647\",\"delivery_region\":null,\"delivery_postcode\":null,\"delivery_country\":\"SA\",\"delivery_phone\":\"966555555555\",\"delivery_description\":null,\"collection_name\":\"\\u0641\\u064a\\u0635\\u0644 \\u0627\\u0644\\u0633\\u0628\\u064a\\u0639\\u064a\",\"collection_email\":\"[email protected]\",\"collection_city\":\"Jeddah\",\"collection_address\":\"\\u0637\\u0631\\u064a\\u0642 \\u0627\\u0644\\u0645\\u0644\\u0643 - \\u062d\\u064a \\u0627\\u0644\\u0628\\u0633\\u0627\\u062a\\u064a\\u0646\",\"collection_region\":\"Makkah\",\"collection_postcode\":null,\"collection_country\":\"SA\",\"collection_phone\":\"0540702512\",\"collection_description\":null,\"submission_date\":\"2020-07-15T18:37:31.667237Z\",\"pickup_date\":\"2020-07-15T15:37:31.000000Z\",\"received_at\":null,\"delivery_date\":\"2020-07-15T15:37:31.000000Z\",\"weight\":null,\"pieces\":\"1\",\"items_count\":null,\"status\":\"Submitted\",\"status_label\":null,\"reason_en\":null,\"reason_ar\":null,\"created_at\":\"2020-07-15T18:37:31.000000Z\",\"label\":\"https:\\\/\\\/dev.aymakan.com.sa\\\/pdf\\\/generate\\\/211b4299-3c21-4c24-bedb-4140f5a8be19\",\"pdf_label\":\"https:\\\/\\\/dev.aymakan.com.sa\\\/pdf\\\/generate\\\/211b4299-3c21-4c24-bedb-4140f5a8be19\"}}}"

This is my code snippet for preparing post data:

vendor/vnecoms/module-vendors-shipping/Controller/Vendors/Order/Shipment/Save.php

    /**
 * @param $vendorOrder
 * @return \Magento\Framework\App\ResponseInterface|mixed
 */
protected function ayMakan($vendorOrder)
{
    $currentOrder = $vendorOrder->getOrder();
    $aymakanData['id'] = $vendorOrder->getId();
    $aymakanData['delivery_country'] = $this->getCountryId($currentOrder);
    $aymakanData['delivery_name'] = $currentOrder->getCustomerName();
    $aymakanData['delivery_email'] = $currentOrder->getCustomerEmail();
    $aymakanData['delivery_address'] = $this->getAddress($currentOrder)->getCity();
    $aymakanData['delivery_region'] = $this->getAddress($currentOrder)->getRegion();
    $aymakanData['delivery_phone'] = $this->getAddress($currentOrder)->getTelephone();
    $aymakanData['delivery_postcode'] = $this->getAddress($currentOrder)->getPostcode();
    $aymakanData['delivery_city'] = $this->getEnglishTranslatedCity($this->getAddress($currentOrder)->getCity());
    $aymakanData['reference'] = $currentOrder->getIncrementId();
    $aymakanData['declared_value'] = $vendorOrder->getGrandTotal();
    $aymakanData['deliver_items'] = "1";
    $aymakanData['deliver_pieces'] = "1";
    $aymakanData['pieces'] = "1";
    $aymakanData['requested_by'] = $this->_session->getVendor()->getName();
    $aymakanData['submission_date'] = date('Y-m-d H:i:s');
    $aymakanData['pickup_date'] = date('Y-m-d H:i:s');
    $aymakanData['delivery_date'] = date('Y-m-d H:i:s');

    if ($currentOrder->getPayment()->getData('method') == 'cashondelivery') {
        $aymakanData['is_cod'] = "1";
        $aymakanData['cod_amount'] = $vendorOrder->getGrandTotal();
    }

    $aymakanData['collection_name'] = $this->_session->getVendor()->getName();
    $aymakanData['collection_email'] = $this->_session->getVendor()->getEmail();
    $aymakanData['collection_city'] = $this->_session->getVendor()->getCity();
    $aymakanData['collection_address'] = $this->_session->getVendor()->getStreet();
    $aymakanData['collection_region'] = $this->_session->getVendor()->getRegion();
    $aymakanData['collection_phone'] = $this->_session->getVendor()->getTelephone();

    $results = $this->api->createShipment($aymakanData);
    if (isset($results['errors'])) {
        $messages = 'You have errors: ';

        foreach ($results['errors'] as $error) {
            $messages .= $error[0];
        }
        $this->messageManager->addError($messages);
        return $this->_redirect('*/*/new', ['order_id' => $this->getRequest()->getParam('order_id')]);
        exit;
    }
    if (!isset($results['shipping']))
    {
        $this->messageManager->addError('An unknown error occurred. Please check Aymakan log file for errors.');
        return $this->_redirect('*/*/new', ['order_id' => $this->getRequest()->getParam('order_id')]);
        exit;
    }
    return $this->response = $results['shipping'];
}

vendor/vnecoms/module-vendors-shipping/Controller/Vendors/Order/Shipment/Save.php:227

            if (strpos($vendorOrder->getShippingDescription(), "aymakan") !== false) {
            $this->isAymakanShippingMethod = true;
            $this->response = $this->ayMakan($vendorOrder);

            $trackingNumber = $this->response['tracking_number'];
            $labelUrl = $this->response['pdf_label'];
        }

and This code snippet for AyMakan API to Post and Get the response:

vendor/vnecoms/module-vendors-shipping/Helper/Api.php

<?php
/**
 * File Name: Api.php
 * Created by Altaf Hussain
 * User: Altaf Hussain
 * Description: Aymakan API v2 Integration class
 * Date: 29 January 2020
 * Copyright ©Aymakan, Inc. All rights reserved
 */

namespace Vnecoms\VendorsShipping\Helper;

use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;

class Api extends AbstractHelper
{
    /**
     * var $endPoint
     */
    private $endPoint = '';
    /**
     * var testingUrl
     */
    protected $testingUrl = 'https://dev.aymakan.com.sa/api/v2';
    /**
     * var liveUrl
     */
    protected $liveUrl = 'https://aymakan.com.sa/api/v2';

    /**
     * var apiKey
     */
    private $apiKey = '';

    /**
     * Api constructor.
     * @param Context $context
     */
    public function __construct(Context $context)
    {
        parent::__construct($context);
        $this->apiKey = $this->scopeConfig->getValue('carriers/aymakan_carrier/api_key');
        $isTesting = $this->scopeConfig->getValue('carriers/aymakan_carrier/testing');
        if ($isTesting)
            $this->endPoint = $this->testingUrl;
        else
            $this->endPoint = $this->liveUrl;
    }

    /** Get the list of available cities from Ayamakan. It provides both English and Arabic city names.
     * @return array|bool
     */
    public function getCities()
    {
        $url = $this->endPoint.'/cities';
        $cities = $this->makeCall($url);
        return $cities['cities'];
    }

    /** Creates a shipment
     * @param array $data
     * @return array|bool
     */
    public function createShipment($data)
    {
//        $data['collection_name'] = $this->scopeConfig->getValue('carriers/aymakan_carrier/collection_name');
//        $data['collection_email'] = $this->scopeConfig->getValue('carriers/aymakan_carrier/collection_email');
//        $data['collection_city'] = $this->scopeConfig->getValue('carriers/aymakan_carrier/collection_city');
//        $data['collection_address'] = $this->scopeConfig->getValue('carriers/aymakan_carrier/collection_address');
//        $data['collection_region'] = $this->scopeConfig->getValue('carriers/aymakan_carrier/collection_region');
        $data['collection_postcode'] = "";
        $data['collection_country'] = "SA";
//        $data['collection_phone'] = $this->scopeConfig->getValue('carriers/aymakan_carrier/collection_phone');
        $data['collection_description'] = " ";

        $url = $this->endPoint.'/shipping/create';
        return $this->makeCall($url, $data, 'POST');
    }

    /** Make a call to Aymakan API
     * @param $url
     * @param null $data
     * @param string $type
     * @return array|bool
     */
    private function makeCall($url, $data = null, $type = 'GET')
    {
        if (!$this->isEnabled())
            return false;

        $ch = curl_init();

        if(isset($data) and !empty($data))
        {
            curl_setopt($ch,CURLOPT_POST, 1);
            curl_setopt($ch,CURLOPT_POSTFIELDS, http_build_query($data));
        }

        $headers = [
            'Accept: application/json',
            'Authorization: '.$this->apiKey
        ];
        curl_setopt($ch,CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
        $response = curl_exec($ch);
        $this->log($response);
        curl_close($ch);

        $result = json_decode($response, true);
        if (isset($result) and isset($result['errors']))
            $this->log($result);
            $this->log($data);
            return $result;

        if(!isset($result['data']))
        {
            $this->log($result);
            return $result;
        }
        $this->log($result);
        return $result['data'];
    }

    protected function log($data)
    {
        $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/aymakan.log');
        $logger = new \Zend\Log\Logger();
        $logger->addWriter($writer);
        $logger->err('Error: '.json_encode($data));
    }

    /** Check if the module is enabled or not.
     * @return bool
     */
    public function isEnabled()
    {
        if ($this->scopeConfig->getValue('carriers/aymakan_carrier/active'))
            return true;
        return false;
    }
}

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.