Правильно добавить API Key при подключении к внешнему ресурсу.

PK
На сайте с 22.05.2009
Offline
89
258

Столкнулся с ситуацией, когда нужно к коду добавить отправку API Key при подключении к внешнему ресурсу.

Рекомендация внешнего ресурса такая:

1 вариант - Via a custom header named API-KEY-1

2 вариант - Via a query string parameter named API-KEY-3

Подключение к https://api.adm.com/v1/

Мой код:

<?php


namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\Response;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\ContactForm;
use app\models\Cry2;
use app\models\Cry3;
use app\models\UserSmsModel;
use app\models\UserSmsSearchModel;
use yii\web\NotFoundHttpException;

class C2Controller extends Controller
{
public function behaviors()
{
return [ 'access' => [ 'class' => AccessControl::className(),
'only' => ['index', 'update', 'delete', 'history', 'delete-message'],
'rules' => [ [ 'allow' => true,
'actions' => ['index', 'update', 'delete', 'history', 'delete-message'],
'roles' => ['@'],
],
],
]
];
}

public function actions()
{
return [ 'error' => [ 'class' => 'yii\web\ErrorAction',
],
'captcha' => [ 'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}

public function actionIndex()
{
$Cry2 = new Cry2();

if ($Cry2->load(Yii::$app->request->post()) && $Cry2->validate()) {
$json_string = Yii::$app->params['urlApi9'] . $Cry2->name . '/?convert=USD';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata, true);

if (isset($obj[0]['price_usd'])) {
$Cry2->price = $obj[0]['price_usd'];
$Cry2->time_start = date('Y-m-d H:i:s', time());
$Cry2->save();
}
else {
$message = 'Неверный запрос к валюте ' . $Cry2->name;
Yii::$app->session->setFlash('message', '<strong>' . $message . '</strong>');
}
return $this->redirect(['index']);
}

$searchModel = new Cry3();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);

$currencies = self::getNewCurrenciesNames(Yii::$app->params['urlApi9']);

return $this->render('index', [ 'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'Cry2' => $Cry2,
'currencies' => $currencies,
]);
}

public function actionUpdate($id)
{
$Cry2 = $this->findModel(Cry2::className(), $id);

if ($Cry2->load(Yii::$app->request->post()) && $Cry2->save()) {
return $this->redirect(['index']);
}

$currencies = self::getNewCurrenciesNames(Yii::$app->params['urlApi9'], $Cry2->name);

return $this->render('update', [ 'Cry2' => $Cry2,
'currencies' => $currencies,
]);
}

public function actionDelete($id)
{
$Cry2 = $this->findModel(Cry2::className(), $id);
$Cry2->delete();

return $this->redirect(['index']);
}

public function actionHistory()
{
$searchModel = new UserSmsSearchModel();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);

return $this->render('history', [ 'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}

public function actionDeleteMessage($id)
{
$UserSmsModel = $this->findModel(UserSmsModel::className(), $id);
$userSmsModel->delete();

return $this->redirect(['history']);
}

protected function findModel($className, $id)
{
if (($model = $className::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested model does not exist.');
}
}

private function getNewCurrenciesNames($path, $name = null) {
$jsondata = file_get_contents($path);
$obj = json_decode($jsondata, true);

$allCurrencies = [];
foreach ($obj as $currency) {
$allCurrencies[$currency['name']] = $currency['id'];
}

$cr9Names =[];
$Cry2s = Cry2::find()->all();
foreach ($Cry2s as $Cry2) {
$cr9Names[] = $Cry2->name;
}

if ($name) {
$key = array_search($name, $cr9Names);
if (false !== $key) unset($cr9Names[$key]);
}

$currencies = array_diff($allCurrencies, $cr9Names);
$currencies = array_flip($currencies);
asort($currencies);

return $currencies;
}
}

urlApi9 такой:

<?php


return [ 'adminEmail' => 'adm@adm.net',
'urlApi9' => 'https://api.adm.com/v1/',
'urlWm' => 'https://api2.adm.ru/',
];

Как понимаю, нужно в верхний код, как-то встроить подобное:

$ApiKey='API-KEY';

$C1Url='https://api.adm.com/v1/';
$APIREST = new APIREST($C1Url);
$C2Coins= $APIREST->call(
array('API-KEY-1:'.$ApiKey)
);

но в этом не силен:(

Gerga
На сайте с 02.08.2015
Offline
94
#1
phoenix_kys:
Как понимаю, нужно в верхний код, как-то встроить подобное:

Нет, нужно в конфигурационном файле поставить API-KEY. Попробуйте в urlApi9 сделать так:


<?php

return [ 'adminEmail' => 'adm@adm.net',
'urlApi9' => 'https://api.adm.com/v1/',
'API-KEY-1' => 'ваш API-KEY',
];

Если где-то реализован вызов и отправка этого ключа, значит это сработает.

Авторизуйтесь или зарегистрируйтесь, чтобы оставить комментарий