How to connect multiple database in phalcon framework - phalcon

i have to database namely master and xyz ,in that i required to connect both database in application .
so is it possible to connect multiple database in one application and yes then how.?

Set your connections in DI:
//This service returns a MySQL database
$di->set('dbMaster', function() {
return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
"host" => "localhost",
"username" => "",
"password" => "",
"dbname" => ""
));
});
//This service returns a PostgreSQL database
$di->set('dbSlave', function() {
return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
"host" => "localhost",
"username" => "",
"password" => "",
"dbname" => ""
));
});
In your models choose the connection:
public function initialize()
{
$this->setConnectionService('dbMaster');
//or
$this->setConnectionService('dbSlave');
}

Another way to do this, using the same configuration
//This service returns a MySQL database
$di->set('dbMaster', function() {
return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
"host" => "localhost",
"username" => "",
"password" => "",
"dbname" => ""
));
});
//This service returns a PostgreSQL database
$di->set('dbSlave', function() {
return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
"host" => "localhost",
"username" => "",
"password" => "",
"dbname" => ""
));
});
In your model set
public function initialize()
{
$this->setReadConnectionService('dbSlave');
$this->setWriteConnectionService('dbMaster');
$this->setSource('table_name');
}
If you use transaction, remember in the injector dependency to change
$di->set('dbMaster' ....
For
$di->setShared('dbMaster'....
And the rest is the same

Related

Jazzcash Payment Integration V2.0

I'm working on Rest based api version 2.0. It constantly giving me error
Please provide a valid value for pp_SecureHash
It is working fine in case of "Page redirection" so hash key generation method is correct and issue is with parameters (maybe some missing/extra/wrong data). what I'm doing wrong?
{ “uri”: “https://sandbox.jazzcash.com.pk/ApplicationAPI/API/2.0/Purchase/DoMWalletTransaction”, “method”: “POST”, “body”: “pp_Amount=1100&pp_BillReference=billRef&pp_CNIC=345678&pp_Description=jazzcash&pp_Language=EN&pp_MerchantID=xyz&pp_MobileNumber=03123456789&pp_Password=xyz&pp_ReturnURL=https://sandbox.jazzcash.com.pk/ApplicationAPI/API/2.0/Purchase/DoMWalletTransaction&pp_SecureHash=BC3BABD0481A2FA756F2E16CE15FC6F8029D40E23B974065668CCEAC300B80AE&pp_TxnCurrency=PKR&pp_TxnDateTime=20220406132730&pp_TxnExpiryDateTime=20220406142730&pp_TxnRefNo=T20220406142730&ppmpf_1=1&ppmpf_2=2&ppmpf_3=3&ppmpf_4=4&ppmpf_5=5” }
Your pp_SecureHash value needs to be HmacSHA256 encoded.
var sHash = HMACSHA256Encode(hash, jazz.salt);
You can refer this code sample to achieve your requirement.
C#: Generate pp_SecureHash ()
Please check your merchant Id, password and salt key. It's also through the error if your any of info is wrong.
Read the doc carefully. if add version 1.2 and in the doc it's mention 1.1 it's not going to work and through the same error. provide valid secure
If you are sure that other info is correct so you can generate secure ssh by using below method
$post_data = array(
"pp_Version" => Config::get('constants.jazzcash.VERSION'),
"pp_TxnType" => "MWALLET",
"pp_Language" => Config::get('constants.jazzcash.LANGUAGE'),
"pp_MerchantID" => Config::get('constants.jazzcash.MERCHANT_ID'),
"pp_SubMerchantID" => "",
"pp_Password" => Config::get('constants.jazzcash.PASSWORD'),
"pp_BankID" => "TBANK",
"pp_ProductID" => "RETL",
"pp_TxnRefNo" => $pp_TxnRefNo,
"pp_Amount" => $pp_Amount,
"pp_TxnCurrency" => Config::get('constants.jazzcash.CURRENCY_CODE'),
"pp_TxnDateTime" => $pp_TxnDateTime,
"pp_BillReference" => "billRef",
"pp_Description" => "Description of transaction",
"pp_TxnExpiryDateTime" => $pp_TxnExpiryDateTime,
"pp_ReturnURL" => Config::get('constants.jazzcash.RETURN_URL'),
"pp_SecureHash" => "",
"ppmpf_1" => "1",
"ppmpf_2" => "2",
"ppmpf_3" => "3",
"ppmpf_4" => "4",
"ppmpf_5" => "5",
);
private function get_SecureHash($data_array)
{
ksort($data_array);
$str = '';
foreach($data_array as $key => $value){
if(!empty($value)){
$str = $str . '&' . $value;
}
}
$str = Config::get('constants.jazzcash.INTEGERITY_SALT').$str;
$pp_SecureHash = hash_hmac('sha256', $str, Config::get('constants.jazzcash.INTEGERITY_SALT'));
//echo '<pre>';
//print_r($data_array);
//echo '</pre>';
return $pp_SecureHash;
}
And Last by calling this method you can get the secure key
$pp_SecureHash = $this->get_SecureHash($post_data);

cakephp 3.8.13 add admad/cakephp-jwt-auth

This question is asked many times in the stack overflow but I tried every accepted solution.
I'm new to cake PHP and I was assigned to add JWT in our application. Previously the team used the default cake sessions. In order to integrate, I used admad/cakephp-jwt-auth. So In the AppController
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Recurring');
$this->loadComponent('Auth', [
'storage' => 'Memory',
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'user_name',
'password' => 'password',
],
'contain' => ['Roles']
],
'ADmad/JwtAuth.Jwt' => [
'parameter' => 'token',
'userModel' => 'CbEmployees',
'fields' => [
'username' => 'id'
],
'queryDatasource' => true
]
],
'unauthorizedRedirect' => false,
'checkAuthIn' => 'Controller.initialize'
]);
}
I have to use CbEmployees which is our user model.
Then in my custom controller, I add my login function
public function login()
{
$user = $this->Auth->identify();
if (!$user) {
$data = "Invalid login details";
} else {
$tokenId = base64_encode(32);
$issuedAt = time();
$key = Security::salt();
$data = JWT::encode(
[
'alg' => 'HS256',
'id' => $user['id'],
'sub' => $user['id'],
'iat' => time(),
'exp' => time() + 86400,
],
$key
);
}
$this->ApiResponse([
"data" => $data
]);
}
Then I call this function using postman with body
{
"username": "developer",
"password": "dev2020"
}
I always get the response as Invalid login details. So the suggested solution is to check the password data type and length. The password is varchar(255). Another solution is to check the password in the entity. In the entity I have
protected function _setPassword($password)
{
if (strlen($password) > 0) {
return Security::hash($password, 'sha1', true);
// return (new DefaultPasswordHasher)->hash($password);
}
}
I specifically asked why the team is using Security::hash($password, 'sha1', true); due to migration from cake 2 to cake 3 they have to use the same.
Why I'm getting always Invalid login details? What I'm doing wrong here? I can log in the using the same credentials when I'm using the application.

only strings in influxdb

i've this config file in logstash
input {
redis{
host => "localhost"
data_type => "list"
key => "vortex"
threads => 4
type => "testrecord"
codec => "plain"
}
}
filter {
kv {
add_field => {
"test1" => "yellow"
"test" => "ife"
"feild" => "pink"
}
}
}
output {
stdout { codec => rubydebug }
influxdb {
db => "toast"
host => "localhost"
measurement => "myseries"
allow_time_override => true
use_event_fields_for_data_points => true
exclude_fields => ["#version", "#timestamp", "sequence", "message", "type", "host"]
send_as_tags => ["bar", "feild", "test1", "test"]
}
}
and a list in redis with the following data:
foo=10207 bar=1 sensor2=1 sensor3=33.3 time=1489686662
everything works fine but every field in influx is defined as string regardless of values.
does anybody know how to get around this issue?
The mutate filter may be what you're looking for here.
filter {
mutate {
convert => {
"value" => "integer"
"average" => "float"
}
}
}
It means you need to know what your fields are before-hand, but it will convert them into the right data-type.

How to give db connection in db beginTransaction

$transaction = Yii::app()->db->beginTransaction();
try {
$transaction=$connection->beginTransaction();
$model = new UserRole();
$model->role_name="new";
$model->save();
$transaction->commit();
Yii::log('Done', 'trace', 'stripe');
}
catch (Exception $e) {
$transaction->rollback();
}
Why data's are insert in db after that begintransaction in yii,What is $connection?i dont exactly what is meaning of $connection.
In My config.php My Db connection like below.
'db' => require(dirname(__FILE__) . '/database.php'),
$connection = array(
'connectionString' => "mysql:host=localhost;dbname=xxx",
'username' => "root",
'password' => "",
'charset' => 'utf8',
'emulatePrepare' => true,
'tablePrefix' => 'tbl_',
);
My databse connection in another file database.php
I got error like,
Call to a member function beginTransaction() on a non-object.
Why data's are not insert after that beginTransaction?
1. set correct db connection params in your config file:
'db' => array(
'connectionString' => "mysql:host=localhost;dbname=xxx",
'username' => "root",
'password' => "",
'charset' => 'utf8',
'emulatePrepare' => true,
'tablePrefix' => 'tbl_',
)
or write connection data in database.php and include it in main config:
in database.php
return array(
'connectionString' => "mysql:host=localhost;dbname=xxx",
'username' => "root",
'password' => "",
'charset' => 'utf8',
'emulatePrepare' => true,
'tablePrefix' => 'tbl_',
);
in main.php (or other config file)
'db' => require(dirname(__FILE__) . '/database.php'),
2. define $connection varaible before using:
$connection = Yii::app()->db;
try {
$transaction = $connection->beginTransaction();
$model = new UserRole();
$model->role_name = "new";
$model->save();
$transaction->commit();
Yii::log('Done', 'trace', 'stripe');
} catch (Exception $e) {
if (isset($transaction)) {
$transaction->rollback();
}
Yii::log('Error', 'trace', 'stripe');
}

How to make the database connection to be utf-8 compliant in this setting?

This is my index.php file ( the database is MySQL ) :
<?php
use Phalcon\Loader;
use Phalcon\DI\FactoryDefault;
use Phalcon\Mvc\View;
use Phalcon\Mvc\Application;
use Phalcon\Mvc\Url as UrlProvider;
use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;
include("../app/config_const.php");
include("../app/config_inc.php");
include("../app/lib/PSR.php");
try {
// Register an autoloader
$loader = new Loader();
$loader->registerDirs(array(
'../app/controllers/',
'../app/models/'
))->register();
// Create a DI
$di = new FactoryDefault();
// Setup the database service
$di->set('db', function(){
$cnx = new DbAdapter(array(
"host" => "localhost",
"username" => "root",
"password" => "",
"dbname" => BDD
));
return $cnx;
});
// Setup the view component
$di->set('view', function(){
$view = new View();
$view->setViewsDir('../app/views/');
$view->registerEngines(array(
".phtml" => 'Phalcon\Mvc\View\Engine\Volt'
));
return $view;
});
// Setup a base URI so that all generated URIs include the "phalcon" folder
$di->set('url', function(){
$url = new UrlProvider();
$url->setBaseUri('/resto/');
return $url;
});
//Register the flash service with custom CSS classes
$di->set('flash', function(){
$flash = new \Phalcon\Flash\Direct(array(
'error' => 'alert alert-error',
'success' => 'alert alert-success',
'notice' => 'alert alert-info',
));
return $flash;
});
//Handle the request
$app = new Application($di);
echo $app->handle()->getContent();
} catch(\Exception $e) {
echo "Exception: ", $e->getMessage();
}
?>
How to make the database setting to be utf-8 compliant in this case ?
Add encoding parameter to DB adapter as well:
// Setup the database service
$di->set('db', function(){
$cnx = new DbAdapter(array(
"host" => "localhost",
"username" => "root",
"password" => "",
"dbname" => BDD,
"charset" => "utf8",
"options" => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'
),
));
return $cnx;
});
Reference.
Also you can set encoding to your .htaccess file:
# your file could start with something like this
RewriteEngine On
RewriteBase /
# add next line
AddDefaultCharset utf-8
Ok I found the solution : I modified the ssp.class.php for the server processing :
static function sql_connect($sql_details) {
try {
$db = #new PDO("mysql:host={$sql_details['host']};dbname={$sql_details['db']}",
$sql_details['user'],$sql_details['pass'],array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\'',
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$db->exec("set names utf8");
$db->exec("set character_set_client='utf8'");
$db->exec("set character_set_results='utf8'");
$db->exec("set collation_connection='utf8_bin'");
}
catch (PDOException $e) {
self::fatal("An error occurred while connecting to the database. ".
"The error reported by the server was: ".$e->getMessage());
}
return $db;
}