Prestashop 1.5 Webservice Updating Customer id_default_group PHP - web-services

I need to automatically update the prestashop->customers->customer->id_default_group value using PHP via the Prestashop webservice. The script knows the new value and it is done before/as the page loads.
I can get a customer record, or I can get just the "id_default_group" of a customer record but I run into trouble when I try changing the record value and updating the webservice. I get back "HTTP/1.1 400 Bad Request".
It seems like I am incorrectly trying to update the xml or object.
It would be preferable to do all this by only getting and updating the "id_default_group" and not having to retrieve the complete customer record.
I have:
define('DEBUG', true);
define('PS_SHOP_PATH', 'http://www.site.com/');
define('PS_WS_AUTH_KEY', 'yuyiu');
require_once('../PSWebServiceLibrary.php');
// First : We always get the customer's list or a specific one
try
{
$webService = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, DEBUG);
$opt = array('resource' => 'customers'); // Full customer record
//$opt = array('resource'=>'customers','display'=> '[id_default_group]','filter[id]' => '['.$_SESSION["iemIdCustomer"].']'); // Customer id_default_group value
if (isset($_SESSION['iemIdCustomer'])){
$opt['id'] = $_SESSION['iemIdCustomer'];
}
$xml = $webService->get($opt);
// The elements from children
$resources = $xml->children()->children();
// $resources = $xml->children()->children()->children(); // If just getting id_default_group
}
catch (PrestaShopWebserviceException $e)
{
// Here we are dealing with errors
$trace = $e->getTrace();
if ($trace[0]['args'][0] == 404) echo 'Bad ID';
else if ($trace[0]['args'][0] == 401) echo 'Bad auth key';
else echo 'Other error';
}
// Second : We update the data and send it to the web service
if (isset($_SESSION['iemIdCustomer'])){
// Update XML with new values
$xml->customers->customer->id_default_group = 4;
//$resources = $xml->children()->children()->children();
// And call the web service
try
{
$opt = array('resource' => 'customers');
//$opt = array('resource'=>'customers','display'=> '[id_default_group]','filter[id]' => '['.$_SESSION["iemIdCustomer"].']');
$opt['putXml'] = $xml->asXML();
$opt['id'] = $_SESSION['iemIdCustomer'];
//$opt['display'] = 'id_default_group';
$xml = $webService->edit($opt);
// if WebService succeeds
echo "Successfully updated.";
}
catch (PrestaShopWebserviceException $ex)
{
// Dealing with errors
$trace = $ex->getTrace();
if ($trace[0]['args'][0] == 404) echo 'Bad ID';
else if ($trace[0]['args'][0] == 401) echo 'Bad auth key';
else echo 'Other error<br />'.$ex->getMessage();
}
}
This is basic for those in the know so I hope you can help.
Thanks in advance,
Lance

Ok I go the following to work.
The following line seem to do the trick:
$xml->children()->children()->id_default_group = 4;
Follows is the line with the rest of the code to do the task.
// Get the customer's id_default_group
try
{
$webService = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, DEBUG);
$opt = array('resource' => 'customers');
$opt['id'] = $_SESSION["iemIdCustomer"];
$xml = $webService->get($opt);
// Get the elements from children of customer
$resources = $xml->children()->children()->children();
}
catch (PrestaShopWebserviceException $e)
{
// Here we are dealing with errors
$trace = $e->getTrace();
if ($trace[0]['args'][0] == 404) echo 'Bad ID';
else if ($trace[0]['args'][0] == 401) echo 'Bad auth key';
else echo 'Other error';
}
// Update the data and send it to the web service
// Update XML with new value
$xml->children()->children()->id_default_group = 4;
// And call the web service
try
{
$opt = array('resource' => 'customers');
//$opt = array('resource'=>'customers','display'=> '[id_default_group]','filter[id]' => '['.$_SESSION["iemIdCustomer"].']');
$opt['putXml'] = $xml->asXML();
$opt['id'] = $_SESSION['iemIdCustomer'];
//$opt['display'] = 'id_default_group';
$xml = $webService->edit($opt);
// if WebService don't throw an exception the action worked well and we don't show the following message
echo "Successfully updated.";
}
catch (PrestaShopWebserviceException $ex)
{
// Here we are dealing with errors
$trace = $ex->getTrace();
if ($trace[0]['args'][0] == 404) echo 'Bad ID';
else if ($trace[0]['args'][0] == 401) echo 'Bad auth key';
else echo 'Other error<br />'.$ex->getMessage();
}
Hope that it assists someone.

i think you have this error because you are editing the bad node ;)
try with
$xml->customer->id_default_group = 4;
That should be OK :)

Related

Trying to change the company (team) application status from Drupal 8 portal (APIGEE Edge)

I Can't change the company app status Approved/Revoked, I tried to load and update the team_app entity using EntityTypeManager, and the other values have been updated without any issues like (callback URL, Description, Dispalyname, and custom attributes) but still the app status won't change/update,
$app_storage = \Drupal::entityTypeManager()->getStorage('team_app');
$app_ids = $app_storage->getQuery()
->condition('companyName', $team->id())
->condition('name', $app_mame)
->execute();
if (!empty($app_ids)) {
$app_id = reset($app_ids);
$loaded_app = $app_storage->load($app_id);
$loaded_app->set('status', 'revoked');
$loaded_app->save();
}
Also, I tried to make a PUT API request to change the app status with the same results, No status value changed.
/** #var \Drupal\apigee_edge\SDKConnectorInterface $sdk_connector */
$sdk_connector = \Drupal::service('apigee_edge.sdk_connector');
try {
$sdk_connector->testConnection();
$client = $sdk_connector->getClient();
}
catch (\Exception $exception) {
dump('client is not defined');
die();
}
$endpoint = $client->getUriFactory()
->createUri("/organizations/{$sdk_connector->getOrganization()}/companies/{$team->id()}/apps/{$loaded_app->getName()}");
try {
$response = $client->get($client->getEndpoint() . $endpoint);
$results = json_decode((string) $response->getBody());
$results->status = 'revoked';
// PUT.
$endpoint = $client->getUriFactory()
->createUri("/organizations/{$sdk_connector->getOrganization()}/companies/{$team->id()}/apps/{$loaded_app->getName()}")
$response = $client->put($client->getEndpoint() . $endpoint, json_encode($results));
$results = (array) json_decode((string) $response->getBody());
}
catch (\Exception $exception) {
dump('error, not trigger');
}
Any help with this?

How to fix "fb_exchange_token parameter not specified"?

I cannot find any documentation on this.
Here is my code:
I'm using Laravel 5.5 and Facbook graph. Im posting to a page but I got this error fb_exchange_token parameter not specified but I have successfully logged in.
Due to shoddy documentation I cannot find anything on fb_exchange_token on the Facebook's website nor elsewhere.
Can anyone help?
{
$facebook = Facebooks::findOrFail($id);
$fb = new Facebook([
'app_id' => 'my_id', // Replace {app-id} with your app id
'app_secret' => 'my_secret',
'default_graph_version' => 'v3.3',
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['manage_pages', 'publish_pages']; // optional
try {
if (isset($_SESSION['facebook_access_token'])) {
$accessToken = $_SESSION['facebook_access_token'];
} else {
$accessToken = $helper->getAccessToken();
}
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (isset($_SESSION['facebook_access_token'])) {
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
} else {
// getting short-lived access token
$_SESSION['facebook_access_token'] = (string) $accessToken;
// OAuth 2.0 client handler
$oAuth2Client = $fb->getOAuth2Client();
// Exchanges a short-lived access token for a long-lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
// setting default access token to be used in script
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
// redirect the user back to the same page if it has "code" GET variable
if (isset($_GET['code'])) {
header('Location: ./');
}
// getting basic info about user
try {
$profile_request = $fb->get('/me');
$profile = $profile_request->getGraphNode()->asArray();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
session_destroy();
// redirecting user back to app login page
header("Location: ./");
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
// post on behalf of page
$pages = $fb->get('/me/accounts');
$pages = $pages->getGraphEdge()->asArray();
foreach($pages as $key){
if($key['name'] == 'CloudGuest Test'){
if(isset($_POST['facebook_status'])){
$text1 = $_POST['facebook_status'];
$post = $fb->post('/' . $key['id'] . '/feed', array('message' =>$text1),$key['access_token']);
$post = $post->getGraphNode()->asArray();
print_r($post);
}
}
}
}

Facebook SDK returned an error: Cross-site request forgery validation failed. The state param from the URL and session do not match

I'm working with Laravel 5.2 and I'm using SammyK/laravel-facebook-sdk Package i Tried the code in the following link enter link description here
I keep on having this error : "Cross-site request forgery validation failed. The "state" param from the URL and session do not match."
this is my controller code :
public function callbackfbsdk(Facebook $fb){
$helper = $fb::getRedirectLoginHelper();
$loginUrl = $helper->getLoginUrl(['email']);
var_dump($loginUrl);
try {
$token = $fb::getAccessTokenFromRedirect();
} catch (Facebook\Exceptions\FacebookSDKException $e) {
dd($e->getMessage());
}
if (! $token) {
// Get the redirect helper
$helper = $fb::getRedirectLoginHelper();
if (! $helper->getError()) {
abort(403, 'Unauthorized action.');
}
// User denied the request
dd(
$helper->getError(),
$helper->getErrorCode(),
$helper->getErrorReason(),
$helper->getErrorDescription()
);
}
if (! $token->isLongLived()) {
$oauth_client = $fb::getOAuth2Client();
try {
$token = $oauth_client->getLongLivedAccessToken($token);
} catch (Facebook\Exceptions\FacebookSDKException $e) {
dd($e->getMessage());
}
}
$fb::setDefaultAccessToken($token);
Session::put('fb_user_access_token', (string) $token);
try {
$response = $fb::get('/me?fields=id,name,email');
} catch (Facebook\Exceptions\FacebookSDKException $e) {
dd($e->getMessage());
}
$facebook_user = $response->getGraphUser();
$user = App\User::createOrUpdateGraphNode($facebook_user);
// Log the user into Laravel
Auth::login($user);
return redirect('/')->with('message', 'Successfully logged in with Facebook');
}
Any Ideas about how can I solve this error??
why you are putting these line in callback
$helper = $fb::getRedirectLoginHelper();
$loginUrl = $helper->getLoginUrl(['email']);
it will try to generate link again after redirect.seperate it, will solve the problem

Undefined index: action error in facebook api

I am using php api's in my website (to make a profile page)
I am using the below code:
$action = $_REQUEST["action"];
switch($action){
case "fblogin":
include 'facebook.php';
$appid = "**********";
$appsecret = "*************************";
$facebook = new Facebook(array(
'appId' => $appid,
'secret' => $appsecret,
'cookie' => TRUE,
));
$fbuser = $facebook->getUser();
if ($fbuser) {
try {
$user_profile = $facebook->api('/me');
}
catch (Exception $e) {
echo $e->getMessage();
exit();
}
$user_fbid = $fbuser;
$user_email = $user_profile["email"];
$user_fnmae = $user_profile["first_name"];
$user_image = "https://graph.facebook.com/".$user_fbid."/picture?type=large";
$check_select = mysql_num_rows(mysql_query("SELECT * FROM `fblogin` WHERE email = '$user_email'"));
if($check_select > 0){
mysql_query("INSERT INTO `fblogin` (fb_id, name, email, image, postdate) VALUES ('$user_fbid', '$user_fnmae', '$user_email', '$user_image', '$now')");
}
}
break;
}
It gives an error saying : Undefined index: action
I am using wamp server as localhost. Please provide a solution

facebook registration plugin location field not writing to mysql

Everything else works fine except for the location. The actual city/state does not come across. Instead the word Array is displayed. My field type in the database is text but I've tried every field type through mysql. The HTML file is JSON where it comes to the field names. I am very new at this so any help is appreciated.
This is my php file:
<? ob_start(); ?>
<?php
define('FACEBOOK_APP_ID', '');
define('FACEBOOK_SECRET', '');
// No need to change function body
function parse_signed_request($signed_request, $secret) {
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
// decode the data
$sig = base64_url_decode($encoded_sig);
$data = json_decode(base64_url_decode($payload), true);
if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
error_log('Unknown algorithm. Expected HMAC-SHA256');
return null;
}
// check sig
$expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
if ($sig !== $expected_sig) {
error_log('Bad Signed JSON signature!');
return null;
}
return $data;
}
function base64_url_decode($input) {
return base64_decode(strtr($input, '-_', '+/'));
}
if ($_REQUEST) {
$response = parse_signed_request($_REQUEST['signed_request'],
FACEBOOK_SECRET);
/*
echo "<pre>";
print_r($response);
echo "</pre>"; // Uncomment this for printing the response Array
*/
$name = $response["registration"]["name"];
$email = $response["registration"]["email"];
$gender = $response["registration"]["gender"];
$prosecutor = $response["registration"]["prosecutor"];
$location = $response["registration"]["location"];
// Connecting to Database
$con = mysql_connect("my_hosting_site","Database","password");
if (!$response)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("Database", $con);
mysql_query("INSERT INTO my_table (name, email, gender, prosecutor, location)
VALUES ('$name', '$email', '$gender', '$prosecutor', '$location')");
mysql_close($con);
}
$URL="https://www.facebook.com";
header ("Location: $URL");
?>
<? ob_flush(); ?>
Facebook
Basically, it's an array.
[location] => Array
(
[name] => Delhi, India
[id] => 1.1604xxxxxx286E+14
)
Use this for getting location stored in your db, like I have written below:
$location = $response["registration"]["location"]["name"];