Thursday, August 13, 2026

anil

The Importance of Knowledge Management in the Telecom Industry

 The telecommunications sector is a rapidly evolving landscape where the proliferation of

services and technologies demands agile and informed decision-making. Knowledge

management plays a critical role in ensuring that telecom companies stay ahead of trends,

technological advancements, and customer expectations. By effectively harnessing and

utilizing the vast amount of information generated within this dynamic industry, organizations

can achieve superior operational efficiency and customer satisfaction. Knowledge

management systems help in capturing, organizing, and disseminating important information

across various departments and teams. In this article, we will explore why a robust

knowledge management strategy is essential for telecom companies to thrive in today's

competitive marketplace.


Enhancing Customer Service through Effective Information Sharing

Alt text: A customer service representative in a call center, wearing headphones and

speaking to a customer, enhancing customer service through effective knowledge

management for telecom

The quality of their customer service often judges telecom companies. Knowledge

management for telecom supports customer service teams by providing them with

comprehensive databases for troubleshooting, service protocols, and customer interaction

histories. This allows for prompt responses to customer inquiries and the delivery of accurate

solutions, enhancing the overall customer experience.

With a unified knowledge base, service representatives can provide consistent information to

customers, which helps in building trust and credibility. In the event of complex technical


issues, the ability to quickly access expert knowledge and guidance ensures that customer

concerns are addressed efficiently without unnecessary delays.

Knowledge management also aids in personalized service offerings. By analyzing customer

data and interactions, telecom companies can understand individual preferences and tailor

their services accordingly. This not only leads to higher customer satisfaction but also opens

the door to upselling and cross-selling opportunities.

Additionally, knowledge management systems support self-service portals that empower

customers to find answers to their questions without direct interaction, leading to reduced

support costs and an increase in customer autonomy and satisfaction.


Streamlining Operations and Fostering Innovation with Knowledge Management

Alt text: A customer service representative in a call center, wearing headphones and

speaking to a customer, streamlining operations and fostering innovation with knowledge

management

Operational efficiency is paramount in the telecom sector, where margins are often tight and

competition is fierce. Knowledge management aids in optimizing processes by reducing

repetitive tasks and encouraging the sharing of best practices. This leads to a more

streamlined operation where resources are utilized effectively, and productivity is maximized.


Critical to staying ahead in the highly competitive telecom industry is the continuous pursuit

of innovation. Knowledge management fosters an environment where ideas and learnings

are easily shared and accessed, thus promoting innovation. Employees across the board

can contribute to and benefit from a culture of shared learning and creativity.

Detailed insights garnered from knowledge management systems can also drive strategic

planning and policy-making. With comprehensive analytics and reporting features, telecom

leaders can make informed decisions about the direction of their services and investments.

Consequently, this can result in better risk management and more opportunities for growth.

Furthermore, by documenting processes and outcomes, knowledge management helps

establish benchmarks and define key performance indicators (KPIs) that are vital for

continuous improvement and accountability within the organization.

Overcoming the Challenges of Knowledge Silos in the Telecom Sector

One of the significant challenges telecom companies face is the existence of knowledge

silos, where information is trapped within certain teams or departments. Knowledge

management systems counteract this by enabling the free flow of information across the

enterprise. They break down barriers, ensuring that knowledge reaches all corners of the

organization, and everyone benefits from shared expertise.

The agility of a telecom company is also enhanced as a result of overcoming these silos.

Teams can quickly adapt to technology shifts and market changes without being held back

by outdated or inaccessible information. This agility is a critical asset in an industry where

customer preferences and technology trends can change overnight.

Additionally, knowledge management systems mitigate the risk of losing critical information

when personnel leave the company or move to different roles. By having a centralized

repository, the organization can maintain a continuity of operations and preserve institutional

memory, resulting in a resilient and adaptive enterprise.

By addressing the inefficiencies associated with siloed information, telecom companies can

also avoid redundancy, inconsistency, and errors in their operations, ultimately leading to

cost savings and improved service reliability.

Altogether, effective knowledge management empowers telecom companies to streamline

operations, enhance customer service, and foster innovation, all while overcoming the

challenges of knowledge silos. By leveraging shared insights and resources, these

companies can remain agile, competitive, and poised for long-term success in a dynamic

industry.

Read More

Saturday, August 22, 2020

anil

Easy Process to Host website on AWS

 I found lots of professional struggle to host their website on Amazon Web Services (AWS) . So here I am going to explain the step by step process to host a website on AWS. using this process you can save your money too on AWS. You can host multiple small type of websites also using this process. 

Note:- This process is recommended for medium traffic website. if your website has large traffic then you should follow a different process using AWS load blancers.

Step by Step Process to Host Website on AWS:-

Step-1 :-

 Launch a ec2 instance first using ubuntu 16.04 AMI on AWS marketplace.(Also you have to download PEM file in the last step)


Step-2:-

 Ensure all ports like 80, 8080,8083,22,143 etc are enabled in your security croup.


Step-3:-

 Login using ssh command(sudo ssh -i /home/user/Downloads/aws_admin.pem ubuntu@52.66.129.45)

-> Sudo su


Step-4:-

Now you have to install vista panel to host a website on AWS. 

Install vista panel just click Install Vista Panel


Step 5:- 

After installation done. login to vista panel using your username and password.


Step 6:- 

Now go to web and create your hosting for specified domain.


Step 7:- 

You can either create ftp or copy your files in ec2 hosting directory /home/admin/web/your_domain/public_html for uploading your website files


Step 8:-

Create your database in DB section and upload your database by login to phpmyadmin.


Step 9:-

Now change your database crdentials in your config file.


Step 10:-

Do not forget to change ip address in your domain name service provider. It should be same as your ec2 instance public ip address.


Now just visit your website on browser and enjoy. if  you found any type of difficulty, you can simply comment here. I will try to resolve your issue. Thank you.


**** if website still showing deafult page. then just remove index.html from the specified directory.****

Read More
anil

How to Setup Vista Panel on AWS.

 You can follow below step by step process to setup vista panel aws EC2 instance.


Install Vista Panel

Step 1:-

First you have to login into your EC2 instance on terminal using below command.

sudo ssh -i /home/user/Downloads/aws_admin.pem ubuntu@52.66.129.45

Note:- make sure you have given a right path of PEM file to access ec2 instance.


Step 2:-

Now just run below command one by one.

-> apt-get update -y

-> apt-get upgrade -y

-> nano /etc/hosts

-> 127.0.0.1            vestacp.linuxbuz.com

-> wget http://vestacp.com/pub/vst-install.sh

-> chmod 755 vst-install.sh

-> bash vst-install.sh / bash vst-install.sh --force


Step 3:-

-> Type y and ENTER to continue:

-> Please enter admin email address: admin@linuxbuz.com

-> Please enter FQDN hostname [vestacp.linuxbuz.com]: 

-> Installation backup directory: /root/vst_install_backups/1564552012


Your installation has been done. Now just visit vista panel on browse and start to host your website on AWS


If you found any type of difficulty just intimate me using comment. I will try to resolve your issue. Thank you.


Read More

Friday, May 15, 2020

phpMyPassion

How to Send an Email Using PHPMailer ?

                                                            
Many of developers struggle to integrate send mail functionality in a website. So I thought why do we make the easy process for sending mail functionality by post. 

                                                              Image Source:- Google Images

Here I comes with a simplified process for sending an email using PHPMailer. I integrated this many of websites developed by me using PHP.   I have created my own code using PHPMailer library to send an emails easily.

So first of all I am providing the introduction of PHPMailer as below.

PHPMailer:-

PHPMailer is a library that is used to send emails safely and easily using PHP code from a web server. In a website Sending emails directly via PHP code requires a high-level familiarity to SMTP standard protocol and related issues and vulnerabilities about Email injection for spamming. PHPMailer simplifies the process of sending emails easily.

Process to Integrate:-

Step:- 1 Clone this git repository or download it using below URL.
 
git clone https://github.com/phpmypassion/phpmailer.git

Step:- 2 Update composer for latest update of library.

composer update

Step:- 3 Include function.php where you want to send mail.

<?php
   require 'functions.php'; 

Step:- 4 Now call send_mail() function with param

sendemail($to, $from, $fromname, $subject, $message);

$to :- Email id on that you want to send an email.
$from :-  Email id from which  you want to send an email.
$fromname :- Your business name.
$subject :- What is all about that mail.
#message :- Your mail content

Your file for sending mail could be look like below:-

I have used below file after filling up contact us form for sending email. 

if (isset($_POST['con_submit']) && !empty($_POST['con_submit'])) {
			// PREPARE THE BODY OF THE MESSAGE
			$message = '<html><body>';
			$message .= 'PhpMyPassion.com - Hi admin, you got a new query.';
			$message .= '<table rules="all" style="border-color: #666;" cellpadding="10">';
			$message .= "<tr style='background: #eee;'><td><strong>Name:</strong> </td><td>" . strip_tags($_POST['con_name']) . "</td></tr>";
			$message .= "<tr><td><strong>Email:</strong> </td><td>" . strip_tags($_POST['con_email']) . "</td></tr>";
			$message .= "<tr><td><strong>Phone Number:</strong> </td><td>" . strip_tags($_POST['con_phonenumber']) . "</td></tr>";
			$message .= "<tr><td><strong>Interested for:</strong> </td><td>" . strip_tags($_POST['con_intrest']) . "</td></tr>";
			$message .= "<tr><td><strong>Message:</strong> </td><td>" . $_POST['con_message'] . "</td></tr>";
			$message .= "</table>";
			$message .= "</body></html>";

			//  MAKE SURE THE "FROM" EMAIL ADDRESS DOESN'T HAVE ANY NASTY STUFF IN IT
			$pattern = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i";
			if (preg_match($pattern, trim(strip_tags($_POST['con_email'])))) {
				$cleanedFrom = trim(strip_tags($_POST['con_email']));
			} else {
				header('Location: thank_you.php?msg=fail');
			}
			if (empty($_POST['con_name'] || $_POST['con_email'] || $_POST['con_phonenumber'] || $_POST['con_intrest'])) {
				header('Location: thank_you.php?msg=empty');
			} else {
				
					$to = 'to@gmail.com';

					$subject = 'PhpMyPassion.com Contact Us';

					$thanksemail = $_POST['con_email'];
					$message2 = lead_user_mail_format();

					$fromname = 'PhpMyPassion.com';
					$from = 'support@gotPhpMyPassion.com.com';
					if ($to != '' && $thanksemail != '') {
						$res = sendemail1($to, $from, $cc, $fromname, $subject, $message);
						$res1 = sendemail($thanksemail, $from, $fromname, $subject, $message2);
						if ($res && $res1) {
							header('Location: thank_you.php?msg=success');
						} else {
							header('Location: thank_you.php?msg=fail');
						}
					} else {
						header('Location: thank_you.php?msg=fail');
					}
				
			}
		}
		else {
			header('Location: thank_you.php?msg=fail');
		}

I hope this article simplified the process for sending an emails to any number of users.
Read More

Monday, May 4, 2020

phpMyPassion

How to Install VestaCP on Ubuntu 18.04 LTS

VestaCP gives you a user interface to host your website more efficiently and makes your work so easy. Below are the commands to install VestaCP..




->apt-get update -y

-> apt-get upgrade -y

-> nano /etc/hosts

-> 127.0.0.1    vestacp.phpmypassion.com

-> wget http://vestacp.com/pub/vst-install.sh

-> chmod 755 vst-install.sh

-> bash vst-install.sh / bash vst-install.sh --force

Type y and ENTER to continue:

Please enter admin email address: admin@linuxbuz.com

Please enter FQDN hostname [vestacp.linuxbuz.com]: 


Installation backup directory: /root/vst_install_backups/1564552012

If you found any type of difficulty for installing VestaCP in ec2 instance, you can intimate me by your comment. I will try to resolve your issue.
Thank you.
Read More

Friday, April 24, 2020

phpMyPassion

Process to Create AWS Lambda Function in Python

In this article I am sharing the full and easy process of creating a AWS lambda function using python. So follow step by step process for creating AWS lambda using python 3.

********************** process to create lambda function *****************


> fill basic information like name, runtime envoironment, permission



*******************Now add Trigger from the list in left side****************


In my case I used s3

-> configure triggers basics
-> select s3 Bucket [bucket name on that you want run your trigger]
-> event type {like bucket PUT}
-> prefix
-> suffix [like - .csv, .jpg]



Note:- you can either choose prefix or suffix.

*********************** upload your lambda function code ****************


In my case I had to produced csv name as massage that was automatically uploaded in s3 bucket by python program for athena query result. So I produced massage by kafka producer on s3 put event trigger.

For setting up kafka producer on lambda trigger I did below steps..

#Install kafka in your local machine and create .zip of whole package.

Follow below steps:-

"""
# https://pypi.org/project/kafka-python/

# pip install kafka-python -t <FOLDER PATH>
# pip install requests -t <FOLDER PATH>

# README:
* Please Install the Kafka Python & Request Libs in the same folder for it to  work
    in AWS Lambda.
* When Uploading on AWS Lambda, zip the entire folder. 
   If you are uploading a zip file.  Make sure that you are zipping the contents 
   of the directory and not the directory itself.  
   Else you will get an Error: aws lambda unable to import module

zip -r ../build_dmp_dashboard_from_athena.zip *

"""

#Now you have to create a file for produced massage on trigger as below -

Lets create a file first with name lambda_producer.py

from __future__ import print_function
import sys, time
import json
import requests
from kafka import KafkaProducer

########################### Configurations #############################################
email_api = 'https://api.phpmypassion.com/api/send-mail'
email_to = 'phpmypassion@gmail.com'

kafka_server_cluster = ['cluster1', 'cluster2', 'cluster3'] 
topic = "athena_query_result"

"""
Send Email
"""
def sendmail(message):
  msg = ("{}:{}".format("lambda_producer", message))
  data = {
    'toEmail': email_to,
    'mailSubject': msg,
    'mailBody': msg
  }

  return requests.post(email_api, data)


"""
Producer Connection
"""
exception_counter = 0
for x in range(3):
  try:
    producer = KafkaProducer(bootstrap_servers=kafka_server_cluster)
    break

  except Exception as e:
    exception_counter = exception_counter + 1
    print(e)
    print("Error in Connection to kafka cluster: {0}".format(kafka_server_cluster))
    time.sleep(2)  # 2 Sec

if (exception_counter >= 2):
  message = ('Error: Looks like connection to kafka cluster failed on lambda producer: {0}'.format(kafka_server_cluster))
  print(message)
  response = fnc_sendmail(message)
  print("Email Sent Response: {0}".format(response))
  print("Program exiting")
  sys.exit(2)

"""
Lambda Handler. Received the trigger from the Code Commit Repositoy of AWS and  Produces
a message on kafka Queue
"""
def lambda_handler(event, context):
  print("Received event : " + json.dumps(event, indent=2))

  # Parse the S3 Trigger and Get the CSV Path & File from the "event"
  key_file_name = (event['Records'][0]['s3']['object']['key']) 

  print("We have a new file. file name & path : ", key_file_name)
  try:
    producer_ret_val = producer.send(topic, key_file_name.encode())  # If Topic Does not Exist then it get created automatically by python Producer
    record_metadata = producer_ret_val.get(timeout=10)
    print("sent event to Kafka! topic {} partition {} offset {}".format(record_metadata.topic, record_metadata.partition, record_metadata.offset))

  except Exception as e:
    print(e)
    print("Some Error in lambda_producer")
    raise e



#Now Lets setup thin within Aws lambda:-

-> choose "code entry type" and select the option to upload .zip


-> upload your zip file and click to save

-> your lambda code has been uploaded.

-> in my case I uploaded kafka configuration zip folder

#You have to also change lambda handler function too. as you are using lambda_handler function within lambda_producer.py file so you have to fill "lambda_producer.lambda_handler" within the above input box [shows in right red line above image].

#Now click on save button.

You done the all steps.


Read More

Wednesday, April 22, 2020

phpMyPassion

How to Copy files from host to Docker container?

Most common problem "Copying files from host to Docker container" that usually developers face. So here I am providing you a simple command that would be copy a file from host to docker container.
To copy a file into your docker container you have to follow below 3 points.
  1. first, copy the path of localhost where your file stored. ** in my case its stored on /home/anil/Desktop/database/database.sql **
  1. second you have to set a path into your docker container where you want to store your file. ** in my case I created a folder with name "database" and get the path "/home/ubuntu/database/" **
  1. Now you are to just replace file path, container folder path and container id in below command.




sudo docker cp /home/(user_name)/(folder_name)/(file_name)  (your_container_id):/(folder_path_you_want_the_file_to_be)



Now just copy and paste your command into terminal and you will find your file into your docker specified folder path. Enjoy.
Read More

Tuesday, April 21, 2020

phpMyPassion

Python map() function

Map() function :-


map() function in python used to perform operations on a given number of iterable sequence like list, set, tuple etc.

map() function takes a function as an one argument and a iterable sequence as a second argument. 

map(func, iter)

func:- This is a function on which map function passes each element of given iterator.
iter:- This is a iterable sequence like lists, sets, tuples etc.

map() function returns a map object. so you have to change the type of result to list or tuple as per your requirement.

Example 1:- Python program for getting triple of a given numbers list using map().


# Return triple of n 
def triple(n): 
    return n**3 
  
# We make triple all numbers using map() 
numbers = (1, 2, 3, 4) 
res = map(triple, numbers) 
print(list(res)) 



Output :- [1, 8, 27, 64]


Example 2:- get triple of a given numbers list using lambda and map() function.


# We make triple of all numbers using map() 
numbers = (5, 2, 6, 3) 
res = map(lambda x: x**3, numbers) 
print(list(res)) 

Output :- [125, 8, 216, 27]

I tried my best to explain the one of special python function. So if you still have any difficulty, you can drop a comment here.  Thank you.
Read More

Saturday, April 11, 2020

phpMyPassion

How to Transfer a Domain into Another Godaddy Account?


Step 1.  Login into your godaddy account.

First of all you have to login into your godaddy account from which you booked that domain (xyz.com)

Step 2. Now go to your all products & services page.


You have to just click on the manage button shown in above right side of screenshot.


Step 3. Go to your DNS management page.

Here you have to click on transfer domain link shown in red circle.

Step 4. Fill up the required information's.

Here you have to fill up following information's -
  • Owners mail address (Godaddy account mail id on that you want to transfer)
  • Customer (optional- it could be godaddy customer id)
  • Do you want to copy contact information? (Here you should ideally choose YES)
That's It. Now just click on Transfer Domain button.


After successfully transfer domain, new owner will receive a mail for accepting your transferred domain authority.

Once owner click on the acceptance link, you will not see that domain into your Godaddy account dashboard.

You will also receive a mail regarding to same after successfully domain transfer. 

Read More

Thursday, November 28, 2019

phpMyPassion

Difference Between React and Angular - AngularJS v/s ReactJS


Many of web developers are struggling for choosing good option for frontend. there is confusion in choosing AngularJS or ReactJS whether it is a smarter choice for front-end development. React and Angular are powerful front end development technologies. AngularJS is designed and managed by Google, while Facebook and its community maintain ReactJS. They are built on JavaScript that makes advancement and customisation to develop advanced front end of web applications.

According to my experience, here I am mentioning some of the comparison points between AngularJS and ReactJS. I hope this will be helpful for front end web developers.

Angular :

  • It is a Framework.
  • Angular is best for large scale web applications.
  • Angular use two directional data flow process where its updated the real DOM directly.
  • Its difficult for learning to a beginner.
  • Angular is easy to set up but it takes time to deliver project.
  • Backward compatibility issue in its versions below Angular 2.
  • It does not has flex architecture inbuilt. angular uses observable for data store.
  • Angular is slow and high weighted compare to React. 
  • It has solid community support. 

React :

  • It is a JavaScript Library
  • React is perfect option of small and medium scale type of web application.
  • React updates only the virtual DOM and is deal with the one-directional data flow.
  • React learning curve is easy for beginner.
  • React takes longer to set up than Angular but it takes less time to deliver projects. React lets you create projects and build apps relatively quickly.
  • Its all versions are completely backward compatible with all its previous versions.
  • React fully support flex architecture. It has data store ability inbuilt.
  •   React is Fast and light weighted compare to Angular.
  • React is behind in community contribution and collaborations.
If you have any type of query, please intimate me by your comment.
Read More

Monday, November 25, 2019

phpMyPassion

How To Remove Last Character From A String Using jQuery?

Common problem faced by developers, how to remove last character from a string using jQuery, Here I am going to explain the solution with an example.


var str = '123-4';
alert(str.slice(0, -1));
Read More
phpMyPassion

Difference between TRUNCATE , DELETE and DROP in MySql Server

TRUNCATE
  • TRUNCATE is a DDL(Data Manipulation Language) command
  • TRUNCATE is executed using a table lock and whole table is locked for remove all records.
  • We cannot use Where clause with TRUNCATE.
  • TRUNCATE removes all rows from a table.
  • Minimal logging in transaction log, so it is performance wise faster.
  • TRUNCATE TABLE removes the data by deallocating the data pages used to store the table data and records only the page deallocations in the transaction log.
  • Identify column is reset to its seed value if table contains any identity column.
  • To use Truncate on a table you need at least ALTER permission on the table.
  • Truncate uses the less transaction space than Delete statement.
  • Truncate cannot be used with indexed views.
DELETE
  • DELETE is a DML(Data Definition Languages) command.
  • DELETE is executed using a row lock, each row in the table is locked for deletion.
  • We can use where clause with DELETE to filter & delete specific records.
  • The DELETE command is used to remove rows from a table based on WHERE condition.
  • It maintain the log, so it slower than TRUNCATE.
  • The DELETE statement removes rows one at a time and records an entry in the transaction log for each deleted row.
  • Identity of column keep DELETE retain the identity.
  • To use Delete you need DELETE permission on the table.
  • Delete uses the more transaction space than Truncate statement.
  • Delete can be used with indexed views.
DROP
  • The DROP command removes a table from the database.
  • All the tables' rows, indexes and privileges will also be removed.
  • No DML(Data Definition Languages) triggers will be fired.
  • The operation cannot be rolled back.
  • DROP and TRUNCATE are DDL commands, whereas DELETE is a DML command.
  • DELETE operations can be rolled back (undone), while DROP and TRUNCATE operations cannot be rolled back.
Read More
phpMyPassion

How to connect with redshift in python


import psycopg2
import psycopg2.extras





def redshif_connect(): 
  ####### connection and session creation ##############  
  print("redshif_connect start......")  
  conn = psycopg2.connect(dbname="RS_DB_NAME", host="HOST_NAME", 
                    port="RS_PORT", user="USER_NAME", password="PWD")  
  print('redshif connection variable', conn)  
  self.cursor = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)  

Read More
phpMyPassion

Set Library Path for python running configuration

******************** Set Library Path for python running configuration *****

-> home/user/.bashrc

Add below code in your library path

export PATH="/home/user/anaconda3/bin:$PATH"

export PYTHONPATH="/home/user/anaconda3/bin/md"
Read More
phpMyPassion

How to Convert a Python Dictionary to List


 >>> from functools import reduce
 >>> a = {'foo': 'bar', 'baz': 'quux', 'hello': 'world'}
 >>> list(reduce(lambda x, y: x + y, a.items()))
 ['foo', 'bar', 'baz', 'quux', 'hello', 'world']

explanation
-> a.items() returns a list of tuples. 
-> Adding two tuples together makes one tuple containing all elements. Thus the reduction creates one tuple containing all keys and values and then the list(...) makes a list from that.







Read More

Sunday, June 2, 2019

phpMyPassion

How To Integrate DoubleClick Bid Manager API With Laravel 5.4

In this article I am explaining a simple process to setup Google Bid Manager (DBM) API by PHP Artisan Command with laravel 5.4. You can get campaigns or your line items data either setting up a cron using created command or running command on terminal.

First, edit composer.json in the project's root folder to include the Google Client:


{    "require": {
        "google/apiclient": "^2.0"    }
}



Next run composer update at shell prompt to pull in the sdk to the vendor folder.

php composer.phar install --no-dev


Now we would like to use the Google DBM SDK within our app as a command. But before doing that, let us setup our client_id, client_secret and access_token which are parameters required while making requests to Google DBM API. You can obtained client_id and client_secret from your Google App Console .

Once we have these credentials from Facebook, we would now edit .env file in the project's root folder. Add them to the end:

DBM_CLIENT_ID=8990-ru2amnc17f5jchhgsepp0uro96smu16b.apps.googleusercontent.com
DBM_CLIENT_SECRET=XXXXXXXXXXXXX
DBM_REFRESH_TOKEN=1/VeTb6k8T291WCKWsPfnBrjOBxtwwCxO11Q6FGH8DZJk
Replace the xxx.. with the values provided to you. Note that the variable names are just my own creation. You can name them whatever you'd like. We would now have to use these variables to setup a separate config file. We need to do this so that we can use Laravel's config() helper function to retrieve the values wherever we want within the app. So let's create google-dbm.php in the config folder and add the following:

return [
    'client_id' => env('DBM_CLIENT_ID', null),
    'client_secret' => env('DBM_CLIENT_SECRET', null),
];

Now we have to create a class GoogleDbmService.php with below command..

php artisan make:console GoogleDbmService
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
class GoogleDbmService extends Command
{   
   /**
    * The name and signature of the console command.
    */
   protected $signature = 'google-dbm:service {--date=today}';
    /** 
     *The console command description.
     * @var string 
     */ 
   protected $description = 'google ads api for campaign 
                            service, adset etc';    /** 
     * Create a new command instance.
     * @return void
     */    
   public function __construct(){
        parent::__construct();    
   }
   /** 
    * Execute the console command.
    * @return mixed 
    */    
   public function handle()    {
      //Your Code Goes Hare
    }
}

You have to write your all code to get Google campaign & their reporting in the handle() function.

Now to run this command on our terminal we have to register it in Kernal.php with path "/app/Console/kernel.php".

So add "Command\GoogleDbmService::class" in the $commands array as below -


protected $commands = [    
   Commands\GoogleDbmService::class
];


Now we have all setup to get campaign or lineitems reporting from google dbm api.

Now just add some classes at the top of our GoogleDbmService class that we gonna use to get campaign data.

use Google_Client;
use Google_Service_DoubleClickBidManager;
use Google_Service_DoubleClickBidManager_DownloadLineItemsRequest;
use Google_Service_DoubleClickBidManager_DownloadRequest;
use Google_Service_DoubleClickBidManager_FilterPair;
use Google_Service_DoubleClickBidManager_Parameters;
use Google_Service_DoubleClickBidManager_Query;
use Google_Service_DoubleClickBidManager_QueryMetadata;
use Google_Service_DoubleClickBidManager_QuerySchedule;
use Google_Service_Exception;

Now write your code to get google dbm campaign data in its handle() function as below -

We have to get access token first to make an google bid manager api call.

To instantiate an Api object you will need a valid access token:


$client = new Google_Client();
$client->setAccessType('offline');
$client->setClientId(env('DBM_CLIENT_ID'));
$client->setClientSecret(env('DBM_CLIENT_SECRET'));
$client->addScope('https://www.googleapis.com/auth/doubleclickbidmanager');
$service = new Google_Service_DoubleClickBidManager($client);
$data = $client->refreshToken(env('DBM_REFRESH_TOKEN'));
$client->setAccessToken($data['access_token']);

Download Campaigns by AdvId -

you should pass adv_id to get all campaigns -

public function downloadCmp($service, $adv_ids){
    // Setup any filtering on the API request
    $dliRequest = new
    Google_Service_DoubleClickBidManager_DownloadRequest();
    $dliRequest->setFilterType("ADVERTISER_ID");
    $dliRequest->setFileTypes(array("CAMPAIGN"));
    $dliRequest->setFilterIds(array($adv_ids));
    try {
      $result = $service->sdf->download($dliRequest);
    } catch (Google_Service_Exception $e) {
      printf('<p>Exception: %s</p>', $e->getMessage());
      print '<p>Consider filtering by ADVERTISER_ID</p>';
      return;
    } catch (Exception $e) {
      printf('<p>Exception: %s</p>', $e->getMessage());
      return;
    }
    $csv_content = $result['campaigns'];
    $csvDelimiter = '';
    $csvLines = str_getcsv($csv_content, "\n");
    $linesToImport = [];
    foreach($csvLines as $row)
    {
      $linesToImport[] = str_getcsv($row, $csvDelimiter);
    }
    return $linesToImport;
  }

Create Query -

In DBM it is necessary to create query to get data of a lineitems. So here I here is the code for creating a query.

//Create Query
  public function createQuery($service, $dateRange, $filters){
    // Setup any filtering on the API request
    $qryRequest_prm = new  Google_Service_DoubleClickBidManager_Query();
    $qryRequest = new Google_Service_DoubleClickBidManager_QueryMetadata();
    $qryRequest->setDataRange($dateRange);
    $qryRequest->setFormat('csv');
    $qryRequest->setTitle('query:'.time());
    $qryRequest->setRunning('true');
    $a = [];
    foreach($filters as $k=>$v){
      $filterPairRequest = new Google_Service_DoubleClickBidManager_FilterPair();
      $filterPairRequest->setType($k);
      $filterPairRequest->setValue($filters[$k]);
      $a[] = $filterPairRequest;
    }
    $groupBY = array(
      //"FILTER_ADVERTISER",
      //"FILTER_ORDER_ID",
      "FILTER_MEDIA_PLAN",
      "FILTER_LINE_ITEM",
      //"FILTER_BUDGET_SEGMENT_DESCRIPTION",
      "FILTER_DATE"
    );
    $prmRequest = new Google_Service_DoubleClickBidManager_Parameters();
    //$prmRequest->setFilters(["FILTER_PARTNER"]);
    $params = array(
      "METRIC_CLICKS",
      "METRIC_TOTAL_CONVERSIONS",
      "METRIC_CONVERSIONS_PER_MILLE",
      "METRIC_IMPRESSIONS",
      "METRIC_CTR",
      "METRIC_REVENUE_PARTNER",
      //'METRIC_REVENUE_ADVERTISER',
    );
    $prmRequest->setMetrics($params);
    $prmRequest->setType("TYPE_GENERAL");
    $prmRequest->setFilters($a);
    $prmRequest->setGroupBys($groupBY);
    //$prmRequest->setGroupBys();
    $schRequest = new Google_Service_DoubleClickBidManager_QuerySchedule();
    $schRequest->setFrequency('ONE_TIME');
    $qryRequest_prm->setKind('doubleclickbidmanager#query');
    $qryRequest_prm->setMetadata($qryRequest);
    $qryRequest_prm->setParams($prmRequest);
    $qryRequest_prm->setQueryId(123456);
    $qryRequest_prm->setSchedule($schRequest);
    try{
      $result = $service->queries->createquery($qryRequest_prm);
    }catch (Exception $e){
      print($e);
    }
    return $result->queryId;
  }

Delete Query -

Always delete query id after you done the all operation related to that query id.

//Delete query after operations
  public function deleteQuery($service, $queryId){
    try{
      $result = $service->queries->deletequery($queryId);
    }catch (Exception $e){
      print($e);
    }
    return $result;
  }

Download All LineItems of an Advertiser -

if you want to download all line items of an advertiser you can do it with below function.

//Download Line Items public function downloadLineItems($service, $adv_ids){ $dliRequest = new Google_Service_DoubleClickBidManager_DownloadLineItemsRequest(); $dliRequest->setFilterType("ADVERTISER_ID"); $dliRequest->setFilterIds(array($adv_ids)); try { $result = $service->lineitems->downloadlineitems($dliRequest); //print_r($result); } catch (Google_Service_Exception $e) { printf('<p>Exception: %s</p>', $e->getMessage()); print '<p>Consider filtering by ADVERTISER_ID</p>'; return; } catch (Exception $e) { printf('<p>Exception: %s</p>', $e->getMessage()); return; } if (!isset($result['lineItems']) || count((array)$result['lineItems']) < 1) { print '<p>No items found</p>'; return; } else { //print_r( $result->lineItems); $csv_content = $result->lineItems; $csvDelimiter = ''; $csvLines = str_getcsv($csv_content, "\n"); $linesToImport = []; foreach($csvLines as $row) { $linesToImport[] = str_getcsv($row, $csvDelimiter); } print '<p>Download complete</p>'; } return $linesToImport; }

Get LineItems Insight -

You can change fields and parameters according to your need.

public function handle() { if ($this->option('date') == "today") { $dateRange = 'CURRENT_DAY'; } elseif ($this->option('date') == "yesterday") { $dateRange = 'PREVIOUS_DAY'; } elseif ($this->option('date') == "last_month") { $dateRange = 'PREVIOUS_MONTH'; }elseif ($this->option('date') == "this_month") { $dateRange = 'MONTH_TO_DATE'; }elseif ($this->option('date') == "last_year") { $dateRange = 'PREVIOUS_YEAR'; }elseif ($this->option('date') == "this_year") { $dateRange = 'YEAR_TO_DATE'; }elseif ($this->option('date') == "all_time") { $dateRange = 'ALL_TIME'; } else { $this->info('Please choose date param between today/yesterday/last_month/this_month/last_year/this_year'); return; } $prefix = "DBM_"; $partner_id = 20534561234; $requestParam = []; $requestParam['account_type'] = "DBM"; $account = Account::getAccountListByAccountType($requestParam); if(count($account) <= 0) { $this->error('You have not any account please set up your account'); return; } $this->info("Total Ad Account:-" . count($account)); if($account) { foreach ($account as $key => $value) { if($value['access_token'] && $value['ext_account_id']) { $requestParam['user_id'] = $value['user_id']; $requestParam['account_id'] = $value['account_id']; $requestParam['account_name'] = $value['name']; $requestParam['ext_account_id'] = $value['ext_account_id']; $requestParam['adv_id'] = $value['adv_id']; $requestParam['manager_id'] = $value['manager_id']; $this->info("Account:-".$value['ext_account_id']); $client = new Google_Client(); $client->setAccessType('offline'); $client->setClientId(env('DBM_CLIENT_ID')); $client->setClientSecret(env('DBM_CLIENT_SECRET')); $client->addScope('https://www.googleapis.com/auth/doubleclickbidmanager'); $service = new Google_Service_DoubleClickBidManager($client); $data = $client->refreshToken($value['access_token']); $client->setAccessToken($data['access_token']); try{ $cmpByAdvId = $this->downloadCmp($service, $requestParam['ext_account_id']); $this->info('Campaign count:-' . (count($cmpByAdvId)-1)); if(count($cmpByAdvId) > 0) { foreach ($cmpByAdvId as $key_id => $cmp_value) { if ($key_id == 0) { continue; } else{ $filters = array( 'FILTER_PARTNER'=>$partner_id, 'FILTER_ADVERTISER'=>$requestParam['ext_account_id'], 'FILTER_MEDIA_PLAN'=>$cmp_value[0], ); $queryId = $this->createQuery($service, $dateRange, $filters); if ($queryId != '' || $queryId != 0) { sleep(60); #coz csv takes time to write on google cloud // Call the API, getting a list of queries. $result = $service->queries->getquery($queryId); $csv_content = file_get_contents($result->getMetadata()->getGoogleCloudStoragePathForLatestReport()); if (isset($csv_content)) { $csvDelimiter = ''; $csvLines = str_getcsv($csv_content, "\n"); $linesToImport = []; foreach ($csvLines as $row) { $linesToImport[] = str_getcsv($row, $csvDelimiter); } $this->info('Campaign Id:-'.$cmp_value[0]); $i = 0; if (count($linesToImport) > 0) { foreach ($linesToImport as $key => $value) { if ($key == 0) { continue; } else if($key > 0 && count($linesToImport[$key])<5){ continue; } else{ if(!empty($value[10])){ if(!empty($cmp_value[10])){ $sdate = strtotime($cmp_value[10]); $cmp_sdate = date('Y-m-d h:i:s', $sdate); }else{ $cmp_sdate=''; } if(!empty($cmp_value[11])){ $edate = strtotime($cmp_value[11]); $cmp_edate = date('Y-m-d h:i:s', $edate); }else{ $cmp_edate=''; } $requestParam['cmp_id'] = $cmp_value[0]; $requestParam['flight_id'] = $value[3]; //adsGroup id $requestParam['conversions'] = $value[10]; $requestParam['impressions'] = $value[12]; $requestParam['clicks'] = $value[9]; $requestParam['ctr'] = $value[13]; $requestParam['date'] = $value[7]; $requestParam['wkno'] = (int)date("W", strtotime($value[7])); $requestParam['rev_model'] = NULL; $requestParam['cmp_name'] = $prefix . $cmp_value[2]; $requestParam['cmp_status'] = $value[2]; $requestParam['campaign_name'] = $cmp_value[2]; $requestParam['cmp_type'] = NULL; $requestParam['flight_name'] = $prefix . $value[2]; $requestParam['start_date'] = $cmp_sdate; $requestParam['end_date'] = $cmp_edate; $requestParam['budget'] = $cmp_value[9]; $requestParam['payout'] = $value[14]; $requestParam['hour'] = 0; $requestParam['ms_id'] = '178';//DBM media source id $saveCmpRptData = DbmOverviewTableForTest::saveYourCmpRptData($requestParam); if ($saveCmpRptData) { if (isset($saveCmpRptData['status']) && $saveCmpRptData['status'] == 9) { DbmOverviewTableForTest::updateYourCmpRptData($requestParam); } } else { $this->info('database not connected and something went wrong'); return; } $i++; } } } $this->info('Count Report:-' . $i); $this->info('*************************'); $this->deleteQuery($service, $queryId); } } else{ $this->info('@Error:csv_content variable is not found'); $this->deleteQuery($service, $queryId); } } } } } }catch (\Execption $e){ print($e) return; } } } } }


Run your command on terminal -

php artisan google-ads:service

You can see your output on the terminal.

If you found any difficulty in setting up Google DBM API with laravel, you can intimate me by comment.  
Read More