I am experiencing connection problems to demo API
https://demo.docusign.net/restapi
To connect to API I am using the code provided below. It works well for my colleague from US, but when I try to connect from Lithuania there is zero response. Could it be there any location restrictions, or am I missing something?
Should it be some specifics in fire wall (I am under NAT)? Does my local php/http server needs some specific configuration?
$email = "some email # fsdfdsf";
$integratorKey = "TEST-xxxxxxxxxxx";
$password = "some password";
$url = "https://demo.docusign.net/restapi/v2/login_information?include_account_id_guid=true";
$header = "<DocuSignCredentials><Username>" . $email . "</Username><Password>" . $password . "</Password><IntegratorKey>" . $integratorKey . "</IntegratorKey></DocuSignCredentials>";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("X-DocuSign-Authentication: $header"));
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if($status==200){
$response = json_decode($json_response, true);
print_r(json_encode($response['loginAccounts'][0]));
}else{
print_r($json_response);
}
I found a what was stopping to work a source code above.
On my local server ssl was not signed.
So simple and only in test environment quick fix could be to turn off ssl checking on curl:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
or get a signed ssl sertificate.
This is how I solved it, I added $config->setSSLVerification(false); tu turn off ssl verification
$username = "marko#XXX.com";
$password = "XXX";
$integrator_key = "some_key";
// change to production before going live
//https://www.docusign.net/restapi
//https://www.docusign.com/p/RESTAPIGuide/Content/GettingStarted/REST%20API%20Version.htm
$host = "https://demo.docusign.net/restapi";
// create a new DocuSign configuration and assign host and header(s)
$config = new \DocuSign\eSign\Configuration();
$config->setHost($host);
$config->setSSLVerification(false);
$config->addDefaultHeader("X-DocuSign-Authentication", "{\"Username\":\"" . $username . "\",\"Password\":\"" . $password . "\",\"IntegratorKey\":\"" . $integrator_key . "\"}");
// instantiate a new docusign api client
$apiClient = new \DocuSign\eSign\ApiClient($config);
DocuSign does not implement any location restrictions for API clients.
You can check that your firewall is allowing connections to DocuSign by trying to use the service from your web browser. Try demo.docusign.net
You can also use your browser to directly access a method in the API server that provides information on the API service points.
If it works then you know the problem is in your API code.
If so, first try one of the API recipes.
If you can't access the web service then check your firewall settings.
Related
I try to use CURL with PHP to create filters with GMAIL API.
So far I managed to create/delete new users, add and delete labels but I block for that part.
Here is the code :
<?php
//load the necessary
require_once '/root/gmail/google-api-php-client/src/Google/autoload.php';
set_include_path("/root/gmail/google-api-php-client/src" . PATH_SEPARATOR . "/root/gmail/google-api-php-client/examples" . PATH_SEPARATOR. get_include_path());
include_once "templates/base.php";
require_once 'Google/Client.php';
require_once 'Google/Service/Directory.php';
require_once 'Google/Service/Gmail.php';
//PARAM IDENTIFICATION AND SCOPE
$client_id = '<CLIENT_ID>.apps.googleusercontent.com';
$service_account_name = '<SERVICE>.iam.gserviceaccount.com';
$key_file_location = '<PATH_TO_CERT>.p12';
$scope = array("https://apps-apis.google.com/a/feeds/emailsettings/2.0/", "https://mail.google.com/");
$service_token = null;
// Start auth process:
$client = new Google_Client();
$client->setApplicationName("managegmail");
// Create the service
$service = new Google_Service_Gmail($client);
if (isset($service_token))
{
$client->setAccessToken($service_token);
}
// SET Credential
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
$scope,
$key,
'notasecret',
'http://oauth.net/grant_type/jwt/1.0/bearer',
'<account>#<my_domain.com>'
);
// IF Auth OK then OK.
$client2->setAssertionCredentials($cred2);
if($client2->getAuth()->isAccessTokenExpired())
{
$client2->getAuth()->refreshTokenWithAssertion($cred2);
}
// prepare the data packet for curl :
$data = '<?xml version="1.0" encoding="utf-8"?>';
$data .= "<atom:entry xmlns:atom='http://www.w3.org/2005/Atom'
xmlns:apps='http://schemas.google.com/apps/2006'>";
$data .= "<apps:property name='from' value='<toexclude#domain.com>' />";
$data .= "<apps:property name='label' value='<label_name>' />";
$data .= "<apps:property name='neverSpam' value='true' />";
$data .= "</atom:entry>";
//Set the Header with the Token :
$key = $jsonservice_token->access_token;
$headers = array(
"Content-type: application/atom+xml",
"Content-length: " . strlen($data),
"Authorization: " . $key,
"X-HTTP-Method-Override: POST");
// Set and Execute Curl request :
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://apps-apis.google.com/a/feeds/emailsettings/2.0/unity3d.com/test1234567/filter");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
print_r($response = curl_exec($ch));
?>
every time I get the following error :
<HTML>
<HEAD>
<TITLE>Unknown authorization header</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Unknown authorization header</H1>
<H2>Error 401</H2>
</BODY>
</HTML>
Is there something else to do to make work the O2auth authentification ?
Here is also the list of the scope that I allowed :
Email Settings (Read/Write) https://apps-apis.google.com/a/feeds/emailsettings/2.0/
Email (Read/Write/Send) https://mail.google.com/
View and manage the provisioning of groups on your domain https://www.googleapis.com/auth/admin.directory.group
View and manage the provisioning of users on your domain https://www.googleapis.com/auth/admin.directory.user
Email (Manage labels) https://www.googleapis.com/auth/gmail.labels
Email (Read/Write) https://www.googleapis.com/auth/gmail.modify
Thank you by advance.
Each request to Gmail API requires an access token, so an APi key will not be enough. While the user may have logged in that does not by itself give your app authorized access to the user's Gmail.
Like other Google REST APIs, the Gmail API uses OAuth 2.0 to handle authentication and authorization. Although you can code the web service authentication calls explicitly, you normally should simplify your app by using the Google API client libraries available for many programming languages.
For more about using auth with the Gmail API, see Authorizing Your App with Gmail
I am not succeeding to login into docusign with PHP API. I am getting error
with timeout. But most interestingly I am able to login via REST client
on address with header which is below
https://demo.docusign.net/restapi/v2/login_information
X-DocuSign-Authentication: <DocuSignCredentials><Username>zzzzzzz#yyyy.com</Username><Password>somepasss</Password><IntegratorKey>TEST-xxxxxxxxxxxxxxxxxxxx</IntegratorKey></DocuSignCredentials>Accept: application/json Content-Type: application/json
Does any one have any idea of this error cause? (php configuration, modules extensions? Firewall? geo location restrictions? )
Fatal error: Uncaught exception 'DocuSign\eSign\ApiException' with message 'API call to https://demo.docusign.net/restapi/v2/login_information timed out: a:26:{s:3:"url";s:54:"https://demo.docusign.net/restapi/v2/login_information";s:12:"content_type";N;s:9:"http_code";i:0;s:11:"header_size";i:0;s:12:"request_size";i:0;s:8:"filetime";i:-1;s:17:"ssl_verify_result";i:1;s:14:"redirect_count";i:0;s:10:"total_time";d:0.842999999999999971578290569595992565155029296875;s:15:"namelookup_time";d:0.51500000000000001332267629550187848508358001708984375;s:12:"connect_time";d:0.6870000000000000550670620214077644050121307373046875;s:16:"pretransfer_time";d:0;s:11:"size_upload";d:0;s:13:"size_download";d:0;s:14:"speed_download";d:0;s:12:"speed_upload";d:0;s:23:"download_content_length";d:-1;s:21:"upload_content_length";d:-1;s:18:"starttransfer_time";d:0;s:13:"redirect_time";d:0;s:12:"redirect_url";s:0:"";s:10:"primary_ip";s:14:"162.248.186.25";s:8:"certinfo";a:0:{}s:12:"primary_port";i:443;s:8:"local_ip";s:13:"192.168.1.126";s:10:"local in C:\xampp\htdocs\localbits\ds\docusign\src\ApiClient.php on line 233
( ! ) DocuSign\eSign\ApiException: API call to https://demo.docusign.net/restapi/v2/login_information timed out: a:26:{s:3:"url";s:54:"https://demo.docusign.net/restapi/v2/login_information";s:12:"content_type";N;s:9:"http_code";i:0;s:11:"header_size";i:0;s:12:"request_size";i:0;s:8:"filetime";i:-1;s:17:"ssl_verify_result";i:1;s:14:"redirect_count";i:0;s:10:"total_time";d:0.842999999999999971578290569595992565155029296875;s:15:"namelookup_time";d:0.51500000000000001332267629550187848508358001708984375;s:12:"connect_time";d:0.6870000000000000550670620214077644050121307373046875;s:16:"pretransfer_time";d:0;s:11:"size_upload";d:0;s:13:"size_download";d:0;s:14:"speed_download";d:0;s:12:"speed_upload";d:0;s:23:"download_content_length";d:-1;s:21:"upload_content_length";d:-1;s:18:"starttransfer_time";d:0;s:13:"redirect_time";d:0;s:12:"redirect_url";s:0:"";s:10:"primary_ip";s:14:"162.248.186.25";s:8:"certinfo";a:0:{}s:12:"primary_port";i:443;s:8:"local_ip";s:13:"192.168.1.126";s:10:"local_port";i:38524;} in C:\xampp\htdocs\localbits\ds\docusign\src\ApiClient.php on line 233
and the php code is below:
<?php
require_once('./docusign/autoload.php');
class DocuSignSample
{
public function login()
{
$username = "__some email__";
$password = "__some password___";
$integrator_key = "TEST-xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$host = "https://demo.docusign.net/restapi";
$config = new DocuSign\eSign\Configuration();
$config->setHost($host);
$config->addDefaultHeader("X-DocuSign-Authentication", "{\"Username\":\"" . $username . "\",\"Password\":\"" . $password . "\",\"IntegratorKey\":\"" . $integrator_key . "\"}");
$apiClient = new DocuSign\eSign\ApiClient($config);
$authenticationApi = new DocuSign\eSign\Api\AuthenticationApi($apiClient);
$options = new \DocuSign\eSign\Api\AuthenticationApi\LoginOptions();
$loginInformation = $authenticationApi->login($options);
if (isset($loginInformation) && count($loginInformation) > 0) {
$loginAccount = $loginInformation->getLoginAccounts()[0];
if (isset($loginInformation)) {
$accountId = $loginAccount->getAccountId();
if (!empty($accountId)) {
echo $accountId;
}
}
}
}
}
$dss = new DocuSignSample();
$dss->login();
?>
Try
$config->setSSLVerification(false);
Worked for me.
I was experiencing difficulties to use API up until I found that it is needed to have a signed ssl with http server and php or there is also insecure solution which is simply to disable ssl checking in curl (curl was cause of this inconvenience):
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
I am having trouble finding the right access_tokens.
I have tried all ways that I have found on Google and developers.fb, but for this application(I have done it before, and made it work for another app) I just don't seem to be succesful.
I am aware that FB is constantly renewing their API's so maybe I just have found outdated solutions.
There seem to be different types of access tokens: user access tokens, and page access tokens. I find some answers in facebook documentation, but none that I understand.
The app I'm trying to create is something similar to a birthday-reminder, so it needs to be able to send offline messages(fex. be runned by a cron-job, and post to just one fb-page, owned by me, just in the name of the app itself)
I have registered the app with the page-tab on this address:
--https://www.facebook.com/dialog/pagetab?app_id=MY_APP'S_ID&display=popup&next=MY_URL--
and can now find it from the Facebook-page's settings.
Then I get to the part where i need the access token.
I dont know which of the URL's that give me what kind of access token, so I have tried both:
I have visited this URL:
(I write all links duplicate, the answer from tutorials, and my re-written link)
(of course all code pointing to my app and webpage is replaced for security reasons)
--https://www.facebook.com/dialog/oauth?client_id=0123456789011121&redirect_uri=http://www.example.com&scope=read_stream,publish_stream,offline_access--
--https://www.facebook.com/dialog/oauth?client_id=MY_APP_ID&redirect_uri=MY_REDIRECT_URL&scope=read_stream,publish_stream,offline_access--
and got:
http://www.example.com/?code=XXXXX1x1X1xxXxxX1xXxXxX1X111xX11XXXXX1XXXXXxX_XxXxxXxX1xxxXx1xXxXx-x1XxXXXxXXx1xXxXXXxXl1xX-111xXxxxXxxx1xXxxx1xXx1X1X1Xx-xxxXXXxXXXX1XXXXxx1Xxx1_xXxXxxxXx1x1XxXxxXx1XXxX-x1x1xxxXXxXxX1XX1XX1x1-xxXxxxx1Xx1XxXXXxxX#_=_
in other words(as I believe), retrieved the code:
XXXXX1x1X1xxXxxX1xXxXxX1X111xX11XXXXX1XXXXXxX_XxXxxXxX1xxxXx1xXxXx-x1XxXXXxXXx1xXxXXXxXl1xX-111xXxxxXxxx1xXxxx1xXx1X1X1Xx-xxxXXXxXXXX1XXXXxx1Xxx1_xXxXxxxXx1x1XxXxxXx1XXxX-x1x1xxxXXxXxX1XX1XX1x1-xxXxxxx1Xx1XxXXXxxX#_=_
As I have found on Google, it seems as I need to get another code as well, so then I have visited this URL(of course I have tried the first code I got first):
https://graph.facebook.com/oauth/access_token?client_id=0123456789011121&redirect_uri=http://www.example.com&client_secret=1x1111xx11111xXXx11x111111111x11&code=XXXXX1x1X1xxXxxX1xXxXxX1X111xX11XXXXX1XXXXXxX_XxXxxXxX1xxxXx1xXxXx-x1XxXXXxXXx1xXxXXXxXl1xX-111xXxxxXxxx1xXxxx1xXx1X1X1Xx-xxxXXXxXXXX1XXXXxx1Xxx1_xXxXxxxXx1x1XxXxxXx1XXxX-x1x1xxxXXxXxX1XX1XX1x1-xxXxxxx1Xx1XxXXXxxX#_=_
--https://graph.facebook.com/oauth/access_token?client_id=MY_APP_ID&redirect_uri=MY_REDIRECT_URL&client_secret=MY_APP_SECRET&code=THE_CODE_I_GOT_FROM_THE_PREVIOUS_RUN--
But when i try to run the app I get this error message:
Result: {"error":{"message":"Malformed access token XXXXX1x1X1xxXxxX1xXxXxX1X111xX11XXXXX1XXXXXxX_XxXxxXxX1xxxXx1xXxXx-x1XxXXXxXXx1xXxXXXxXl1xX-111xXxxxXxxx1xXxxx1xXx1X1X1Xx-xxxXXXxXXXX1XXXXxx1Xxx1_xXxXxxxXx1x1XxXxxXx1XXxX-x1x1xxxXXxXxX1XX1XX1x1-xxXxxxx1Xx1XxXXXxxX#_=_","type":"OAuthException","code":190}}
I have tried with different types of the ending of the access token(#=), because I dont recognize it from the other, working access token I retrieved last week, to a fully working app that I have built. That one did not have that ending, as I remember.
I also post the script here, if that is of any interest. I have found it in a tutorial, and it is quite simple code:
<?php
// CURL function to send with post method
function send_post_curl($url, $postdata = “”) {
$ch = curl_init($url);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
$data = curl_exec ($ch);
curl_close ($ch);
return $data;
}
// setup the message
$fburl = 'https://graph.facebook.com/THE_FB_PAGE_ID/feed';
$fbtoken = 'THE_ACCESS_TOKEN';
$fbmsg = 'Great API to auto status, this is the message.
Thank to WebDDR
http://webddr.net/tips-and-tricks/facebook-offline-access-step-by-step-explanation/';
$fbpcurl = 'access_token='. $fbtoken;
$fbpcurl .= '&message='. str_replace('&', 'and', urlencode($fbmsg)) ;
$result = send_post_curl($fburl, $fbpcurl);
echo 'Result: '. $result;
?>
I really hope someone can help me, I am doing this as an job I have choosen to do for my education at the university.
/Johan
PS.
Sorry, had to wrangle with the links, --link-- because the forum thought it was spam
Ds.
Try this code :
<?php
session_start();
$facebook_appid = "facebook_appid"; // Facebook appplication id
$facebook_secret = "facebook_secret"; // Facebook secret id
$redirect_uri = "https://localhost/facebook_page/events.php"; // return url to our application after facebook login ## should be SAME as in facebook application
$scope = "user_photos,email,user_birthday,user_online_presence,offline_access,manage_pages,publish_stream,user_events,friends_events"; // User permission for facebook
$code = $_REQUEST["code"]?$_REQUEST["code"]:"";
if(empty($code)) {
$_SESSION['state'] = time(); // CSRF protection
$dialog_url = "https://www.facebook.com/dialog/oauth?client_id=". $facebook_appid . "&redirect_uri=" . urlencode($redirect_uri) . "&state=". $_SESSION['state'] . "&scope=".$scope;
header("location:".$dialog_url);
}
if($_SESSION['state'] && ($_SESSION['state'] == $_REQUEST['state'])) {
$token_url = "https://graph.facebook.com/oauth/access_token?". "client_id=" . $facebook_appid . "&redirect_uri=" . urlencode($redirect_uri). "&client_secret=" . $facebook_secret . "&code=" . $code;
$response = #file_get_contents($token_url);
$params = null;
parse_str($response, $params);
echo $params['access_token'];
echo "<br>";
//$offer_url = "https://graph.facebook.com/".$dt->id."/conversations?access_token=".$dt->access_token;
//$off = #file_get_contents($offer_url);
//$dto = json_decode($off);
//echo "<pre>";
//print_r($dto);
}
?>
I am creating an API request (GET bucket) for the storage API and one of the required parameter is the "Authorization" header.
Please note that I am using a Service Account to access the API.
I followed the document https://developers.google.com/accounts/docs/OAuth2ServiceAccount to get the access token for the "Authorization" header so I could send an authorized request to their REST API. The problem is I am always getting the "invalid_grant" error.
Use this code to check it out:
<?php
error_reporting(E_ERROR);
const CLIENT_ID = 'XXXXXXXXXXXX.apps.googleusercontent.com';
const SERVICE_ACCOUNT = 'XXXXXXXXXXXX#developer.gserviceaccount.com';
const KEY_FILE = 'XXX.p12';
function get_oauth_access_token()
{
$header[alg] = 'RS256';
$header[typ] = 'JWT';
$header = urlencode(base64_encode(utf8_encode(json_encode($header))));
$assertion_time = time();
$claim[iss] = CLIENT_ID; //also tried SERVICE_ACCOUNT here, no improvement
$claim[scope] = 'https://www.googleapis.com/auth/devstorage.read_only';
$claim[aud] = 'https://accounts.google.com/o/oauth2/token';
$claim[exp] = $assertion_time + 3600;
$claim[iat] = $assertion_time;
$claim = urlencode(base64_encode(utf8_encode(json_encode($claim))));
$data = $header . '.' . $claim;
$p12 = file_get_contents(KEY_FILE);
$cert = array();
openssl_pkcs12_read($p12, $cert, 'notasecret');
$priv_key_id = openssl_get_privatekey($cert[pkey]);
openssl_sign($data, $signature, $priv_key_id, 'sha256');
$signature = urlencode(base64_encode($signature));
$assertion = $data . '.' . $signature;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://accounts.google.com/o/oauth2/token');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('grant_type'=>'assertion',
'assertion_type'=>'http://oauth.net/grant_type/jwt/1.0/bearer',
'assertion'=>$assertion));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
var_dump($result);
var_dump($error);
}
get_oauth_access_token();
Is there anything wrong in this code that causes the "invalid_grant" error?
Your problem might be the time of your server.
I faced a problem with Google Analytics: all my code was correct but the time of my server was some seconds in the future compared with Google's time. You can delay your server's time a few minutes to do a test.
If it works you can use NTP for example, to keep the server clock correct.
Here's a simple PHP program illustrating use of a service account with the Google Cloud Storage RESTful HTTP interface. I've tested this code with a service account and it seems to work fine. Let me know if you have any further questions.
<?php
require_once 'apiClient.php';
// Define constants.
const CLIENT_ID = 'YOUR_CLIENT_ID_GOES_HERE';
const SERVICE_ACCOUNT_NAME = 'YOUR_SERVICE_ACCOUNT_NAME_GOES_HERE';
const KEY_FILE = 'key.p12';
const BUCKET = 'marc-us';
// Obtain OAuth 2.0 access token for service account.
$client = new apiClient();
$key = file_get_contents(KEY_FILE);
$client->setAssertionCredentials(new apiAssertionCredentials(
SERVICE_ACCOUNT_NAME,
array('https://www.googleapis.com/auth/devstorage.full_control'),
$key)
);
$client::$auth->refreshTokenWithAssertion();
$json = $client->getAccessToken();
$accessToken = json_decode($json)->access_token;
// Add access token to Authorization header of HTTP request.
$ch = curl_init('http://commondatastorage.googleapis.com/' . BUCKET);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array('Authorization: OAuth ' . $accessToken));
$resp = curl_exec($ch);
curl_close($ch);
// Display results.
print '<h2>Response:</h2><pre>' . $resp . '</pre>';
?>
The code in my last response works fine for me so I suspect you're facing an environmental problem. At any rate, I consulted with the owner of the Google PHP client library and he provided a better way to refresh the access token without resorting to calls to the internal refreshTokenWithAssertion() method. He suggested this technique:
$req = new apiHttpRequest(YOUR_URL);
$val = $client->getIo()->authenticatedRequest($req);
The call to authenticatedRequest() takes care of refreshing the access token (with assertion credentials if they're set) as needed. I modified the code above to use this approach and it works fine for me. Note that both the old and new versions work for me so there's no functional difference but I think the new version is better because it avoids the internal call, uses the Google PHP client lib instead of curl to execute the request and results in much shorter, simpler code.
<?php
require_once 'apiClient.php';
// Define constants.
const SERVICE_ACCOUNT_NAME = 'YOUR_SERVICE_ACCOUNT_NAME';
const KEY_FILE = 'key.p12';
const BUCKET = 'marc-us';
// Obtain service account credentials assertion.
$client = new apiClient();
$key = file_get_contents(KEY_FILE);
$client->setAssertionCredentials(new apiAssertionCredentials(
SERVICE_ACCOUNT_NAME,
array('https://www.googleapis.com/auth/devstorage.full_control'),
$key)
);
// Create HTTP request, authorize and execute.
$req = new apiHttpRequest('http://commondatastorage.googleapis.com/' . BUCKET);
$resp = $client::getIo()->authenticatedRequest($req);
// Display results.
print '<h2>Response:</h2>' . $resp->getResponseBody();
?>
I had the same error, but with Java. My problem was that the time in seconds to exp and iat was in GMT-5 and the API google Auth is in GMT. Then I changed the time to GMT value and all is OK.
I'm trying to implement a check new mail function to my page.
By this I mean a script that checks the mail, if there exists unread mails it will notify the user "You got one unread mail".
Is this possible?
Thanks in advance
I managed to get it to work as long as the users emails and passwords are stored as plain text in the database.
I'm using a query to retrieve email and password of a user from my database ($email) and ($password)
The code:
$mbox =
imap_open("{imap.domain.com:143/novalidate-cert}INBOX",
"$email", "$password");
The only problem is that the email passwords for my users are stored as md5 hash.
How can I handle this with imap_open?
Thanks
It is possible, if you implement an IMAP (or POP3) client in your PHP script. When you open your page, PHP would connect to the mail server and check for new messages. To achieve this, PHP would need your username/password and server address/port. Hence, this information will have to be stored on the server.
The example given at http://lv.php.net/imap_mailboxmsginfo will give you some more hints.
If you can't use imap_open (the extension is not installed, for example), you can use curl (example tested with gmail):
// https://support.google.com/mail/answer/7126229 [2017-10-22]
define('URL', 'imaps://imap.gmail.com');
define('PORT', 993);
define('USER', 'your.user#gmail.com');
define('PASS', 'your_Secret_Password');
if ($ch = curl_init()) {
curl_setopt($ch, CURLOPT_URL, URL);
curl_setopt($ch, CURLOPT_PORT, PORT);
curl_setopt($ch, CURLOPT_USE_SSL, CURLUSESSL_ALL);
curl_setopt($ch, CURLOPT_USERNAME, USER);
curl_setopt($ch, CURLOPT_PASSWORD, PASS);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
// set IMAP command
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'STATUS INBOX (MESSAGES UNSEEN)');
$res = curl_exec($ch);
if (curl_errno($ch)) {
echo 'CURL ERROR: ' . curl_error($ch);
} else {
echo trim($res);
}
echo PHP_EOL;
curl_close($ch);
} else {
die('Curl initialization failed.');
}
The script will return something like:
* STATUS "INBOX" (MESSAGES 2 UNSEEN 1)
More about IMAP commands (https://www.google.com/search?q=imap+protocol+commands) [2017-10-22]:
https://www.rfc-editor.org/rfc/rfc3501
https://donsutherland.org/crib/imap
http://busylog.net/telnet-imap-commands-note/
https://www.skytale.net/blog/archives/23-Manual-IMAP.html
You can comfortably do that using the Zeta Mail component, even without any special extension being available.
$hostname='{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'mygmail#gmail.com';
$password = 'mypass';
$mbox = imap_open($hostname,$username,$password) or die('Cannot connect to Tiriyo: ' . imap_last_error());
$status=imap_status($mbox,$hostname,SA_ALL);
if ($status) {
echo "Messages: " . $status->messages . "<br />\n";
echo "Recent: " . $status->recent . "<br />\n";
echo "Unseen: " . $status->unseen . "<br />\n";
echo "UIDnext: " . $status->uidnext . "<br />\n";
echo "UIDvalidity:" . $status->uidvalidity . "<br />\n";
}
else {
echo "imap_status failed: " . imap_last_error() . "\n";
}
$hostname='{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'mygmail#gmail.com';
$password = 'mypass';
/* try to connect */
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Tiriyo: ' . imap_last_error());
$MB = imap_search($inbox,'UNSEEN');
$xcount($MB);
echo $x;