how to call method magento api - php

im working with magento api, and i need verify my connect.
how to call method APIauthentication with $client object? because im getting error on this: Error: Function ("APIauthentication") is not a valid method for this service
thanks for the help.
this is my class:
<?php
class Magento {
const PRODUCTS_LIST = 'catalog_product.list';
public function Verify( $data )
{
$client = new SoapClient( $data['store_url'] );
$verify = $client->APIauthentication( $data['api_user'], $data['api_key'] );
if ($verify)
{
return $this->Register( $data['store_url'], $data['api_user'], $data['api_key'] );
}
}
public function APIauthentication( $apiUser, $apiKey ) {
$client = $this->_getClient();
$token = $client->login( $apiUser, $apiKey );
$this->_setToken( $token );
return $this->_apiJsonResult( $token );
}
}
there is url:
$data['store_url'] = 'http://localhost:8888/magento/api/soap/?wsdl';
firstly i need verify, second - get list:
// For products
public function getProducts()
{
return $client->APIgetProductsList();
}
/*
* Get product list
*/
public function APIgetProductsList() {
$token = $this->_getToken();
$client = $this->_getClient();
$products = $client->call($token, self::PRODUCTS_LIST );
return $this->_apiJsonResult( $products );
}

You need to create your own api by creating new module then you can use that api method refer this link http://www.magentocommerce.com/wiki/5_-_modules_and_development/web_services/custom_api_complete_example

Related

How to adapt my code to meet PSR standards: PSR-7, PSR-15

I am brand new to PSR standards, and I am not sure if I adapted my code to PSR-7, PSR-15 correctly.
My code is handling a POST request to delete a group of products by receiving an array of ids.
Is that a correct adaptation? Thanks.
<?php
require_once 'DataBase.php';
require_once 'config.php';
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
class DeleteRequest implements RequestHandlerInterface
{
private $DB;
public function __construct(DataBase $DB)
{
$this->DB = $DB;
}
//Delete each product from the database using the ID
public function handle(ServerRequestInterface $request): ResponseInterface
{
// Make sure it is a POST request
if ($request->getMethod() !== 'POST') {
throw new Exception('Incorrect REQUEST_METHOD. '.
'Only POST requests are allowed.');
}
// Extract the 'ids' array from the request data
MyLogV($request->getBody()->getContents());
$data = json_decode($request->getBody()->getContents(), true);
// Make sure the 'ids' array is present in the data
if (!isset($data['ids'])) {
throw new Exception('Missing required parameter: ids');
}
$ids = $data['ids'];
foreach ($ids as $id) {
myLog("DeleteRequest->handle","id",$id);
$result = $this->DB->deleteProduct($id);
if ($result['status'] != 'success') break;
}
// Generate the response: 200 => OK, 400 => Bad request
$status = $result['status'] == 'success' ? 200 : 400;
$response = new JsonResponse($result, $status);
myLogV($result['status']);
return $response;
}
}
try {
$serverRequest = ServerRequestFactory::fromGlobals();
$DB = new DataBase();
$deleteRequest = new DeleteRequest($DB);
$response = $deleteRequest->handle($serverRequest);
$response->send();
} catch (Exception $e) {
myLog("delete.php","Exception",$e->getMessage());
$result = ['status' => 'error','message'=> $e->getMessage()];
$response = new JsonResponse($result, 400);
$response->send();
}
exit();
?>
I tried to understand the PSR standards.

How save access_token to db using yii2-dektrium facebook login?

I'm using yii2-dektrium to allow users login with their facebook's accounts.
After the login is done, I need to make API request from my server to get data of the user's accounts. One example of request is:
$client = Yii::$app->authClientCollection->getClient('facebook');
$response = $client->createApiRequest()
->setMethod('GET')
->setUrl('v2.12/me/accounts')
->send();
The access_token is saved on session so I need to persist it to the database.
I already added a column access_token to the social_account default table of yii2-dektrium but I don't know how to get and save it, and further more, how to apply it to the requests.
After reading for a while. I think the way to save it is overriding the method connect in dektrium\user\controllers\SecurityController.
public function connect(ClientInterface $client)
{
/** #var Account $account */
$account = \Yii::createObject(Account::className());
$event = $this->getAuthEvent($account, $client);
$this->trigger(self::EVENT_BEFORE_CONNECT, $event);
$account->connectWithUser($client);
$this->trigger(self::EVENT_AFTER_CONNECT, $event);
$this->action->successUrl = Url::to(['/user/settings/networks']);
}
And for applying to the request, override applyAccessTokenToRequest on yii\authclient\clients\Facebook
public function applyAccessTokenToRequest($request, $accessToken)
{
parent::applyAccessTokenToRequest($request, $accessToken);
$data = $request->getData();
if (($machineId = $accessToken->getParam('machine_id')) !== null) {
$data['machine_id'] = $machineId;
}
$data['appsecret_proof'] = hash_hmac('sha256', $accessToken->getToken(), $this->clientSecret);
$request->setData($data);
}
I can't get it done. And I'm not sure if it is the right way to do it. What I'm missing?
For save the access_token the first time you have to overwrite the connect action from \dektrium\user\controllers\SecurityController.
class SecurityController extends \dektrium\user\controllers\SecurityController
{
public function connect(ClientInterface $client)
{
// default implementation of connect
$account = \Yii::createObject(Account::className());
$event = $this->getAuthEvent($account, $client);
$this->trigger(self::EVENT_BEFORE_CONNECT, $event);
$account->connectWithUser($client);
$this->trigger(self::EVENT_AFTER_CONNECT, $event);
// get acess_token from $client
$access_token['tokenParamKey'] = $client->getAccessToken()->tokenParamKey;
$access_token['tokenSecretParamKey'] = $client->getAccessToken()->tokenSecretParamKey;
$access_token['createTimestamp'] = $client->getAccessToken()->createTimestamp;
$access_token['_expireDurationParamKey'] = $client->getAccessToken()->getExpireDurationParamKey();
$access_token['_params'] = $client->getAccessToken()->getParams();
// save acess_token to social_account table
$model = SocialAccount::find()->where(['provider' => $client->getName()])->andWhere(['user_id' => Yii::$app->user->id])->one();
$model->access_token = \yii\helpers\Json::encode($access_token);
$model->save(false);
$this->action->successUrl = Url::to(['/user/settings/networks']);
}
}
To get the access_token store in the database for further API Requests create a class that extends yii\authclient\SessionStateStorage and overwrite get method.
namespace app\models\authclient;
class DbStateStorage extends SessionStateStorage
{
public function get($key)
{
// $key is a complex string that ends with 'token' if the value to get is the actual access_token
$part = explode('_', $key);
if (count($part) == 3 && $part[2] == 'token') {
$account = SocialAccount::find()
->where(['provider' => $part[1]])
->andWhere(['user_id' => Yii::$app->user->id])
->one();
if ($account != null) {
$access_token = json_decode($account->access_token);
$token = new \yii\authclient\OAuthToken();
$token->createTimestamp = $access_token->createTimestamp;
$token->tokenParamKey = $access_token->tokenParamKey;
$token->tokenSecretParamKey = $access_token->tokenSecretParamKey;
$token->setParams((array)$access_token->_params);
$token->setExpireDurationParamKey($access_token->_expireDurationParamKey);
return $token;
}
}
if ($this->session !== null) {
return $this->session->get($key);
}
return null;
}
}
Finally set the DbStateStorage to your authclient
class Facebook extends \dektrium\user\clients\Facebook
{
public function __construct()
{
$this->setStateStorage('app\models\authclient\DbStateStorage');
}
}

codeigniter flipkart product api

I am trying to get the top deals using the flipkart product feed api in codeigniter.
This is the piece of code that I have written to achieve it.
public function getTopDealsFlipkart()
{
$data = array();
$data['url'] = 'https://affiliate-api.flipkart.net/affiliate/1.0/feeds/'.FK_AFFILIATE_ID.'/category/mens-clothing.json?expiresAt=1510123592000&sig=<urlValidationSignature>&inStock=true';
$header['Accept'] = 'application/json';
$header['Fk-Affiliate-Token'] = FK_AFFILIATE_TOKEN;
$header['Fk-Affiliate-Id'] = FK_AFFILIATE_ID;
$data['header'] = $header;
$output = $this->get_response($data);
return $output;
}
public function get_response($data)
{
$output = null;
try {
$client = new GuzzleHttp\Client();
$response = $client->request('GET', $data['url'], [
'headers' => $data['header']
]);
$output = $response->getBody();
} catch (Exception $e) {
log_message('debug', 'fail to get response ');
}
return $output;
}
The output that it is returning is null.
I am not able to understand what is 'sig' as the API just defines it as "url validation signature". There is no information further information on the API. What is the URL validation signature and How do I generate the URL validation signature?

Slim post method redirect does not Work with slim Middleware

Hey guys i got some Problems with the Slim Middleware.
I created a Middleware that checks if the user is logged with Facebook and has a specific Email address. So now when i call the url with the PHPStorm RESTful Test tool i should not be able to post data to the server...
But the Redirect does not work so i will be able to send data to the server.
/**
* Admin Middleware
*
* Executed before /admin/ route
*/
$adminPageMiddleware = function ($request, $response, $next) {
FBLoginCtrl::getInstance();
$user = isset($_SESSION['user']) ? $_SESSION['user'] : new User();
if (!($user->getEmail() == ADMIN_USER_EMAIL)) {
$response = $response->withRedirect($this->router->pathFor('login'), 403);
}
$response = $next($request, $response);
return $response;
};
/**
* Milestone POST Method
*
* Create new Milestone
*/
$app->post('/admin/milestone', function (Request $request, Response $response) use ($app) {
$milestones = $request->getParsedBody();
$milestones = isset($milestones[0]) ? $milestones : array($milestones);
foreach ($milestones as $milestone) {
$ms = new Milestone();
$msRepo = new MilestoneRepository($ms);
$msRepo->setJsonData($milestone);
if (!$msRepo->createMilestone()) {
return $response->getBody()->write("Not Okay");
};
}
return $response->getBody()->write("Okay");
})->add($adminPageMiddleware);
So can anyone give me a hint what the problem could be?
I tried to add the same middleware to the get Route ... there it works :/ Strange stuff.
The problem is in your middleware logic.
if (!($user->getEmail() == ADMIN_USER_EMAIL)) {
return $response->withRedirect($this->router->pathFor('login'), 403); //We do not want to continue execution
}
$response = $next($request, $response);
return $response;
So now i ended up with this code:
class AdminRouteMiddleware
{
public function __invoke($request, $response, $next)
{
FBLoginCtrl::getInstance();
$user = isset($_SESSION['user']) ? $_SESSION['user'] : new User();
if (!($user->getEmail() == ADMIN_USER_EMAIL)) {
if ($_SERVER['REQUEST_METHOD'] == "GET") {
$response = $response->withRedirect('/login', 403);//want to use the route name instead of the url
} else {
$response->getBody()->write('{"error":Access Denied"}');
}
} else {
$response = $next($request, $response);
}
return $response;
}
}
/**
* Milestone POST Method
*
* Create new Milestone
*/
$app->post('/admin/milestone', function (Request $request, Response $response) use ($app) {
$milestones = $request->getParsedBody();
$milestones = isset($milestones[0]) ? $milestones : array($milestones);
foreach ($milestones as $milestone) {
$ms = new Milestone();
$msRepo = new MilestoneRepository($ms);
$msRepo->setJsonData($milestone);
if (!$msRepo->createMilestone()) {
return $response->getBody()->write("Not Okay");
};
}
return $response->getBody()->write("Okay");
})->add(new AdminRouteMiddleware());

soap response in array

I am trying to get a soap response in php. It keeps coming as an object onto my web browser but not as xml. WSDL shows as XML but not the response received. Below is my server side code. The soap server is Zend Soap
ini_set("soap.wsdl_cache_enabled", 0);
if (isset($_GET['wsdl'])){
$wsdl = 'http://localhost/webservice/soap';
$autoDiscover = new AutoDiscover();
$autoDiscover->setOperationBodyStyle(
array('use' => 'literal',
'namespace' => 'http://localhost/webservice/soap')
);
$autoDiscover->setBindingStyle(
array('style' => 'rpc',
'transport' => 'http://schemas.xmlsoap.org/soap/http')
);
$autoDiscover->setComplexTypeStrategy(new ArrayOfTypeComplex());
// $service is the class that does the handling of functions
$autoDiscover->setClass($service);
$autoDiscover->setUri($wsdl);
$response->getHeaders()->addHeaderLine('Content-Type', 'text/xml');
$response->setContent($autoDiscover->toXml());
} else {
$server = new Server('http://localhost/webservice/soap?wsdl'
);
// $service is the class that does the handling of functions
$server->setObject($service);
$response->setContent($server->handle());
}
return $response;
}
Service class
class service
{
/**
*
* #param string $Email
* #return int $Credit
*/
public function checkCredits($Email)
{
$validator = new email();
if (!$validator->isValid($Email))
{
return new \SoapFault('5', 'Please Provide an Email');
}
$rowset = $this->tableGateway->select(array('EMAIL'=>$Email))
$row = $rowset->current();
$credits = $row->CREDITS;
return $credits;
}
}
Request is :
try{
$sClient = new SoapClient('http://localhost/webservice/soap?wsdl');
$params = "email";
$response = $sClient->checkCredits($params);
var_dump($response);
} catch(SoapFault $e){
var_dump($e);
}
This is an example of how I handle my functions with SoapClient:
$client = new SoapClient('http://url/Service.svc?wsdl');
$var = array('arg' => 10,
'VA' => 48);
$varresponse = $client->Function($var);
print_r( $varresponse->FunctionResult);
Hope this will help you out.
Your soapserver should look a bit like this:
<?php
if(!extension_loaded("soap")){
dl("php_soap.dll");
}
ini_set("soap.wsdl_cache_enabled","0");
$server = new SoapServer("hello.wsdl");
function doHello($yourName){
return "Hello, ".$yourName;
}
$server->AddFunction("doHello");
$server->handle();
?>
How did you set up yours? Do you return anything?
Now, your client should look like this:
<?php
try{
$sClient = new SoapClient('http://localhost/test/wsdl/hello.xml');
$params = "Name";
$response = $sClient->doHello($params);
var_dump($response);
} catch(SoapFault $e){
var_dump($e);
}
?>

Categories