mautic - I want to add contact in mautic via api - api

I want to add contact in mautic via an API. Below I have the code, but it's not adding the contact in mautic.
I have installed mautic in localhost. Studied the API form in the mautic documentation and tried to do it for at least 2 days, but I am not getting any results on it.
<?php
// Bootup the Composer autoloader
include __DIR__ . '/vendor/autoload.php';
use Mautic\Auth\ApiAuth;
session_start();
$publicKey = '';
$secretKey = '';
$callback = '';
// ApiAuth->newAuth() will accept an array of Auth settings
$settings = array(
'baseUrl' => 'http://localhost/mautic', // Base URL of the Mautic instance
'version' => 'OAuth2', // Version of the OAuth can be OAuth2 or OAuth1a. OAuth2 is the default value.
'clientKey' => '1_1w6nrty8k9og0kow48w8w4kww8wco0wcgswoow80ogkoo0gsks', // Client/Consumer key from Mautic
'clientSecret' => 'id6dow060fswcswgsgswgo4c88cw0kck4k4cc0wkg4gows08c', // Client/Consumer secret key from Mautic
'callback' => 'http://localhost/mtest/process.php' // Redirect URI/Callback URI for this script
);
/*
// If you already have the access token, et al, pass them in as well to prevent the need for reauthorization
$settings['accessToken'] = $accessToken;
$settings['accessTokenSecret'] = $accessTokenSecret; //for OAuth1.0a
$settings['accessTokenExpires'] = $accessTokenExpires; //UNIX timestamp
$settings['refreshToken'] = $refreshToken;
*/
// Initiate the auth object
$initAuth = new ApiAuth();
$auth = $initAuth->newAuth($settings);
/*
if( $auth->getAccessTokenData() != null ) {
$accessTokenData = $auth->getAccessTokenData();
$settings['accessToken'] = $accessTokenData['access_token'];
$settings['accessTokenSecret'] = 'id6dow060fswcswgsgswgo4c88cw0kck4k4cc0wkg4gows08c'; //for OAuth1.0a
$settings['accessTokenExpires'] = $accessTokenData['expires']; //UNIX timestamp
$settings['refreshToken'] = $accessTokenData['refresh_token'];
}*/
// Initiate process for obtaining an access token; this will redirect the user to the $authorizationUrl and/or
// set the access_tokens when the user is redirected back after granting authorization
// If the access token is expired, and a refresh token is set above, then a new access token will be requested
try {
if ($auth->validateAccessToken()) {
// Obtain the access token returned; call accessTokenUpdated() to catch if the token was updated via a
// refresh token
// $accessTokenData will have the following keys:
// For OAuth1.0a: access_token, access_token_secret, expires
// For OAuth2: access_token, expires, token_type, refresh_token
if ($auth->accessTokenUpdated()) {
$accessTokenData = $auth->getAccessTokenData();
echo "<pre>";
print_r($accessTokenData);
echo "</pre>";
//store access token data however you want
}
}
} catch (Exception $e) {
// Do Error handling
}
use Mautic\MauticApi;
//use Mautic\Auth\ApiAuth;
// ...
$initAuth = new ApiAuth();
$auth = $initAuth->newAuth($settings);
$apiUrl = "http://localhost/mautic/api";
$api = new MauticApi();
$contactApi = $api->newApi("contacts", $auth, $apiUrl);
$data = array(
'firstname' => 'Jim',
'lastname' => 'Contact',
'email' => 'jim#his-site.com',
'ipAddress' => $_SERVER['REMOTE_ADDR']
);
$contact = $contactApi->create($data);
echo "<br/>contact created";
Any help will be appreciated.

use Curl\Curl;
$curl = new Curl();
$un = 'mayank';
$pw = 'mayank';
$hash = base64_encode($un.':'.$pw);
$curl->setHeader('Authorization','Basic '.$hash);
$res = $curl->post(
'http://mautic.local/api/contacts/new',
[
'firstname'=>'fn',
'lastname'=>'ln',
'email'=>'t1#test.com'
]
);
var_dump($res);
This is something very simple i tried and it worked for me, please try cleaning cache and enable logging, unless you provide us some error it's hard to point you in right direction. Please check for logs in app/logs directory as well as in /var/logs/apache2 directory.

In my experience sometimes after activating the API in the settings the API only starts working after clearing the cache.
Make sure you have activated the API in the settings
Clear the cache:
cd /path/to/mautic
rm -rf app/cache/*
Then try again
If this didn't work, try to use the BasicAuth example (You have to enable this I the settings again and add a new User to set the credentials)
I suspect that the OAuth flow might be disturbed by the local settings / SSL configuration.

these steps may be useful:
make sure API is enabled(yes I know it's might be obvious but still);
check the logs;
check the response body;
try to send it as simple json via Postman
it may be one of the following problems:
Cache;
You are not sending the key:value; of the required custom field;
you are mistaken with authentication;
Good luck :)

Related

Cannot get JWT (json web token) to work with Apple App Store Connect API in PHP

I get a 401/Not Authorized return for my JTW using PHP with Apple's App Store Connect API.
Using php 7.1.3, I've tried various libraries and raw php (code below). I'm pretty sure the header and payload are fine and the problem is the signing of it, using the p8 private key file I downloaded from Apple. I have quadruple checked the kid, iss, and private key file.
// Create token header as a JSON string
$header = json_encode([
'typ' => 'JWT',
'alg' => 'ES256',
'kid' => '1234567980'
]);
// Create token payload as a JSON string
$payload = json_encode([
'iss' => '12345678-1234-1234-1234-123456789012',
'exp' => time()+60*10, // 20 minute max allowed
'aud' => 'appstoreconnect-v1'
]);
$base64UrlHeader = rtrim(strtr(base64_encode($header), '+/', '-_'), '=');
$base64UrlPayload = rtrim(strtr(base64_encode($payload), '+/', '-_'), '=');
$privateKey = openssl_pkey_get_private('file://'.resource_path('/assets/AppleKey_1234567980.p8'));
$signature = '';
openssl_sign("$base64UrlHeader.$base64UrlPayload", $signature, $privateKey, 'sha256');
// Encode Signature to Base64Url String
$base64UrlSignature = rtrim(strtr(base64_encode($signature), '+/', '-_'), '=');
// Create JWT
$jwt = "$base64UrlHeader.$base64UrlPayload.$base64UrlSignature";
When I submit this to Apple via curl, I get a 401/Not Authorized with details "Authentication credentials are missing or invalid" and nothing more specific.
Has anyone used Apple's App Store Connect API with PHP - google searches have slim to no results I can find.
You can check this solution. i manage to get authenticated and get data from appleconnect. https://stackoverflow.com/a/57150060/860353

Google Apps Marketplace CustomerLicense Authorization Steps ?

We have recently create the google marketplace app and published as public .admin of the google apps domain users can able to install it .
i recently try to implement the CustomerLicense,LicenseNotification Apis in for my app
But i dont know how to send a Authorization for it Please suggest me to how to do this
My requirement :
1.I need to know whether the given domain has installed my marketplace app or not (My input is authorization,email id or domain name
2.If any user uninstall or revoke the data access for my marketplace app i need to get the notify (optional)
Here is sample code :
$appId = '';**//Where i get this**
$userid = '';**//It is emailid or domain name or user unique numeric id**/
$oauthOptions = array(
'requestScheme' => Zend_Oauth::REQUEST_SCHEME_HEADER,
'signatureMethod' => 'HMAC-SHA1',
'consumerKey' => '', **//Where i get this**
'consumerSecret' => "" **//Where i get this**
);
//We get from APP URL
try {
$userid = 'backup-testing.in';
$token = new Zend_Oauth_Token_Access();
$client = $token->getHttpClient($oauthOptions);
$url = "https://www.googleapis.com/appsmarket/v2/customerLicense/$appId/$userid";
$client->setMethod(Zend_Http_Client::GET);
$gdata_put = new Zend_Gdata($client);
$resultR = $gdata_put->get($url);
} catch (Exception $e) {
var_dump($e);
}
This is my marketplace app
in chrome westore : https://chrome.google.com/webstore/detail/gapps-backup/jmjnfmekbahcminibjmedfehecoihglj
Here you can find information about the Licensing API https://developers.google.com/google-apps/marketplace/v2/developers_guide which i think will be useful for what you want to do. hope it helps.

Facebook PHP SDK auth between main domain and multiple subdomains

I really don't manage to make this work. I've tried already all the steps I've found on SO or other websites, but my cross-domain fb authentication doesn't work..
How my auth script looks like:
session_set_cookie_params(0,"/",".my-domain.com");
session_start();
// include facebook class
try {
$fb = new Facebook(array(
'appId' => $facebook_app_id,
'secret' => $facebook_app_secret,
'cookie' => true
));
} catch(FacebookAPIException $e) {
// no active fb session
}
// other content here
try {
$uid = $fb->getUser();
if($uid) {
$user = $fb->api('/me','GET');
}
} catch(FacebookApiException $e) {
// not logged in
}
Now the problem is that this code works perfect on my-domain.com but not on subdomain.my-domain.com.
Even if I successfully authenticate on the main domain my-domain.com, when I'm visiting subdomain.my-domain.com the session of the main domain is replaced and the connection is lost.
Note that in the case of subdomain.my-domain.com there is no API Exception thrown but the $uid is 0.
I've already set the domain on FB APP Settings page as my-domain.com.
Which is the problem here?

How to store google api (OAuth 2) permissions?

i'm using the examples provided in the "google-api-php-client"-Library (http://code.google.com/p/google-api-php-client/) to implement user login and authorization on my website with google services.
I didn't make any changes to the examples, except adding my Client-ID, etc..
The authorization itself works fine: Users can login and i can fetch the provided informations.
However, when leaving the page, the whole authorization procedure is called again; users are not remembered and need to grant permissions again, which is some kind of annoying and not typical for google-logins as i know them.
For example: On stackoverflow, i'm logged in with my google account.
Whenever i revisit this site, i'm logged in automaticly, or (if logged out) just have to log in again - i do not have to confirm the general rights again.
Using the examples on my site however, forces the user to allow access whenever the site is visited again.
Did i make any mistakes, when using the examples?
What do i have to do, to avoid the permission request over and over again?
Thanks in advance for any kind of help!
Use this code for first time to retrieve access_code and save it to database:
<?php
require 'google-api-php-client/src/Google_Client.php';
require 'google-api-php-client/src/contrib/Google_DriveService.php';
require 'google-api-php-client/src/contrib/Google_Oauth2Service.php';
session_start();
$client = new Google_Client();
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$client->setRedirectUri(REDIRECT_URI);
$client->setScopes(array(
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile'));
$client->setUseObjects(true);
$service = new Google_DriveService($client);
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
const ACCESS_TOKEN=$_SESSION['token'];
//code here to save in database
?>
Once ACCESS_TOKEN is saved in database change code to:
<?php
require 'google-api-php-client/src/Google_Client.php';
require 'google-api-php-client/src/contrib/Google_DriveService.php';
require 'google-api-php-client/src/contrib/Google_Oauth2Service.php';
session_start();
$client = new Google_Client();
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$client->setRedirectUri(REDIRECT_URI);
$client->setScopes(array(
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile'));
$client->setUseObjects(true);
$service = new Google_DriveService($client);
//ACCESS_TOKEN is already saved in database, is being saved on first time login.
$_SESSION['access_token'] = ACCESS_TOKEN;
if (isset($_SESSION['access_token'])) {
$client->setAccessToken($_SESSION['access_token']);
}
if ($client->getAccessToken())
{
$userinfo = $service->about->get();
echo '<script>console.log('.json_encode($userinfo).');</script>';
$userinfoService = new Google_OAuth2Service($client);
$user = $userinfoService->userinfo->get();
echo '<script>console.log('.json_encode($user).');</script>';
}
?>
That works fine for me.
Based on the kaushal's answer:
<?php
require_once 'globals.php';
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$client = new Google_Client();
// Get your credentials from the APIs Console
$client->setClientId('YOUR_ID');
$client->setClientSecret('YOUR_SECRET');
$client->setRedirectUri('REDIRECT_URI');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$service = new Google_DriveService($client);
$client->setUseObjects(true);
//if no token in the session
if ($_SESSION['google_token'] == '') {
//get stored token from DB
$sToken = $oDb->getOne("SELECT `google_token` FROM `users` WHERE `u_id` = " . (int)$_SESSION['user_id']);
//if no stored token in DB
if ($sToken == '') {
//autentificate user
$client->authenticate();
//get new token
$token = $client->getAccessToken();
//set token in session
$_SESSION['google_token'] = $token;
// set token in DB
$oDb->Query("UPDATE `users` SET `google_token`='$token' WHERE `u_id` = " . (int)$_SESSION['user_id']);
} else {
$_SESSION['google_token'] = $sToken;
}
}
$client->setAccessToken($_SESSION['google_token']);
//do what you wanna do with clients drive here
?>
The Google Drive SDK documentation includes a complete PHP sample application that you can use as a reference to get started:
https://developers.google.com/drive/examples/php
Basically, once the user is logged in and you retrieve access token and refresh token, you store those credentials in a database and reuse them instead of asking the user to authenticate every time.

Symfony REST API authentication without sfGuardPlugin

I'm trying to find information on securing a HTTP REST API in a Symfony project, but all I can find is information about using sfGuardPlugin. From what I can see, this plugin isn't very useful for web services. It tries to have user profile models (which aren't always that simple) and have "sign in" and "sign out" pages, which obviously are pointless for a stateless REST API. It does a lot more than I'll ever have need for and I what to keep it simple.
I want to know where to implement my own authorisation method (loosely based on Amazon S3's approach). I know how I want the authorisation method to actually work, I just don't know where I can put code in my Symfony app so that it runs before every request is processed, and lets approved requests continue but unsuccessful requests return a 403.
Any ideas? I can't imagine this is hard, I just don't know where to start looking.
There is a plugin for RESTful authentication -> http://www.symfony-project.org/plugins/sfRestfulAuthenticationPlugin
Not used it though ....
How where you planning to authenticate users ?
The jobeet tutorial uses tokens ... http://www.symfony-project.org/jobeet/1_4/Doctrine/en/15
I ended up finding what I was looking for by digging into the code for sfHttpAuthPlugin. What I was looking for was a "Filter". Some details and an example is described in the Askeet sample project.
Stick a HTTP basicAuth script in your <appname>_dev.php (Symfony 1.4 =<) between the project configuration "require" and the configuration instance creation.
Test it on your dev. If it works, put the code in your index.php (the live equivalent of <appname>_dev.php) and push it live.
Quick and dirty but it works. You may want to protect that username/password in the script though.
e.g.
$realm = 'Restricted area';
//user => password
$users = array('username' => 'password');
if (empty($_SERVER['PHP_AUTH_DIGEST'])) {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Digest realm="'.$realm.
'",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"');
die('Text to send if user hits Cancel button');
}
// || !isset($users[$data['username']]
// analyze the PHP_AUTH_DIGEST variable
if (!($data = http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) || !isset($users[$data['username']])) {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Digest realm="'.$realm.
'",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"');
die('Wrong Credentials!');
}
// generate the valid response
$A1 = md5($data['username'] . ':' . $realm . ':' . $users[$data['username']]);
$A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']);
$valid_response = md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2);
if ($data['response'] != $valid_response) {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Digest realm="'.$realm.
'",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"');
die('Wrong Credentials!');
}
// function to parse the http auth header
function http_digest_parse($txt)
{
// protect against missing data
$needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
$data = array();
$keys = implode('|', array_keys($needed_parts));
preg_match_all('#(' . $keys . ')=(?:([\'"])([^\2]+?)\2|([^\s,]+))#', $txt, $matches, PREG_SET_ORDER);
foreach ($matches as $m) {
$data[$m[1]] = $m[3] ? $m[3] : $m[4];
unset($needed_parts[$m[1]]);
}
return $needed_parts ? false : $data;
}
// ****************************************************************************
// ok, valid username & password.. continue...