Gmail API Request Excel VBA PHP - php

I'm using Excel VBA to get a user's oAuth2 token for the mail.google.com scope for a native application. It works fine so I have the the user's Access Token (it refreshes if it expires) and I have the user's email address. I was using Zend SMTP to send the emails but found out there are limits to bulk sending emails this way (currently my account is locked out due to going over quota while trying to figure this out over the weekend). My client may send 2,000 emails at once and locking themselves out of their Gmail account for 24 hours is unacceptable. I think using the Gmail REST API will work, as it has higher quotas, but not finding any detailed PHP examples of how to create and send an HTML email via an HTTP request.
I know I have to create the MIME email and think I can figure that out (using this thread stackoverflow.com/questions/24940984/send-email-using-gmail-api-and-google-api-php-client) or from the Zend emails I was successfully creating. My question is what PHP code do I use to create and send the email?
The Google Dev examples all reference /userId/ (from developers.google.com/gmail/api/v1/reference/) but not sure where to get that if I just have the users token and their email address.
I assume it's something like this:
<?php
require 'GoogleAPI/src/Google/autoload.php';
extract($_POST); // use to get my client token, client's email address, the email to, cc, bcc, subject, body, etc.
//<Build the email $mime message here>
$m = new Google_Service_Gmail_Message();
$data = base64_encode($mime);
$data = str_replace(array('+','/','='),array('-','_',''),$data); // url safe
$m->setRaw($data);
$service->users_messages->send('me', $m);
?>
I don't know where to put the user's token. I know 'me' is the person that is authenticated.
I'm open to using an HTTP request as well, something like https://mywebsite.com/sendgmail.php?token=[UsersToken]&UserEmail=joe#test.com&ToEmail=toperson#xyz.com&Subject=HI&Body=Thanks for your help instead of the post method.
Just not sure how to implement that either.
I'm self taught PHP and VBA and new to the google api world so please forgive me if this is easy. I'm also looking into boxspring but trying to use the native APIs and PHP first.
EDIT:
So I've tried this using the examples but getting an error that my token is not in proper JSON format. I just want to send the token as a string. If I can't is there a way to make the string into JSON so oauth2 will accept it?:
<?php
require 'GoogleAPI/src/Google/autoload.php';
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
$client = new Google_Client();
$client->setAccessToken('ya29.hwFcwk2M73vaPwNObeuwizHGjXT2y6UsAFEcDIvRAoWTM28gu2pJeK4GiMySkfAllTOQvXVMYfffff');
// Get the API client and construct the service object.
//$client = getClient();
$service = new Google_Service_Gmail($client);
// Print the labels in the user's account.
$user = 'me';
$results = $service->users_labels->listUsersLabels($user);
if (count($results->getLabels()) == 0) {
print "No labels found.\n";
} else {
print "Labels:\n";
foreach ($results->getLabels() as $label) {
printf("- %s\n", $label->getName());
}
}
?>
Error:
Fatal error: Uncaught exception 'Google_Auth_Exception' with message
'Could not json decode the token' in
/home/[my domain]/public/GoogleAPI/src/Google/Auth/OAuth2.php:179
Stack trace: #0
/home/[my domain]/public/GoogleAPI/src/Google/Client.php(215):
Google_Auth_OAuth2->setAccessToken('ya29.hwFcwk2M73...') #1
/home/[my domain]/public/labels.php(17):
Google_Client->setAccessToken('ya29.hwFcwk2M73...') #2 {main} thrown
in
/home/[my domain]/public/GoogleAPI/src/Google/Auth/OAuth2.php
on line 179
I'm sure I'm making this more difficult than it should be. I'm using the PHP example of showing a users labels, even though my final goal is to send emails.

Related

DocuSign API: sending a signature request via e-mail with the Envelope ID

I am trying to do the following with the DocuSign API, but I am not getting very much wiser from their documentation.
The admin creates the envelope in DocuSign just as they normally would, but without sending it
They take the Envelope ID and enter it in our software
We show a button to the end user that sends out the Envelope signature request when clicked (based on the Envelope ID)
The closest I came to finding something like this was https://developers.docusign.com/docs/esign-rest-api/how-to/request-signature-email-remote/ but that doesn't seem to allow me to use and existing envelope.
The API reference doesn't seem to offer any help either (https://developers.docusign.com/docs/esign-rest-api/reference/envelopes/envelopes/)
What I have got so far is the following:
OAuth + generating the JWT + access token (works fine)
generating Recipient View (which is not what I need but needs to be replaced with the right call
$view_request = new \DocuSign\eSign\Model\RecipientViewRequest(['return_url' => $args['ds_return_url']]);
if ($args['starting_view'] == "envelope" && $args['envelope_id']) {
$view_request->setEnvelopeId($args['envelope_id']);
}
# Call the API method
$config = new \DocuSign\eSign\Configuration();
$config->setHost($args['base_uri']);
$config->addDefaultHeader('Authorization', 'Bearer ' . $args['ds_access_token']);
$api_client = new \DocuSign\eSign\Client\ApiClient($config);
$envelope_api = new \DocuSign\eSign\Api\EnvelopesApi($api_client);
$results = $envelope_api->createRecipientView($args['account_id'], $view_request);
$view_url = $results['url'];
return $view_url;
Thanks!
So based on your description it looks like for the first step, you're looking to create an envelope as a draft. Which is basically creating an envelope, filling all the information out, and then not sending it.
This will spit out an envelope Id which you can store in your application.
And when the button you describe is clicked, you can update the status of the envelope to "sent" using this endpoint which will send out the envelope.
If you're looking for something more detailed, you can always reach out to us at DocuSign Developer Support and we can discuss it further.

Need Email Address from Google with Access Token that we receive from Alexa Skill?

I was able to Link Account using Google Auth v2 in Alexa Skill. And I am able to get Access Token. Now I want to get the Google Email address with which user has used to link account. So how can I get that Google Email Address?
Use the Oauth2 Scope "https://www.googleapis.com/auth/userinfo.email".
Add the scope to your Google Client (Example with the Google Library for PHP):
$googleClient = new Google_Client();
// Your code here with Client ID, Secret, ...
$googleClient->addScope('https://www.googleapis.com/auth/userinfo.email');
That'll give you the E-Mail of the user.
if(isset($_GET['code'])) {
// Your code here, the login code is in $_GET['code']
/**
* Get access token
*/
$token = $googleClient->fetchAccessTokenWithAuthCode($_GET['code']);
$googleClient->setAccessToken($token['access_token']);
// Create Google Auth Service with the Google Client
$google_auth = new Google_Service_Oauth2($googleClient);
// Get the userinfo
$google_auth_info = $google_auth->userinfo->get();
// Get the E-Mail:
$email = $google_auth_info->email;
}
I think the part you're looking for is authinfo->get()->email, but i added a bit more context so you see how to use this.
Don't forget to enable this scope also in your Google Developers Console:
https://console.cloud.google.com/apis/credentials/consent -> Edit -> Step 2: Scopes

Get the Email-Id of the Client PHP

I want So I've followed the instructions given on the following page
https://developers.google.com/api-client-library/php/auth/web-app
However, it isn't too clear on how to get the currently signed in user's email id. The current scopes that I've set are for reading the person's profile, his email-id and gmail.readonly (reading all emails).
My question is, say I have the access token, and I've initialized the Google_Client object by setting the access token, how do I get the currently sign-in user's email?
Heh, looks like I just needed to find the proper Google Service. Got this by going through the documentation.
https://developers.google.com/resources/api-libraries/documentation/gmail/v1/php/latest/class-Google_Service_Gmail.html
The code now is:
$gmail = new Google_Service_Gmail($client);
if($client->getAccessCode()) {
$token_data = $client->verifyAccessToken();
$email = $token_data['email'];
}
Also, for some reason, the line with $token_data doesn't seem to work, so I ended up using the REST API to verify the access token. Just replace that line with
$token_data = json_decode(file_get_contents('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token='.urlencode($client->getAccessToken()["access_token"])), true);

XML RPC connection using PHP

Has anyone ever created code to connect to Adestra.com's XML RPC API with PHP.
I have seen a couple of XML RPC examples on here, but none of them demonstrate how to send username and password authentication via headers. According to the Adestra Support:-
"We use HTTP basic authentication, which requires the username and password passed through as headers. Most XML-RPC clients will handle this for you by exposing a more convenient interface for supplying credentials. To ensure credentials are passed securely, please connect to the API over https (https://app.adestra.com/api/xmlrpc)."
I [think I] understand the basic process here, i.e. you use an XML RPC library to encode function calls and parameters into XML format, and get a reponse from the server, but how would you send the authentication?
Any help much appreciated.
First you have to download XMLRPC client library. This library is used to create an XMLRPC object which will communicate with ADESTRA API services.
Bellow is example of calling API contact.search method. The principle stays the same for other API methods:
//******* LOGIN DATA*******/
$account = 'account';
$username = 'username';
$password = 'password';
$adestraCoreTable=1;
/**INITIALIZE API*****/
require_once('xmlrpc.inc');//First inlcude XMLRPC client library
//Calling Adestra API with our credentials
$xmlrpc= new xmlrpc_client("http://$account.$username:$password#new.adestra.com/api/xmlrpc");
$xmlrpc->setDebug(0);
$xmlrpc->request_charset_encoding="UTF-8";
$msg = new xmlrpcmsg(
"contact.search",
array(
//Set user id
new xmlrpcval($adestraCoreTable, "int"),
new xmlrpcval(
array(
"email"=> new xmlrpcval("test#test.com", "string"),
),"struct"
)
)
);
$response = $xmlrpc->send($msg);//Send request, and get the response
if($response->faultCode()){//API call not succeed. This can happen when there is no connection
$errorMessage=htmlspecialchars($response->faultString());
$errorCode=htmlspecialchars($response->faultCode());
}
$returnValue = php_xmlrpc_decode($response->value());//Parse API return
if(empty($returnValue)){//If return value is empty, user not find in Adestra, we should log that
$errorMessage="Searching user by mail did not succeed! Problably there is no this user in Adestra DB";
continue;///SCRIPT MUST continue for other users
}
$adestraUSERID=$returnValue[0]["id"];//Use this ID for what ever you want

How to get responses other than timestamp and num_bytes from TripIt API?

I have got a successful oauth TripIt granting process using the same methodology that is used to connect and authenticate users against the LinkedIn and Twitter APIs in PHP (PECL Oauth etc).
However, whenever when I do a valid request (ie a 200 response... no 401 nor 404), all I get in response is:
<Response><timestamp>1301411027</timestamp><num_bytes>80</num_bytes></Response>
I want to list the authenticated user's profile and trip data... The API docs (the pdf) is a bit sketchy on how to do this when the actual user id isn't known, but here are the queries I have attempted:
https://api.tripit.com/v1/list/trip
https://api.tripit.com/v1/list/trip/traveler/true
https://api.tripit.com/v1/get/profile
All returning the same response (as part of the oauth class "last response" method). This is where the LinkedIn API response contents can be found... so what is going on with TripIt? :P
It took a bit of experimenting, but here's an example of one that appears to be working to return data.
$response = $TripIt->_do_request('get/profile');
EDIT:
This one is likely the preferred method.
$response = $TripIt->_do_request('get', 'profile');
I've gone one step further and thrown it into an XML parser.
$response = $TripIt->_do_request('get', 'profile');
$profile = new SimpleXMLElement($response);
Here is one I'm using to get past trips. That third parameter is the one to use for filters.
$response = $TripIt->_do_request('list', 'trip', array('past'=>'true' );
$trips = new SimpleXMLElement($response);

Categories