Tuesday 8 June 2021

Microsoft Graph API PHP

Microsoft Graph API PHP Tutorials

I am sharing some basic sample PHP code for Microsoft Graph API. May this will  helpful for someone.

For full reference, go to GIT URL:

PHP Framework Laravel Sample Code GIT URL:





















To start, you should have Outlook/Hotmail or any Microsoft Account.

First required to register App on Azure Active Directory. You can create App on Azure even if you have School or Organization account.

Graph API will generate Microsoft Authentication URL, where user will redirect and after successful login he will redirect back callback URL. Callback URL need to define in Azure App.

User can get Calendar events based on dates provided. User can create events on their Calendar.

Sharing Create Calendar Event using Microsoft Graph API.

<?php
// POST /me/events
$events_response = $graph->createRequest('POST', '/me/events')
    ->attachBody($newEvent)
    ->setReturnType(Model\Event::class)
    ->execute();


Get Calendar Events using Microsoft Graph API

<?php

$userEventsArr = $graph->createRequest('GET', $getEventsUrl)
// Add the user's timezone to the Prefer header
    ->addHeaders(array(
        'Prefer' => 'outlook.timezone="' . $userTimezone . '"',
    ))
    ->setReturnType(Model\Event::class)
    ->execute();

Sunday 6 June 2021

Calculate Number of Days PHP

Calculate Number of Working Days Between Two Days in PHP

I am sharing my PHP code to get difference between two dates.

$workingDays = 0;

$startTimestamp = strtotime('2021-06-03');
$endTimestamp = strtotime('2022-07-09');
for ($i = $startTimestamp; $i <= $endTimestamp; $i = $i + (60 * 60 * 24)) {
    if (date("N", $i) <= 5) $workingDays = $workingDays + 1;
}

echo "no. of days: " . $workingDays;

Save code in nofdays.php.

Run program in terminal. Output will be:

$ php nofdays.php

no. of days: 287




Tuesday 11 May 2021

Digital E-sign Tool

Digital E-sign Tool

I have developed Digital E-Signature Tool to digital sign any PDF file. It's a developed in HTML5, JQuery technology and JSPDF library. JS Signature Pad library is also used. PHP script is also added to save the file on server. May be its helpful for someone.

Digital E-Sign Tool Img1


User can drag signature at any place on the PDF document. User can upload signature as well.




Digital E-Sign Tool -2



Digital E-sign - 3



Digital E-Sign - 4



    
Digital E-Sign Tool



Full code can be found at below Bitbucket URL:



First we load any PDF.  Then user click Add signature button. User can upload signature file as well. Once user draw or upload his signature, it will show in drag area on right side. User can drag that signature anywhere on the PDF file. Once user click Acceptance checkbox, as most of the sites ask for acceptance of policy or any agreement. Submit button becomes available. User can save signature file, email that or upload on server, developer has to write that script as per his requirements.




Friday 12 March 2021

PDF file generation from HTML file in Python

PDF Generation from HTML File in Python






I am sharing my script to generate PDF file from HTML file in Python using PDFKit module.

Install Python PDF-Kit

$ pip install pdfkit

Some Simple Examples:
import pdfkit

pdfkit.from_url('http://testpage.com', 'out.pdf')
pdfkit.from_file('test.html', 'out.pdf')
pdfkit.from_string('Hello!', 'out.pdf')

My Sample Script to generate PDF from HTML page.

 import os

import sys
from flask import Flask,request
import pdfkit
from flask import make_response
import logging.config
app = Flask(__name__)
from decouple import config

# Logger and handlers
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'console': {
            'format': '%(levelname)-1s%(asctime)s [%(name)-12s.%(funcName)s.%(lineno)s%(message)s',
        },
        'file': {
            'format': '%(levelname)-1s%(asctime)s [%(name)-12s.%(funcName)s.%(lineno)s%(message)s',
        },
    },
    'handlers': {
        'console': {
            'level': "DEBUG",
            'class': 'logging.StreamHandler',
            'formatter': 'console',
            'stream': sys.stdout
        },
        'file': {
            'level': "DEBUG",
            'class': 'logging.handlers.RotatingFileHandler',
            'formatter': 'file',
            'filename': 'htmltopdf.log',
        },
    },
    'loggers': {
        '': {
            'handlers': ['file'],
            'level': "DEBUG",
            'propagate': True
        },
    }
}

logging.config.dictConfig(LOGGING)
LOGGER = logging.getLogger(__name__)


@app.route("/")
# Function for html to pdf convertor
def function_html_to_pdf_convertor():
    try:
        logging.debug("calling func")
        html_file = request.args.get('f', default="", type=str)
        if html_file:
            html_file = '{}{}'.format(html_file,'.html')
            filepath = os.path.join(app.static_folder, html_file)
            filename = os.path.splitext(os.path.basename(filepath))[0]
            css = "static/style.css"
            options = {
                'page-size': 'Letter',
                'encoding': "UTF-8",
                'zoom': 1.80,
                'footer-center': 'Page [page]/[topage]',
                'footer-font-size': 8
            }
            if os.path.isfile(filepath):
                #pdf = pdfkit.from_file(filepath, css=css)
                pdf = pdfkit.from_file(filepath, False,options=options, css=css)
                response = make_response(pdf)
                response.headers.set('Content-Disposition', 'attachment', filename=filename + '.pdf')
                response.headers.set('Content-Type', 'application/pdf')
                return response
            else:
                logging.debug("File not found")
                return {
                    "status": 404,
                    "message": 'File not found'
        }
        logging.debug("'Please provide file'")
        return{
            "status": 400,
            "message": 'Please provide file'
        }

    except Exception as e:
        logging.debug("Bad request {}".format(e))
        return {
            "status": 400,
            "error": '{}'.format(e)
        }
# main function
if __name__ == "__main__":
    app.run()

Monday 8 February 2021

AWS Cognito SSO Integration with Python

AWS Cognito SSO Integration with Python

AWS SSO Cognito OAuth2.0 implementation as per below URL:

https://aws.amazon.com/blogs/mobile/understanding-amazon-cognito-user-pool-oauth-2-0-grants/

First we need to create code, get Client ID and Client Secret. Run below URL:

https://AUTH_DOMAIN/login?client_id=XXXXXXXXXX&response_type=code&scope=email+openid&redirect_uri=http://localhost/test/sso_check

Above URL will return to redirect url with code in query string.

Note: Code is valid for one time transaction only.

Get Access Token using the Code as per below description:



Make below request:





this will return below response:

{
    "id_token": "eyJraWQiOiJJNGs2UXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    "access_token": "eyJraWQiOiJENllqdXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    "refresh_token": "eyJjdHkiOiJKV1QiLCJlbmXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    "expires_in": 3600,
    "token_type": "Bearer"
}


From above response we need to use id_token to get user information:

  • id_token – A valid user pool ID token. Note that an ID token is only provided if the openid scope was requested.
Below is the Python code Github URL to get user information by validating JWT token returned in id_token key.






Below is the response from above Python code:



Saturday 30 January 2021

Python Flask REST API Tutorial

Python Flask REST API Tutorial

I am sharing my Python code to create simple REST API. I have used Python's lightweight framework Flask is used to create simple REST API. Flask Restful is an extension of Flask. This code may helpful for some beginner Python developer. 


from flask import Flask
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

class HelloWorld(Resource):
    def get(self):
        return {'hello': 'world'}

api.add_resource(HelloWorld, '/')

if __name__ == '__main__':
    app.run(debug=True)

Print CSV Content in Python Tutorial

Print CSV Content in Python Tutorial

As CSV is most common file to import and export data on web applications. So we may need to use this feature in almost our most of the apps. So I am sharing my small Python code to print CSV data into an array. May this code is helpful for someone.

We need CSV module of Python for this code to run. We used CSV module `reader` function to read CSV content in Python.

import csv

results = []
with open('test.csv', newline='') as csvfile:
    reader = csv.reader(csvfile, delimiter=' ', quotechar='|')
    for row in reader:
        results.append(row)
print("CSV data: ", results)



More details on CSV module of Python, please follow below URL:

https://docs.python.org/3/library/csv.html

Create .ICS file using PHP code

Recently worked on creating a .ics file in PHP after a very long time, code so thought to share with everybody. Please find below the comple...