Token Issue with recurring payments with Payum - php

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.

Related

Missing class import via use statement

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

Class 'Silex\Application' not found

I’ve done with google sign-up, I want to ask regarding google token_id authentication. Google issues a token-id to every user which changes on every sign-in, I am getting that token-id when the user sign-in, I want to authenticate that token-id from google to verify if the sign-in was original or fake. I am using this php api provided by google, but it is continuously giving this error:
Uncaught Error: Class 'Silex\Application' not found in C:\xampp\htdocs\final\gplus-verifytoken-php-master\verify.php:23
Stack trace: #0 {main} thrown in C:\xampp\htdocs\final\gplus-verifytoken-php-master\verify.php on line 23
require_once __DIR__.'/vendor/autoload.php';
require_once __DIR__.'/google-api-php-client/src/Google_Client.php';
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
const CLIENT_ID = 'xyz';
const CLIENT_SECRET = 'xyz';
const APPLICATION_NAME = "xyz";
$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$app = new Silex\Application();
$app['debug'] = true;
$app->register(new Silex\Provider\TwigServiceProvider(), array(
'twig.path' => __DIR__,
));
$app->register(new Silex\Provider\SessionServiceProvider());
// Initialize a session for the current user, and render index.html.
$app->get('/', function () use ($app) {
return $app['twig']->render('index.html', array(
'CLIENT_ID' => CLIENT_ID,
'APPLICATION_NAME' => APPLICATION_NAME
));
});
// Verify an ID Token or an Access Token.
// Example URI: /verify?id_token=...&access_token=...
$app->post('/verify', function (Request $request) use($app, $client) {
$id_token = "eyJhbGciOiJSUzI1NiIsImtpZCI6ImE0MzY0YjVmYjliODYxYzNhYTRkYTg5NWExMjk5NzZjMjgyZGJmYzIifQ.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwiaWF0IjoxNDg1NDEyMjQ1LCJleHAiOjE0ODU0MTU4NDUsImF0X2hhc2giOiJMSV9DTWxzeG1lSTdvQm9lSUxoSjZRIiwiYXVkIjoiNDY4MzU1OTM0NzMzLXZqNnRkdDJtazEwZ3R0OHJvZGY2bG84MHM4czdtdTRrLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwic3ViIjoiMTEyNjE1NTE5MDY0MTc3ODI0NTgzIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsImF6cCI6IjQ2ODM1NTkzNDczMy12ajZ0ZHQybWsxMGd0dDhyb2RmNmxvODBzOHM3bXU0ay5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbSIsImVtYWlsIjoibWdoYXphbmZhcmFsaWtoYW4wOUBnbWFpbC5jb20ifQ.Bpa2_zeVebQ7xtKXvuEell50bvUtKOGb5ZertUZGvzGWXnlA-c2kw4Mvko9Xd4JI_R4wbFoyBtrGCiK0jAlJMgaIH8p3wJbzNKPZ-gPFJdX8mv4v42v8-9urGM7rRUCDylz16WEcR1A2qOmEcNCpCf0_FGNpChl8sc8q8zvTnIb_zYYHp_V7ebR2RlUuO2z9G5YzBN3hZDnmen1xLStmNmYKsIiP5ypMqbWaLjnXJjre6bjTuIGymg_phDYDmwWMVTJyx88zmKAfwQTCh2u3qe_fkCDxxm0MO2wC29__q4uc0BfUNdH62GOrNTBJXmPTUZuT1vdUhzz4CLu1KUohWg";
/*$id_token = $request->get("id_token");*/
$access_token = $request->get("access_token");
$token_status = Array();
$id_status = Array();
if (!empty($id_token)) {
// Check that the ID Token is valid.
try {
// Client library can verify the ID token.
$jwt = $client->verifyIdToken($id_token, CLIENT_ID)->getAttributes();
$gplus_id = $jwt["payload"]["sub"];
$id_status["valid"] = true;
$id_status["gplus_id"] = $gplus_id;
$id_status["message"] = "ID Token is valid.";
} catch (Google_AuthException $e) {
$id_status["valid"] = false;
$id_status["gplus_id"] = NULL;
$id_status["message"] = "Invalid ID Token.";
}
$token_status["id_token_status"] = $id_status;
}
$access_status = Array();
if (!empty($access_token)) {
$access_status["valid"] = false;
$access_status["gplus_id"] = NULL;
// Check that the Access Token is valid.
$reqUrl = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=' .
$access_token;
$req = new Google_HttpRequest($reqUrl);
$tokenInfo = json_decode(
$client::getIo()->authenticatedRequest($req)
->getResponseBody());
if ($tokenInfo->error) {
// This is not a valid token.
$access_status["message"] = "Invalid Access Token.";
} else if ($tokenInfo->audience != CLIENT_ID) {
// This is not meant for this app. It is VERY important to check
// the client ID in order to prevent man-in-the-middle attacks.
$access_status["message"] = "Access Token not meant for this app.";
} else {
$access_status["valid"] = true;
$access_status["gplus_id"] = $tokenInfo->user_id;
$access_status["message"] = "Access Token is valid.";
}
$token_status["access_token_status"] = $access_status;
}
return $app->json($token_status, 200);
});
$app->run();
I did like this
composer install (after that run this command)
composer dump-autoload
it is working for me
If your Framework don't work after migration.
or see Class 'Silex\Application' not found.
Delete "vendor" folder after composer install.
Working for me

Unable to get User Credential grant type working

I have a Laravel 4.2 app that I have successfully implemented Authorization Code using oauth2-server-php. However, I can't seem to get User Credential grants working.
Here's my code setting up the oauth server:
App::singleton(
'oauth2',
function () {
$host = Config::get('database.connections.mongodb.host');
$hosts = is_array($host) ? $host : [$host];
$dbName = Config::get('database.connections.mongodb.database');
$dbOptions =
empty( Config::get('database.connections.mongodb.options') ) ? [] : Config::get(
'database.connections.mongodb.options'
);
$mongo = new MongoClient('mongodb://' . implode(',', $hosts) . '/' . $dbName, $dbOptions);
$storage = new OAuth2\Storage\Mongo($mongo->{$dbName});
$server = new OAuth2\Server(
$storage, [
'always_issue_new_refresh_token' => true,
'refresh_token_lifetime' => 2419200,
]
);
$userStorage = new \Medusa\Oauth\Storage\MedusaUserCredentials();
$server->addStorage($userStorage, 'users');
$userCredentialGrant = new Oauth2\GrantType\UserCredentials($userStorage);
$server->addGrantType(new OAuth2\GrantType\AuthorizationCode($storage));
$server->addGrantType(new OAuth2\GrantType\ClientCredentials($storage));
$server->addGrantType($userCredentialGrant);
$server->addGrantType(new OAuth2\GrantType\RefreshToken($storage));
return $server;
}
);
MedusaUserCredentials has the following code:
namespace Medusa\Oauth\Storage;
use OAuth2\Storage\UserCredentialsInterface;
class MedusaUserCredentials implements UserCredentialsInterface
{
public function checkUserCredentials($username, $password)
{
return Auth::attempt(['email_address' => strtolower($username), 'password' => $password, 'active' => 1]);
}
public function getUserDetails($username)
{
return ['user_id' => $username];
}
}
When I post to the web server to the token route using a raw payload of
grant_type=password&username=<USERNAME>&password=<PASSWORD>
I just get the login page. The token route looks like this
Route::post(
'oauth/token',
function () {
$bridgedRequest = OAuth2\HttpFoundationBridge\Request::createFromRequest(Request::instance());
$bridgedResponse = new OAuth2\HttpFoundationBridge\Response();
$bridgedResponse = App::make('oauth2')->handleTokenRequest($bridgedRequest, $bridgedResponse);
print_r($bridgedResponse); die();
return $bridgedResponse;
}
);
What am I missing?
Thanks!
I found the issue -- I had a namespace issue that I had to resolve. For some reason, my app returned a 200 OK response and the normal login page, so I didn't think to check the logs.
I know, bad dev, no cookie!

how to load libraries and creating object of another libraray class in codeigniter

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
}
}

how to create object of class in codeigniter

Here is my 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");
}
How do I initialize object of another class in mvc, I have adopt new method by initialize new by namespace name and class its show non existing class error.
oath2 is namespace and client is library class name.
function a()
{
$this->library('client');
How do pass clientid and secret key in during object creation codeigniter as if you would see my core php code I have initialize object with new operator and pass values , so how could we initialize object of class client and namespace with passing values in constructor.
}
client.php lib
namesapce oath2
class client
{
public function __construct($client_id, $client_secret, $client_auth = self::AUTH_TYPE_URI, $certificate_file = null)
{
if (!extension_loaded('curl')) {
throw new Exception('The PHP extention curl must be installed to use this library.', Exception::CURL_NOT_FOUND);
}
$this->client_id = $client_id;
$this->client_secret = $client_secret;
$this->client_auth = $client_auth;
$this->certificate_file = $certificate_file;
if (!empty($this->certificate_file) && !is_file($this->certificate_file)) {
throw new InvalidArgumentException('The certificate file was not found', InvalidArgumentException::CERTIFICATE_NOT_FOUND);
}
}
}
Create a library in Codeigniter and load it.
See here and here

Categories