2

My client asked me to make a small change in his online store, I have never tried it and hope before starting maybe someone could give me some insights, mayble a class or script that already exists that someone knows about.

Basically I have some pdf files in my magento store which are generated from a api that I use them for the invoice company management. So the client asked me to use some kind of cloud technology such that when a invoice is generated it should be automatically stored in cloud (google drive), and then organize them by year, and month folders.

Does anybody know about how may I do it? Or does anyone know if such plugins or code already available serving the purpose?

1 Answer 1

0

This is a big question to ask, definitely not a "small change" as you put it. Likely you won't get a full answer in a place like this. But what I can do is give you some resources to seek out further.

These solutions are based on native Magento invoicing functionality. I don't know much about your custom solution for invoice receipts, but starting from these should inspire you to find the answer to your scenario.


Option A: Minimum Development

Try a popular app connector service like Zapier. I put together a quick template, as shown below:

Configuring a Zap for Magento-Google Drive

Where here you configure an available Magento trigger, like order invoice generation. Then, you bind that trigger to an action like Google Drive file upload.

Pros

  • Easy setup
  • No coding involved

Cons

  • You have to develop the invoice template yourself
  • You are limited in available data to use in the template

Option B: Custom Development

This is not an easy solution. You should know that Google's APIs use the OAuth 2 specification for authorizing connections to its services. In this case, that won't do. So instead you can look to using the service account approach:

https://developers.google.com/identity/protocols/OAuth2ServiceAccount

Then, there is a PHP SDK for Google Drive:

https://github.com/google/google-api-php-client/tree/v1.1.8

Download and use version/tag 1.1.8. This one is old, but uses PSR-0 standards, which in short means you just to place the repo's src/Google folder into your Magento project under lib/Google, and all classes will autoload. With this library installed, you can start to experiment with building a Magento module to do your work.

As I see it, your task looks something like this:

  1. Build a new module
  2. Register an observer on event sales_order_invoice_save_after
  3. Build observer class to receive event data
  4. Build an API connector to upload contents to Google Drive as files
  5. Connect observer class event data to your API connector
  6. Use built-in PDF generation to create raw PDF contents
  7. Send PDF contents to Google Drive using your API connector

I have written an example class for step #5 above so that you can get an idea of how to bridge Magento invoice generation to a Google Drive upload interface:

class Vbuck_DriveIntegrationTest_Model_Upload
    extends Varien_Object
{
    const APP_NAME     = '';
    const CLIENT_ID    = 'YOUR_SERVICE_ACCOUNT_CLIENT_ID_HERE';
    const SERVICE_ID   = '[email protected]';
    const TARGET_OWNER = 'YOUR_DRIVE_ACCOUNT_EMAIL_ADDRESS';

    private $_client;
    private $_service;

    protected function _construct()
    {
        $this->_client = new Google_Client();
        $this->_client->setApplicationName(self::APP_NAME);
        $this->_client->setAssertionCredentials($this->_getCredentials());

       $this->_service = new Google_Service_Drive($this->_client);
    }

    protected function _getCredentials()
    {
        return new Google_Auth_AssertionCredentials(
            self::SERVICE_ID,
            'https://www.googleapis.com/auth/drive',
            file_get_contents(
                Mage::getModuleDir('etc', 'Vbuck_DriveIntegrationTest') . DS . 'auth.p12'
            )
        );
    }

    protected function _getFile($name)
    {
        $file = new Google_Service_Drive_DriveFile();
        $file->setName($name);

        return $file;
    }

    protected function _getPermissions()
    {
        $permission = new Google_Service_Drive_Permission();
        $permission->setEmailAddress(self::TARGET_OWNER);
        $permission->setRole('reader');
        $permission->setType('user');

        return $permission;
    }

    public function generatePdfStream(Mage_Sales_Model_Order_Invoice $invoice)
    {
        /* @var $renderer Mage_Sales_Model_Order_Pdf_Invoice */
        $renderer = Mage::getSingleton('sales/order_pdf_invoice');

        /* @var $document Zend_Pdf */
        $document = $renderer->getPdf(array($invoice));

        return $document->render();
    }

    public function writeFile($name, $contents)
    {
        $file    = $this->_getFile($name);
        $result  = $this->_service->files->create(
            $file,
            array(
                'data'          => $contents,
                'mimeType'      => 'application/pdf',
                'uploadType'    => 'multipart'
            )
        );

        sleep(3);

        $this->_service->permissions->create(
            $result->getId(),
            $this->_getPermissions()
        );

        return $result;
    }

    public function syncInvoice(Mage_Sales_Model_Order_Invoice $invoice)
    {
        return $this->writeFile(
            "Invoice #{$invoice->getIncrementId()}",
            $this->generatePdfStream($invoice)
        );
    }

}

I also tested this to make sure it works by following the steps I laid out in this sample class. I was able to upload an invoice PDF to my personal Drive account in the exact same format as what Magento sends out to customers natively.

Here is the sample code I wrote to use the above class:

require_once '/vagrant/public_html/app/Mage.php';
Mage::app()->setCurrentStore(0);

$model   = new Vbuck_DriveIntegrationTest_Model_Upload();
$invoice = Mage::getModel('sales/order_invoice')->load(1);
$result  = $model->syncInvoice($invoice);

var_dump($result);

If you use the class I wrote, you must edit the constant properties at the top of the class to match your service account credentials, which can be found here after defining a service account and enabling the Drive API:

Managing Google Service Accounts

When you setup a service account, you will be asked how you wish to download your OAuth credentials file. Choose the legacy format, P12, since we are using an older PHP SDK and that is the format required. When you download the file, save it to your module's etc folder, as auth.json. So using my sample code above, my auth file would be saved to:

app/code/local/Vbuck/DriveIntegrationTest/etc/auth.json

This will allow the class method _getCredentials I wrote above to locate it.

Pros:

  • Complete control over PDF upload process

Cons:

  • Hard to build
  • Lots of integration steps
  • Maintenance debt

Give either of these a try. Hopefully you can figure it out from here.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.