I'm trying to fix the pipeline and
I get the following 2 warning
$secretKeyString = new \java("java.lang.String", $secretKey);
$pbbEncryptAES = new \java("my.com.onlinepayment.encoders.PBE_encrypt_AES");:
Missing class import via use statement (line '124', column '30').
for the following code:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Response;
use java;
class AlbPaymexController extends Controller
{
protected $responses = [
'B2C91BC3' => "",
'PX_VERSION' => "",
'PX_TRANSACTION_TYPE' => "",
];
private function generateSignature( array $payload, string $secretKey, &$calculated = null )
{
if(array_key_exists("PX_SIG", $payload))
unset($payload['PX_SIG']);
$plaintext = implode("\n" , $payload)."\n";
$calculated["payload"] = $payload;
$calculated["plain"] = $plaintext;
$calculated["secret"] = $secretKey;
$secretKeyString = new \java("java.lang.String", $secretKey);
$pbbEncryptAES = new \java("my.com.onlinepayment.encoders.PBE_encrypt_AES");
try{
$result = $pbbEncryptAES->encrypt(
$secretKeyString->getBytes(),
$plaintext,
"AES"
);
return $calculated["signature"] = java_values($result);
} catch( \java_InternalException $ex ) {
throw new Exception("Failed to generate signature");
}
}
}
I got this error while running my pipeline in GitLab. I'm very new to GitLab and not sure how to fix this issue. It will be very helpful if anyone know how to fix it. Hoping to get fix before the submisson date
Related
I have encoded a token with JWT::encode($payload, $key, 'HS256');
When I am trying to decode it with the same key, it throws an error.
Here is the code:
<?php
namespace App\Filters;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use \Firebase\JWT\JWT;
use Config\Services;
use Config\MyConfig;
class AuthFilter implements FilterInterface
{
public function before(RequestInterface $request, $arguments = null)
{
$myconfig = new MyConfig;
$key = $myconfig->JWT_SECRET_KEY;
$header = $request->getServer('HTTP_AUTHORIZATION');
if(!$header) return Services::response()
->setJSON(['msg' => 'Token Required'])
->setStatusCode(ResponseInterface::HTTP_UNAUTHORIZED);
$token = explode(' ', $header)[1];
try {
JWT::decode($token, $key, ['HS256']); // it throws error: jwt decode throws
// Invalid argument supplied for foreach()
} catch (\Throwable $th) {
return Services::response()
->setJSON(['msg' => $th->getMessage()])
->setStatusCode(ResponseInterface::HTTP_UNAUTHORIZED);
}
}
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
//
}
}
So this happens every time when I try to decode, but works fine when I encode it.
After spending hours, I went through official documentation (https://github.com/firebase/php-jwt#readme), seems I had to use
JWT::decode($token, new Key($key, 'HS256')); instead of JWT::decode($token, $key, ['HS256']);
It works for me like this:
use Firebase\JWT\Key; // add the library
JWT::decode($token, new Key($key, 'HS256'));
index.php
require "vendor/autoload.php";
require "routes.php";
routes.php
<?php
require "vendor/autoload.php";
use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Generator\UrlGenerator;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
try {
$form_add_route = new Route(
'/blog/add',
array(
'controller' => '\HAPBlog\Controller\EntityAddController',
'method'=>'load'
)
);
$routes = new RouteCollection();
$routes->add('blog_add', $form_add_route);
// Init RequestContext object
$context = new RequestContext();
$context->fromRequest(Request::createFromGlobals());
$matcher = new UrlMatcher($routes, $context);
$parameters = $matcher->match($context->getPathInfo());
// How to generate a SEO URL
$generator = new UrlGenerator($routes, $context);
$url = $generator->generate('blog_add');
echo $url;
}
catch (Exception $e) {
echo '<pre>';
print_r($e->getMessage());
}
src/Controller/EntityAddController.php
<?php
namespace HAPBlog\Controller;
use Symfony\Component\HttpFoundation\Response;
class EntityAddController {
public function load() {
return new Response('ENTERS');
}
}
I am referring to the tutorial given below:
https://code.tutsplus.com/tutorials/set-up-routing-in-php-applications-using-the-symfony-routing-component--cms-31231
But when I try to access the site http://example.com/routes.php/blog/add
It gives a blank page.
Debugging via PHPStorm shows that it does not enter "EntityAddController" Class
What is incorrect in the above code ?
There is no magic behind this process, once you get the route information, you will have to call the configured controller and send the response content.
Take a complete example here:
// controllers.php
class BlogController
{
public static function add(Request $request)
{
return new Response('Add page!');
}
}
// routes.php
$routes = new RouteCollection();
$routes->add('blog_add', new Route('/blog/add', [
'controller' => 'BlogController::add',
]));
// index.php
$request = Request::createFromGlobals();
$context = new RequestContext();
$context->fromRequest($request);
$matcher = new UrlMatcher($routes, $context);
try {
$attributes = $matcher->match($request->getPathInfo());
$response = $attributes['controller']($request);
} catch (ResourceNotFoundException $exception) {
$response = new Response('Not Found', 404);
} catch (Exception $exception) {
$response = new Response('An error occurred', 500);
}
$response->send();
I am trying to run the example code here
But I am getting this error:
Payum\Core\Exception\InvalidArgumentException: A token with hash `RVpxpP1m3HnTWcj2oL19SQ38NWvCDIz5qeUwfr283kY` could not be found. in /var/www/test/vendor/payum/core/Payum/Core/Security/PlainHttpRequestVerifier.php on line 47
My code looks like this:
namespace Paypal\Model;
use Payum\Core\Model\ArrayObject;
class AgreementDetails extends ArrayObject {
}
namespace Paypal\Model;
use Payum\Core\Model\Token;
class PaymentSecurityToken extends Token
{
}
namespace Paypal\Model;
use Payum\Core\Model\ArrayObject;
class RecurringPaymentDetails extends ArrayObject{
}
config.php
use Buzz\Client\Curl;
use Payum\Paypal\ExpressCheckout\Nvp\PaymentFactory;
use Payum\Paypal\ExpressCheckout\Nvp\Api;
use Payum\Core\Registry\SimpleRegistry;
use Payum\Core\Storage\FilesystemStorage;
use Payum\Core\Security\PlainHttpRequestVerifier;
use Payum\Core\Security\GenericTokenFactory;
$tokenStorage = new FilesystemStorage('/home/vagrant/tmp', 'Paypal\Model\PaymentSecurityToken');
$requestVerifier = new PlainHttpRequestVerifier($tokenStorage);
$agreementDetailsClass = 'Paypal\Model\AgreementDetails';
$recurringPaymentDetailsClass = 'Paypal\Model\RecurringPaymentDetails';
$storages = array(
'paypal' => array(
$agreementDetailsClass => new FilesystemStorage('/home/vagrant/tmp',$agreementDetailsClass),
$recurringPaymentDetailsClass => new FilesystemStorage('/home/vagrant/tmp',$recurringPaymentDetailsClass)
)
);
$payments = array(
'paypal' => PaymentFactory::create(new Api(new Curl, array(
'username' => 'REPLACE WITH YOURS',
'password' => 'REPLACE WITH YOURS',
'signature' => 'REPLACE WITH YOURS',
'sandbox' => true
)
)));
$registry = new SimpleRegistry($payments, $storages, null, null);
$tokenFactory = new GenericTokenFactory(
$tokenStorage,
$registry,
'https://'.$_SERVER['HTTP_HOST'],
'capture.php',
'notify.php'
);
prepare.php
use Payum\Paypal\ExpressCheckout\Nvp\Api;
include 'config.php';
$storage = $registry->getStorageForClass($agreementDetailsClass, 'paypal');
$agreementDetails = $storage->createModel();
$agreementDetails['PAYMENTREQUEST_0_AMT'] = 0;
$agreementDetails['L_BILLINGTYPE0'] = Api::BILLINGTYPE_RECURRING_PAYMENTS;
$agreementDetails['L_BILLINGAGREEMENTDESCRIPTION0'] = $subscription['description'];
$agreementDetails['NOSHIPPING'] = 1;
$storage->updateModel($agreementDetails);
$captureToken = $tokenFactory->createCaptureToken('paypal', $agreementDetails, 'create_recurring_payment.php');
$agreementDetails['RETURNURL'] = $captureToken->getTargetUrl();
$agreementDetails['CANCELURL'] = $captureToken->getTargetUrl();
$storage->updateModel($agreementDetails);
header("Location: ".$captureToken->getTargetUrl());
capture.php
use Payum\Core\Request\BinaryMaskStatusRequest;
use Payum\Core\Request\SecuredCaptureRequest;
use Payum\Core\Request\RedirectUrlInteractiveRequest;
include 'config.php';
$token = $requestVerifier->verify($_REQUEST);
$payment = $registry->getPayment($token->getPaymentName());
$payment->execute($status = new BinaryMaskStatusRequest($token));
if (false == $status->isNew()) {
header('HTTP/1.1 400 Bad Request', true, 400);
exit;
}
if ($interactiveRequest = $payment->execute(new SecuredCaptureRequest($token), true)) {
if ($interactiveRequest instanceof RedirectUrlInteractiveRequest) {
header("Location: ".$interactiveRequest->getUrl());
die();
}
throw new \LogicException('Unsupported interactive request', null, $interactiveRequest);
}
$requestVerifier->invalidate($token);
header("Location: ".$token->getAfterUrl());
create_recurring_payment.php
same as here
I have confirmed that file storage class is able to write data to files, but on capture step it fails to verify the token.
Any sort of help is appreciated to get this code running.
Token storage is not configured correctly (not your fault the doc is wrong too). It has to use hash model field as id. Try:
<?php
$tokenStorage = new FilesystemStorage('/home/vagrant/tmp', 'Paypal\Model\PaymentSecurityToken', 'hash');
About the exception you've gotten. It tries to find token by id and uses for that token's hash. Ofcouce it is could not be found.
link:http://henrypeteralbers.com/user_guide/general/creating_libraries.html.
I have used this to solve my problem but fail to do say after struggling 4 hours in google Please tell where I'm wrong. If run my file with including client file as library php throws an error :Non-existent myclass file.
how to create object of class my_class.
2.how to resolve error: Non-existent my_class error.
controller file
function a(){
$this->load->library('my_class');
$client = new OAuth2\my_class(CLIENT_ID, CLIENT_SECRET);
}
and myclass.php in lib folder
namespace oath2;
class my_class
{
}
here is core php code:
require('common/Client.php'); // include php wrapper class
require('common/GrantType/IGrantType.php');// include php wrapper class//
require('common/GrantType/AuthorizationCode.php'); // include php wrapper class//
const CLIENT_ID = '***********'; //generated from base_camp api//
const CLIENT_SECRET ='***********';
const REDIRECT_URI = '***********';
const AUTHORIZATION_ENDPOINT = 'https://launchpad.37signals.com/authorization/new';
const TOKEN_ENDPOINT = 'https://launchpad.37signals.com/authorization/token';
session_start();
$client = new OAuth2\my_class(CLIENT_ID, CLIENT_SECRET);
if (!isset($_GET['code']))
{
$_SESSION['org'] = $_GET['org'];
$auth_url = $client->getAuthenticationUrl(AUTHORIZATION_ENDPOINT, REDIRECT_URI);
header('Location: ' . $auth_url);
die('Redirect');
}
else
{
$params = array( 'type' => 'web_server', 'client_id' => CLIENT_ID, 'redirect_uri' => REDIRECT_URI, 'client_secret' => CLIENT_SECRET, 'code' => $_GET['code']);
$response = $client->getAccessToken(TOKEN_ENDPOINT, 'authorization_code', $params);
$client->setAccessToken($response['result']['access_token']);
$org = $_SESSION['org'].'_ess';
mysql_connect('localhost','root','*******') or die('Cannot connect to database !');
mysql_select_db($org) or die('No database found in mysql !');
$gcntct = mysql_query("select * from e_users");
if(mysql_num_rows($gcntct) != false)
{
mysql_query("update ess_users set user_access_token = '".$response['result']['access_token']."', user_refresh_token = '".$response['result']['refresh_token']."'");
}
$auth = $client->fetch('https://launchpad.37signals.com/authorization.json');
$counter = 0;
while($auth['result']['accounts'][$counter]['product'] != 'bcx')
{
$counter++;
}
mysql_query("update e_user_info set Account_href = '".$auth['result']['accounts'][$counter]['href']."'");
header('Location: /'.$_SESSION['org'].'/wizard.php');
}
function a(){
$this->load->library('my_class');
$client = $this->my_class->function_name((CLIENT_ID, CLIENT_SECRET);
}
and my_class.php in lib folder
class My_class
{
function function_name($a,$b)
{
//your code
}
}
I have something like that:
$client = new Zend_Http_Client('http://www.site.com');
$client->setParameterGet(array(
'platform' => $platform,
'clientId' => $clientId,
'deploymentId' => $deploymentId,
));
try {
$response = $client->request();
...
This would generate a request similar to 'http://www.site.com/?plataform=..?clientid?..'.
Is there a way I could retrieve this full URL generated by this GET request?
Kind regards,
Surprisingly enough there is no direct method for getting full request string.
BUT
After the request is done you could check $client->getLastRequest
().
If you need to know what the ?plataform=..?clientid? part of the
request is there is a trick.
function getClientUrl (Zend_Http_Client $client)
{
try
{
$c = clone $client;
/*
* Assume there is nothing on 80 port.
*/
$c->setUri ('http://127.0.0.1');
$c->getAdapter ()
->setConfig (array (
'timeout' => 0
));
$c->request ();
}
catch (Exception $e)
{
$string = $c->getLastRequest ();
$string = substr ($string, 4, strpos ($string, "HTTP/1.1\r\n") - 5);
}
return $client->getUri (true) . $string;
}
$client = new Zend_Http_Client ('http://yahoo.com');
$client->setParameterGet ('q', 'search string');
echo getClientUrl ($client);