How to connect to api using codeigniter - codeigniter

newbie here in Restful API. How can I connect to the API? I've tried several ways on how to connect it but nothing seems to work. I provided the restful API connection codes below but I don't know how to connect it. I have provided my codes below. Any help will be appreciated. Thank you.
Views:
<form action="<?=base_url('account/dologin');?>" method="post">
<!-- login -->
<form id="doLogin">
<div class="input-group mb-3 dropShadow" style="padding:35px 35px 5px 45px;">
<input type="text" class="signinrow" name="formUsername" placeholder="Username">
<div class="input-group-append">
<div class="input-group-text" style="background:transparent; border: none;">
<i class="fas fa-at"></i>
</div>
</div>
</div>
<div class="input-group mb-4 dropShadow" style="padding:1px 35px 25px 45px;">
<input type="password" class="signinrow" name="formPassword" placeholder="Password">
<div class="input-group-append">
<div class="input-group-text" style="background:transparent; border: none;">
<span class="fas fa-lock"></span>
</div>
</div>
</div>
<div class="text-bold text-sm afterLoginForm text-center" >
<p class=" mb-2" style="font-size: 18px;">
<a data-toggle="modal" data-target="#recoAcc" type="button" class="dropShadow bebas" ><u>I forgot my password </u></a><br>
</p>
</div>
<br>
<br>
<div>
<button id="btnSubmit"> Sign In</button>
<img id="submit_preloader" src="<?=pubPath('/assets/imgs/order_button_preloader.gif'); ?>" alt="Processing..." style=" display:none;" id="reg_preloader2" >
</div>
</form>
Controller:
public function dologin()
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy
{
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
}
$ci =& get_instance();
$username = $ci->input->post('formUsername');
$password= $ci->input->post('formPassword');
$ipAddress =$ip;
$baseSessionID = $ip.$username;
$url = "https://blabla.com/Auth/login";
$data_array = array('username' => $username,'password' => $password,'baseSessionID' => $baseSessionID,'ipAddress' => $ipAddress);
$data = http_build_query($data_array);
$data1 = array(
'Content-Type: application/x-www-form-urlencoded',
'Auth-Key: simplerestapi',
'Client-Service: frontend-client'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, $data1);
$reply=curl_exec($ch);
$decode = json_decode($reply,true);
$username1=$decode['message'];
$password1=$decode['password'];
$userfailed=$decode['mali'];
$_SESSION["username"] = $this->input->post("formUsername");
if($username1 ==='Successfully login.'||$password1 ==='Successfully login.'){ //Login success
redirect(site_url('account/dashboard'), $data);
}elseif($userfailed ==='failed username'){ //Wrong Username
echo '<script>alert("Wrong Password or Username!");</script>';
redirect(site_url(), $data);
curl_close($ch);

I use the following code which is tested with the wordpress API and codeigniter 3. You'll need to amend the $opts array.
$method would be post, get, put ...
$url the api url ...
$opts = array('https'=>array('method'=>"GET",'header'=>"Authorization: Bearer $token"));
public function CallAPI($method, $url, $opts = false)
{
$curl = curl_init();
switch ($method)
{
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($opts)
curl_setopt($curl, CURLOPT_POSTFIELDS, $opts);
break;
case "PUT":
curl_setopt($curl, CURLOPT_PUT, 1);
break;
default:
if ($opts)
$url = sprintf("%s?%s", $url, http_build_query($opts));
}
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
// The following is your code but slightly amended to change the header and suggest Authorization which is commented out. I also removed some unnecessary curl. I changed your $data_array to include the header but try it in its original form as well but with content-Type as application/json.
$url = "https://blabla.com/Auth/login";
$data_array = array('username' => $username,'password' =>
$password,'baseSessionID' => $baseSessionID,'ipAddress' => $ipAddress,
'https' => array('header' => 'Content-Type: application/json','Auth-Key:
simplerestapi', 'Client-Service: frontend-client'));
$data = http_build_query($data_array);
/*
$data1 = array(
//'Content-Type: application/x-www-form-urlencoded',
'Content-Type: application/json',
'Auth-Key: simplerestapi',
//'Authorization: Basic '. base64_encode("app_key:app_secret")
'Client-Service: frontend-client'
);
*/
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
//curl_setopt($ch, CURLOPT_HTTPHEADER, $data1);
$reply=curl_exec($ch);
if($e = curl_error($ch)){
echo $e;
}else{
echo $decode = json_decode($reply,true);
}
curl_close($ch);

Related

Integrating reCAPTCHA v2 to existing form

I'm having troubles integrating reCAPTCHA v2 with my existing form. I would be grateful if someone has the solution to this.
This is my form page HTML code where I'm adding the widget:
before /head tag:
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
In the body:
<div class='mod modContactForm'>
<form method="post" action="send.php" accept-charset="UTF-8"><p>
<label for='name'>Your Name</label>
<input class="input-text required" id="name" name="name" type="text" />
</p>
<p>
<label for='email'>Your Email</label>
<input class="input-text required email" id="email" name="email" type="text" />
</p>
<p>
<label for='message'>Your Message</label>
<textarea class="required" rows="5" cols="80" id="message" name="message"></textarea>
</p>
<form action="?" method="POST">
<div class="g-recaptcha" data-sitekey="--- MY SITE KEY HERE ---"></div>
<input class="button" type="submit" value="Send message">
<p class='thanks' style='display: none;'>
Thanks for contacting Video Production Edinburgh,<br />we'll be in touch within 24 hours!
</p>
</form>
Live page with not-working reCAPTCHA can be found here.
This is the send.php code on the server side to handle the form submission:
<?php
// Checks if form has been submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
function post_captcha($user_response) {
$fields_string = '';
$fields = array(
'secret' => '--- MY SECRET KEY HERE ----',
'response' => $user_response
);
foreach($fields as $key=>$value)
$fields_string .= $key . '=' . $value . '&';
$fields_string = rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
// Call the function post_captcha
$res = post_captcha($_POST['g-recaptcha-response']);
if (!$res['success']) {
// What happens when the CAPTCHA wasn't checked
echo '<p>Please go back and make sure you check the security CAPTCHA box.</p><br>';
} else {
// If CAPTCHA is successfully completed...
$to = "hello#videoproductionedinburgh.co.uk";
$name = $_POST['name'];
$subject = $_POST['subject'];
$body = stripslashes($_POST['message']);
$from = $_POST['email'];
$headers = "Reply-To: " . $from;
$error_messages = array();
if( strlen($name) < 1 ) {
$error_messages[] = "Name required";
}
if( strlen($subject) < 1 ) {
// set the default subject here
$subject = "Message from Video Production Edinburgh";
}
if( strlen($body) < 1 ) {
$error_messages[] = "Message required";
}
if( strlen($from) < 1 ) {
$error_messages[] = "Email required";
}
if(sizeof($error_messages) == 0 && mail($to, $subject, $body, $headers)) {
echo("success");
} else {
foreach( $error_messages as $error_message ) {
echo "$error_message <br />";
}
}
}
?>
At the moment the form submits successfully regardless of the reCAPTCHA being ticket or not.
Any help would be much apprecaited.
Thank you,
Paolo

How to get the main indicator?

I create script for check speed of sites
<form name="form1" method="post" action="">
<label for="url">URL:</label>
<input type="text" name="url" id="url">
<br>
<input type="submit" name="submit" id="submit" value="Send">
</form>
<?php
if((isset($_POST['url'])) and ($_POST['url']!=""))
{
echo "<h2>".$_POST['url']."</h2>";
// Generated by curl-to-PHP: http://incarnate.github.io/curl-to-php/
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url='.$_POST['url'].'&key=..........................');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
echo "<pre>".$result."</pre>";
}
?>
But in the results I can not find the most important value. I tried to analyze JSON which gives out a script, but I do not see anything similar. Maybe someone can advise where to get this figure?
In the JSON response you want:
['lighthouseResult']['categories']['performance']['score']
You are looking for this part of the response:
"categories": {
"performance": {
"id": "performance",
"title": "Performance",
"score": 1,
Notice that the score is expressed as a decimal, so 1 = 100, 0.5 = 50 etc.

Google Recatpcha v2 Invisible not working at all says missing-input-response

I have gone through various articles over Stack as well as google and done the following implementation in Codeigniter 3. My website is running over https.
Code in head
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script>
function onSubmit(token) {
document.getElementById("enquiryform").submit();
}
</script>
Code of Form
<?php
echo form_open('SubmitForm', array('id'=>'enquiryform'));
?>
<div class="row">
<div class="col-sm-12 col-md-12">
<div class="form-group">
<textarea type="text" class="form-control" rows="5" cols="3" name="message" placeholder="Message"></textarea>
</div>
<div class="text-center contact-page-button">
<button class="g-recaptcha btn btn-danger border-0" data-sitekey="my_site_key" data-callback='onSubmit'>Submit</button>
<input type="reset" class="btn btn-danger border-0"></input>
</div>
</div>
</div>
<?php
echo form_close();
?>
Code in Controller Function
$this->load->library('curl');
if($this->input->post('g-recaptcha-response'))
{
$recaptchaResponse = trim($this->input->post('g-recaptcha-response'));
$userIp=$this->input->ip_address();
$secret='my_secret_key';
$url="https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response;=".$recaptchaResponse."&remoteip;=".$userIp;
$response = $this->curl->simple_get($url);
$status= json_decode($response, true);
//print_r($recaptchaResponse); //prints the data
//echo "<br>";
//print_r($url); //prints the data
//echo "<br>";
//print_r($status); //prints the data
//echo "<br>";
if($status['success'] == 1) {
//True - EXECUTE SOMETHING
} else {
//False - What happens when user is not verified
$data['response']="<div class='alert alert-danger'>Failed to verify that you are a Human. Please Try again.</div>";
}
I have even tried file_get_contents method but the result is same. I always get
Array ( [success] => [error-codes] => Array ( [0] => missing-input-response ) )
I have checked the site and secret keys multiple times, they are correct. I have even placed a separate div for g-recaptcha which shows checkbox version but I still get the same errror.
What is the solution?
Problem is in your server side code. You need to send POST request instead of GET.
$url="https://www.google.com/recaptcha/api/siteverify";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS,"secret=".$secret."&response=".$recaptchaResponse."&remoteip=".$userIp);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

I want to create label in gmail using google-api but i get error Token invalid - AuthSub token has wrong scope

My client_id, secret_id, developer_key and redirect_uri for auth request is set in config file which is included.
I use following code for create label in gmail account using google-api-php-client :-
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// set include path for google php client library
set_include_path( get_include_path() . PATH_SEPARATOR . 'google-api-php-client-master/src' );
require_once 'google-api-php-client-master/src/Google/Client.php';
$client = new Google_Client();
// call when redirect after callback by google oauth
if (isset($_GET['code']))
{
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
if (isset($_SESSION['access_token']) && $_SESSION['access_token'])
{
$client->setAccessToken($_SESSION['access_token']);
}
$data = '<?xml version="1.0" encoding="utf-8"?>
<atom:entry xmlns:atom="http://www.w3.org/2005/Atom" xmlns:apps="http://schemas.google.com/apps/2006">
<apps:property name="label" value="TestCreatedByApi" />
</atom:entry>';
$headers = array(
"X-HTTP-Method-Override: POST",
"Authorization: Bearer $access_token",
"Content-type: application/atom+xml"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://apps-apis.google.com/a/feeds/emailsettings/2.0/google.com/{username}/label");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
print_r($response = curl_exec($ch));
}
$client->addScope("https://www.googleapis.com/auth/userinfo.email");
$client->addScope("https://mail.google.com");
$authUrl = $client->createAuthUrl();
?>
This is view section of code:
<div class="box">
<div class="request">
<?php if (isset($authUrl)): ?>
<a class='login' href='<?php echo $authUrl; ?>'>Connect Me!</a>
<?php else: ?>
<form id="url" method="GET" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input name="url" class="url" type="text">
<input type="submit" value="Shorten">
</form>
<a class='logout' href='?logout'>Logout</a>
<?php endif ?>
</div>
<?php if (isset($short)): ?>
<div class="shortened">
<?php var_dump($short); ?>
</div>
<?php endif ?>
</div>
I use for add scope to create label:
$client->addScope("https://www.googleapis.com/auth/userinfo.email");
$client->addScope("https://mail.google.com");
I get following error:
Token invalid - AuthSub token has wrong scope
Error 401
The right scope for creating a email label is
https://apps-apis.google.com/a/feeds/emailsettings/2.0/
check out documentation here: https://developers.google.com/admin-sdk/email-settings/auth
and also here:
https://developers.google.com/admin-sdk/email-settings/#manage_labels

Send/Include 'name' field to Mailchimp using API with AJAX

I need to know how to send the 'name' field to Mailchimp so that it shows the 'name' the user submitted under the name column on the 'subscribers' page in Mailchimp.
The form looks like this:
<div id="email">
<form action="subscribe.php" id="invite" method="POST">
<input type="text" placeholder="Enter your name.." name="name" id="name" class="name" data-validate="validate(name)"/>
<input type="email" placeholder="and your email address.." name="email" id="MCE-email" class="email" data-validate="validate(required, email)"/>
<p>If you agree with the Terms and Privacy, please press the submit button below.</p>
<div class="clear"><input type="submit" value="Submit" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
</form>
<div id="clear"></div>
<div id="result"></div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#invite').ketchup().submit(function() {
if ($(this).ketchup('isValid')) {
var action = $(this).attr('action');
$.ajax({
url: action,
type: 'POST',
data: {
email: $('#MCE-email').val()
},
success: function(data){
$('#result').html(data).css('color', '#a1a1a1', 'padding', '10px 0px 0px 0px');
},
error: function() {
$('#result').html('Sorry, an error occurred.').css('color', 'white');
}
});
}
return false;
});
});
v</script>
The subscribe.php script looks like this :
<?php
$apiKey = 'MYAPIKEY';
$listId = 'MYLISTID';
$double_optin=false;
$send_welcome=false;
$email_type = 'html';
$email = $_POST['email'];
$name = $_POST['name'];
//replace us2 with your actual datacenter
$submit_url = "http://us5.api.mailchimp.com/1.3/?method=listSubscribe";
$data = array(
'email_address'=>$email,
'apikey'=>$apiKey,
'id' => $listId,
'double_optin' => $double_optin,
'send_welcome' => $send_welcome,
'email_type' => $email_type
);
$payload = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $submit_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode($payload));
$result = curl_exec($ch);
curl_close ($ch);
$data = json_decode($result);
if ($data->error){
echo $data->error;
} else {
echo "Thank you for your email. We'll keep you up to date..";
}
?>
The field tag of the 'name' field on my form in Mailchimp is 'NAME'
I hope this is all the information you need and it makes sense..
Thank you greatly.
Going off of the Mailchimp listSubscribe function documentation found here:
http://apidocs.mailchimp.com/api/1.3/listsubscribe.func.php
You just need to create a merge_vars array that will hold any additional fields associated with the subscribing email. For example:
$merge_vars = array('FNAME'=>'first name', 'LNAME'=>'last name');
And then just pass that array in your $data.

Resources