Google Contacts API v3 - How to Fetch contacts with email id? - php

Is there a way to fetch Google contacts(Google Contacts API v3) with email id?
What I have done so far is :
$client_id=$this->config->item('google_access_key');
$client_secret=$this->config->item('google_secret_key');
$redirect_uri=$this->config->item('google_callback_url');
$max_results = 9999;
$auth_code = $_GET["code"];
$fields=array(
'code'=> urlencode($auth_code),
'client_id'=> urlencode($client_id),
'client_secret'=> urlencode($client_secret),
'redirect_uri'=> urlencode($redirect_uri),
'grant_type'=> urlencode('authorization_code')
);
$post = '';
foreach($fields as $key=>$value) { $post .= $key.'='.$value.'&'; }
$post = rtrim($post,'&');
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,'https://accounts.google.com/o/oauth2/token');
curl_setopt($curl,CURLOPT_POST,5);
curl_setopt($curl,CURLOPT_POSTFIELDS,$post);
curl_setopt($curl, CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,0);
$result = curl_exec($curl);
curl_close($curl);
$response = json_decode($result);
$accesstoken = $response->access_token;
$url = 'https://www.google.com/m8/feeds/contacts/default/full?oauth_token='.$accesstoken;
$xmlresponse = $this->curl_file_get_contents($url);
if((strlen(stristr($xmlresponse,'Authorization required'))>0) && (strlen(stristr($xmlresponse,'Error '))>0))
{
$msg = "OOPS !! Something went wrong. Please try reloading the page.";
$newdata = array('msg' => $msg);
$this->session->set_userdata('message_session', $newdata);
redirect('admin/social_account_master');
}
$xml = new SimpleXMLElement($xmlresponse);
$xml->registerXPathNamespace('gd', 'http://schemas.google.com/g/2005');
foreach ($xml as $title)
{
echo $title->title . "<br>";
}
To fetch email details I used:
$result = $xml->xpath('//gd:email');
But how can I match email details with respective contact details?

echo "<h3>Email Addresses:</h3>";
$xml = new SimpleXMLElement($xmlresponse);
$xml->registerXPathNamespace('gd', 'http://schemas.google.com/g/2005');
$result = $xml->xpath('//gd:email');
foreach ($result as $title) {
echo $title->attributes()->address . "<br>";
}
?>
i to used only email to retrive from google contacts how to retrive phone number and other detaisl

Related

Api Oppwa payment button, Problems with a foreach

I am integrating a Payment Button with Oppwa API,
But with the method that brings me the "CheckoutId".
What happens I have to send all the parameters.
$total = 120;
$iva = 004012000000000012;
$totalTarifa12 = 053012000000000100;
$totalBase0 = 052012000000000200;
$email = "JonathanVeraMarin98#outlook.com";
$primer_nombre = "Jonathan";
$segundo_nombre = "Fernando";
$apellido = "Vera";
$cedula = "0952152525";
$trx = 123456789;
$ip_address = '05100817913101';
$finger = 'https://test.oppwa.com/v1/checkouts';
$merchterm= '1000000505_PD100406';
$telefono ='2172161';
$direccion_cliente = 11222;
$pais_cliente = 121212;
$direccion_entrega = '1600 Pennsylvania Ave NW';
$pais_entrega = 121212;
$checkoutId = prepareCheckout($items,$total,$iva,$totalTarifa12,$totalBase0,$email,$primer_nombre,$segundo_nombre,$apellido,$cedula,$trx,$ip_address,$finger,$merchterm,$telefono,$direccion_cliente,$pais_cliente,$direccion_entrega,$pais_entrega);
These are the values ​​of the burned parameters that I sent to the function
function prepareCheckout($items,$total,$iva,$totalTarifa12,$totalBase0,$email,$primer_nombre
,$segundo_nombre,$apellido,$cedula,$trx,$ip_address,$finger,$merchterm,
$telefono,$direccion_cliente,$pais_cliente,$direccion_entrega,$pais_entrega){
$finger = urlencode($finger);
$i =0;
$url = "https://test.oppwa.com/v1/checkouts";
$iva = str_replace('.', '', $iva);
$totalTarifa12 = str_replace('.', '', $totalTarifa12);
$totalBase0 = str_replace('.', '', $totalBase0);
$valueIva = str_pad($iva,12,'0'.STR_PAD_LEFT);
$valueTotalIva = str_pad($totalTarifa12,12,'0'.STR_PAD_LEFT);
$valueIvaTotalBase0 = str_pad($totalBase0,12,'0'.STR_PAD_LEFT);
$data = "authentication.userId=8a8294184b4f2868014b4f86f767015d" .
"&authentication.password=F8T7N4PD" .
"&authentication.entityId=8a8294184b4f2868014b4f87bf160173" .
"&amount=".$total.
"&currency=USD".
"&paymentType=DB".
"&customer.givenName=".$primer_nombre.
"&customer.middleName=".$segundo_nombre.
"&customer.surname=".$apellido.
"&customer.ip=".$ip_address.
"&customer.merchantCustomerId=00000000001".
"&merchantTransactionId=transaction_".$trx.
"&customer.email=".$email.
"&customer.identificationDocType=IDCAD".
"&customer.identificationDocId=".$cedula.
"&customer.phone=".$telefono.
"&billing.street1=".$direccion_cliente.
"&billing.country=".$pais_cliente.
"&shipping.street1=".$direccion_entrega.
"&shipping.country=".$pais_entrega.
"&risk.paramters[USER_DATA2]=MiComercio".
"customParamters[".$merchterm."]=00810030070103910004012".$valueIva.
"05100817913101052012".$valueIvaTotalBase0."053012".$valueTotalIva;
foreach ($items["cart"] as $c )
{
$data.="&cart.items[".$i."].name =".$c["product_name"];
$data.="&cart.items[".$i."].description ="."Descripcion: ".$c["product_name"];
$data.="&cart.items[".$i."].price =".$c["product_price"];
$data.="&cart.items[".$i."].quantity= ".$c["q"];
}
$data.= "&testMode=EXTERNAL";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization:Bearer OGE4Mjk0MTg1MzNjZjMxZDAxNTMzZDA2ZmQwNDA3NDh8WHQ3RjIyUUVOWA=='));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// this should be set to true inproduction
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$responseData = curl_exec($ch);
if(curl_errno($ch)) {
return curl_error($ch);
}
curl_close($ch);
return $responseData;
}
My function that generates a checkoutId.
The problem I have is in the foreach I know that it is going through an array but I get an error because I don't know what the condition $ items ['cart'] refers to
foreach ($items["cart"] as $c )
{
$data.="&cart.items[".$i."].name =".$c["product_name"];
$data.="&cart.items[".$i."].description ="."Descripcion: ".$c["product_name"];
$data.="&cart.items[".$i."].price =".$c["product_price"];
$data.="&cart.items[".$i."].quantity= ".$c["q"];
}
I've tried it like this
$items = array();
$items['product_name'] = 'Software';
$items['product_name'] = 'Hola';
$items['product_price'] = '50';
$items['q'] = '1';
I hurt:
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\Datafast\index.php on line 63
`

Sandbox Paypal Checkout (PHP, Laravel)

I'm trying to implement Paypal's checkout to my Laravel Api (connected to an Ionic app) and it gets stuck when in the app I press the button to checkout and it goes to Paypal (so far so good) in the login screen. I found it weird because it wouldn't let me login with my sandbox account or even my real account, the error is the same: "Some of your info isn't correct. Please try again." By opening developer tools, those are the errors I get (see screenshots). I really couldn't find where I'm making a mistake here. Maybe you can help me. Below are the screenshots and the code that makes takes the checkout to Paypal. Let me know if I should add any extra info here! Thanks a lot!
error 1: ,
investigating one of the console errors:
Route::middleware('auth:api')->post('/paypal', function (Request $request) {
$user = $request->user();
$data = $request->all();
$list_products_id = $data;
$products = [];
$total = 0;
$titles = '';
foreach($list_products_id as $key => $value) {
$product = Product::find($value);
if($product){
$products[$key] = $product;
$total += $product->price;
$titles .= $product->title." ";
}
}
if($total){
$paypal = config('app.paypal', "sandbox");
if($paypal == "sandbox"){
$userProvider = 'In my app I have the sandbox business credentials here';
$pwdProvider = 'In my app I have the sandbox business credentials here';
$signProvider = 'In my app I have the sandbox business credentials here';
$url = 'https://api-3t.sandbox.paypal.com/nvp';
$url2 = 'https://www.sandbox.paypal.com/cgi-bin/webscr?%s';
} else {
$userProvider = '';
$pwdProvider = '';
$signProvider = '';
$url = 'https://api-3t.paypal.com/nvp';
$url2 = 'https://www.paypal.com/cgi-bin/webscr?%s';
}
$data = [];
$data['USER'] = $userProvider;
$data['PWD'] = $pwdProvider;
$data['SIGNATURE'] = $signProvider;
$data['METHOD'] = 'SetExpressCheckout';
$data['VERSION'] = '108';
$data['LOCALECODE'] = 'en_US';
$data['L_PAYMENTREQUEST_0_NAME0'] = "Products Orders";
$data['L_PAYMENTREQUEST_0_DESC0'] = $titles;
$data['PAYMENTREQUEST_0_AMT'] = number_format($total, 2).'';
$data['PAYMENTREQUEST_0_CURRENCYCODE'] = 'EUR';
$data['PAYMENTREQUEST_0_PAYMENTACTION'] = 'Sale';
$data['L_PAYMENTREQUEST_0_QTY0'] = '1'; //number of the same product the user is ordering
$data['L_PAYMENTREQUEST_0_AMT0'] = number_format($total, 2).'';
$data['L_BILLINGAGREEMENTDESCRIPTION0'] = $titles;
$data['CANCELURL'] = url('/');
$data['RETURNURL'] = url('/');
// curl
$data = http_build_query($data);
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($curl);
curl_close($curl);
$nvp = array();
if (preg_match_all('/(?<name>[^\=]+)\=(?<value>[^&]+)&?/', $response, $matches)) {
foreach ($matches['name'] as $offset => $name) {
$nvp[$name] = urldecode($matches['value'][$offset]);
}
}
if(isset($nvp['ACK']) && $nvp['ACK'] == "Success" ){
$query = array(
'cmd' => '_express-checkout',
'token' => $nvp['TOKEN']
);
$redirectURL = sprintf($url2, http_build_query($query));
return ['date'=>$redirectURL];
}else{
return ['status'=>'error purchasing! - 1'];
}
}
echo "total: " . $total;
return ['status'=>'error purchasing! - 2'];
});
so I did a password reset on my sandboxes account and it worked!

Telegram bot Inline keyboards sends too many callbacks PHP

So problem is I am using inline keyboard in my bot. And when I am trying to push this keyboard it gives me 3-5 callbacks. I don't know where is my mistake.
EDIT
I don't know why but it causes this error when i working with mysqli->fetch_assoc();
There is not full code just peace where I use inline keyboard
if ($callback_data!=Null){
checkJSON(3124,$order_id);
$message_id = $update['callback_query']['message']['message_id'];
$callback_data = json_decode($callback_data,true);
checkJSON(3125,$callback_data["order_id"]);
$order_id = $callback_data["order_id"];
checkJSON(3126,$order_id);
$rs = $mysqli->query("SELECT manager_id FROM orders WHERE id=".$order_id);
$row = $rs->fetch_assoc();
$manager = $row['manager_id'];
if ($manager!=Null){
$rs = $mysqli->query("SELECT telegram_id FROM managers WHERE id=".$manager);
$row = $rs->fetch_assoc();
$manager_telegram_id = $row['telegram_id'];
if ($chatID==$manager_telegram_id){
$callback_data = json_decode($callback_data);
$order_id = $callback_data["order_id"];
$status = $callback_data["status"];
checkJSON(1231234,$callback_data);
if($status == '3'){
editMessage($chatID,$message_id,"Заказ N".$order_id." подтвержден");
}
else{
editMessage($chatID,$message_id,"Заказ N".$order_id." отклонен");
}
$mysqli->query("UPDATE orders SET status=".$status." WHERE id=".$order_id);
}
sendMessage($chatID,$update['callback_query']['message']['message_id']);
editMessage($chatID,$message_id,
"Данный заказ уже в оброботке");
}
else{
$get_manager_query = $mysqli->query("SELECT id FROM managers WHERE telegram_id=".$chatID);
$row = $get_manager_query->fetch_assoc();
$manager = $row['id'];
$data1 = json_encode(array("order_id"=>$order_id,"status"=>3));
$data2 = json_encode(array("order_id"=>$order_id,"status"=>4));
$inline_button1 = array("text"=>"Принять","callback_data"=>$data1);
$inline_button2 = array("text"=>"Отказать","callback_data"=>$data2);
$inline_keyboard = [[$inline_button1,$inline_button2]];
$keyboard=json_encode(array("inline_keyboard"=>$inline_keyboard));
editMessage($chatID,$message_id,
"Вы приняли данный заказ",$keyboard);
$rs = $mysqli->query("UPDATE orders SET status=1, manager_id=".$manager." WHERE id=".$order_id);
}
}
function sendMessage($chatID,$text){
$sendto =API_URL."sendmessage?chat_id=".$chatID."&text=".urlencode($text);
file_get_contents($sendto);
}
function editMessage($chatId, $messageId, $message,$replyMarkup=Null) {
$url = API_URL."editMessageText?chat_id=".$chatId."&message_id=".$messageId.
"&text=".urlencode($message)."&reply_markup=".$replyMarkup;
file_get_contents($url);
}
It's Not your mistake!
Telegram Server is send callbacks for every changes in inline query.
You can setting that to off in BotFatherwith /setinlinefeedback command.
For more information visit this
Set your data by some separator After, get that data by $update['callback_query']['data'] and split by seted separator.
$botToken = "(your token)";
$website = "https://(site_url)/bot" . $botToken;
$order_id = '44423'; //my additional data
$keyboard = ["inline_keyboard" => [
[
[
"text" => "Доставлено",
"callback_data" => "delivered_".$order_id, // set few data by '_' separator Like ("delivered_443423_phone12345667_...)
],
[
"text" => "Затримуюсь",
"callback_data" => "delaying_".$order_id,
]
],
]
];
$params = [
'chat_id' => $chat_id,
'text' => $msg,
'parse_mode' => 'html',
'reply_markup' => json_encode($keyboard),
];
$ch = curl_init($website . '/sendMessage');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
Update processing. For get update you need set webhook on file where bot is placed. https://api.telegram.org/bot(your token)/setWebhook?url=https://example.com/bot_directory/bot.php Site must have SSL (https).
$update = json_decode(file_get_contents('php://input'), TRUE);
$botToken = "(your token)";
$botAPI = "https://api.telegram.org/bot" . $botToken;
$msg = $update['message']['text'];
$user_id = $update['message']['from']['id'];
if (isset($update['callback_query'])) {
$update_multiple = explode('_', $update['callback_query']['data']); //split data
if ($update_multiple[0] == 'delivered') {
$data1 = $update_multiple[1]; // get some data
// ......
}
}

Webapplication stops running code after calling function from another file

My web app stops when it tries executing a function from another file. I am using a include_once to include the file where the function is. I am also pretty sure that the path is correct. (if there is anyway to check let me know). the functions which I am trying to use are written in the class.connections.php . Also as you can see I am echoing 2 test. Only the first one shows.
Invite.php
global $page_array ;
global $current_user ;
include_once(DITC_PATH."/class.friends.php");
include_once(DITC_PATH."/class.connections.php");
$process_status = $current_user->process_hotmail_contacts ;
global $page_array ;
if($page_array['url']['3'] == 'hotmail'){
$process_source = 'hotmail' ;
};
if($_GET['code']){
echo "Test 1 - ";
$access_token_json = get_hotmail_access_token();
echo "Test 2 - ";
if($access_token_json){
echo 'test';
update_user_meta($current_user->ID, 'hotmail_access_token', $access_token_json);
$taskurl = "/tasks";
$data = array();
$data['type'] = 'process_hotmail_contacts';
$data['lang'] = get_site_language();
$data['access_token'] = $access_token_json ;
$data['user_id'] = $current_user->ID ;
$options = array();
add_task($taskurl, $data, $options);
$process_status = 'busy' ;
$process_source = 'hotmail' ;
};
}
$ditc_title = _t("Invite connections") ;
get_header();
function in class.connections
function get_hotmail_access_token(){
global $hotmail_creds;
$fields=array(
'code'=> urlencode($hotmail_creds['auth_code']),
'client_id'=> urlencode($hotmail_creds['client_id']),
'client_secret'=> urlencode($hotmail_creds['client_secret']),
'redirect_uri'=> urlencode($hotmail_creds['redirect_uri']),
'grant_type'=> urlencode('authorization_code')
);
$post = '';
foreach($fields as $key=>$value) { $post .= $key.'='.$value.'&'; }
$post = rtrim($post,'&');
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,'https://login.live.com/oauth20_token.srf');
curl_setopt($curl, CURLOPT_POST,5);
curl_setopt($curl, CURLOPT_POSTFIELDS,$post);
curl_setopt($curl, CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,0);
$result = curl_exec($curl);
curl_close($curl);
$response = json_decode($result);
$access_token_json = $response->access_token;
return $access_token_json;
};

Failing to get yahoo access token

Recently, I'm developing my site with social networking, and want to import gmail,yahoo,hotmail etc.. contacts.
I have already grabbed contacts from Gmail and now next want to do the same with Yahoo. Reading the Yahoo documentation and following my gmail code, I get the authorisation screen and get the auth code back, but unable to get the access token. (I am using curl and I am expecting help related to it).
Here is the dump: string
'code=hzbp3px&client_id=dj0yJmk9WlJ0a3dmQTQ3ZFcyJmQ9WVdrOVFXRXliSFpMTm1zbWNHbzlNQS0tJnM9Y29uc3VtZXJzZWNyZXQmeD1jZA--&client_secret=5b3a803684538bae27519af3e34f3e268da432a1&redirect_uri=http://localhost/DEVELOPMENT/Grabber.php&grant_type=authorization_code' (length=254)
object(stdClass)[5] public 'error' => string 'invalid_request'
(length=15)
Here is my functions:
public function get_url(){
global $session;
switch ($session->get_provider()) {
case "gmail": return "https://accounts.google.com/o/oauth2/token";
break;
case "yahoo": return "https://api.login.yahoo.com/oauth2/get_token";
break;
}
}
public function curl_query($post,$boolean){
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,$this->get_url());
curl_setopt($curl,CURLOPT_POST,true);
curl_setopt($curl,CURLOPT_POSTFIELDS,$post);
curl_setopt($curl, CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,0);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
$result = curl_exec($curl);
curl_close($curl);
$response = json_decode($result);
var_dump($response);
//exit;
switch ($boolean) {
case "true": return $response->access_token;
case "false": return $response->refresh_token;
}
}
public function get_access_token($auth_code){
global $session;
switch ($session->get_provider()) {
case "gmail": return $this->curl_query($this->post_params($auth_code,'access_token'),true);
case "yahoo":
$accesstoken = $this->curl_query($this->post_params($auth_code,'access_token'),true);
//$refreshtoken = $this->curl_query($this->post_params($accesstoken),false);
return $accesstoken;
}
}
public function post_params($auth_code,$token){
global $session;
if($token == 'access_token'){
$fields=array(
'code'=> $auth_code,
'client_id'=> $session->get_client_id(),
'client_secret'=> $session->get_client_secret(),
'redirect_uri'=> $session->get_redirect_uri(),
'grant_type'=> 'authorization_code'
);
} else if($token == 'refresh_token'){
$fields=array(
'refresh_token'=> $auth_code,
'client_id'=> $session->get_client_id(),
'client_secret'=> $session->get_client_secret(),
'redirect_uri'=> $session->get_redirect_uri(),
'grant_type'=> 'authorization_code'
);
}
$post = '';
foreach($fields as $key=>$value) { $post .= $key.'='.$value.'&'; }
$post = rtrim($post,'&');
var_dump($post);
return $post;
}
I found out how to get the tokens, here is the code if anyone needs it
Anyway oauth2 is not working with yahoo as i experienced, bellow i am using oauth1.0
public function get_gmail_access_token($auth_code){
global $session;
$fields=array(
'code'=> $auth_code,
'client_id'=> $session->get_client_id(),
'client_secret'=> $session->get_client_secret(),
'redirect_uri'=> $session->get_redirect_uri(),
'grant_type'=> 'authorization_code'
);
$post = '';
foreach($fields as $key=>$value) { $post .= $key.'='.$value.'&'; }
$post = rtrim($post,'&');
$url = 'https://accounts.google.com/o/oauth2/token';
$result = $this->curl_query_post($url,$post);
$response = json_decode($result);
return $response->access_token;
}
public function get_yahoo_access_token($token,$verifier){
global $session;
$tokens = array();
$fields=array(
'oauth_version'=> '1.0',
'oauth_nonce'=> rand(),
'oauth_consumer_key'=> $session->get_client_id(),
'oauth_signature'=> $session->get_client_secret().'%26'.$session->get_token_secret(),
'oauth_timestamp'=> time()+3600,
'oauth_signature_method'=> 'plaintext',
'oauth_token'=> $token,
'oauth_verifier'=> $verifier,
'oauth_callback'=> $session->get_redirect_uri()
);
$post = '';
foreach($fields as $key=>$value) { $post .= $key.'='.$value.'&'; }
$post = rtrim($post,'&');
$url = 'https://api.login.yahoo.com/oauth/v2/get_token';
$result = $this->curl_query_post($url,$post);
$string = parse_str($result);
$tokens['oauth_token'] = $oauth_token;
$tokens['oauth_token_secret'] = $oauth_token_secret;
//$xoauth_yahoo_guid;
return $tokens;
}

Categories