how to create object of class in codeigniter - php

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

Related

Drupal 8 PHPUnit testing Invalid Credentials

I have a class I want to test that uses this module PHP HTTP client for Emarsys webservice, but when I try to test it, I will always get $response as "Credentials are invalid" from the module itself.
Here's a snippet of my code: (Given that I was able to correctly create my setUp() for Test Class since I was able to use it for other tests)
Test.php
Class TestClass extends UnitTestCase {
public function testCreateWithValidEmail() {
$newsletter = new Newsletter();
$form = new FormState();
$form->setValue('email', 'abc#def.ghi');
$response = $newsletter->register($form);
// Assertion here
}
}
Class.php
use Snowcap\Emarsys\CurlClient;
use Snowcap\Emarsys\Client;
Class Newsletter {
public function register(FormStateInterface $state){
$emailData = $state->getValue('email');
$httpClient = new CurlClient();
$client = new Client($httpClient, $api_username, $api_secret);
$someData = [
"3" => $emailData, // since 3 is the index ID for email
// ...more data here
];
$response = $client->createContact($someData);
}
}
Do I have to create a mock of something here to pass a dummy api and secret then force a valid response from createContact?
You are in the good direction. But that Newsletter class needs the $httpClient injected.
So you will be able to do:
$client = $this->getMockBuilder(Snowcap\Emarsys\CurlClient::class)
->disableOriginalConstructor()
->getMock();
$response = $this->getMockBuilder(ResponseInterface::class)
->disableOriginalConstructor()
->getMock();
$response->expects($this->any())
->method('getStatusCode')
->willReturn(Response::HTTP_OK);
$client->expects($this->any())
->method('createContact')
->with($someData)
->will($this->returnValue($response));
$newsletter = new Newsletter($client);
$response = $newsletter->register($form);
// Assertion here

How do you turn a Google Services oAuth2 into a Google Ads API oAuth2 access

So I'm working with Google API Client for PHP and I have an OAuth flow that works,
class GoogleClient {
private static $client_id = "1050479587066-f64vq210hc2m15fdj4r77g8ml7jin30d.apps.googleusercontent.com";
private static $client_Secret = "CK8orQfPNpD9UgF0bqNJinVI";
private static $redirect_uri = '/return.php';
private static $access;
private static $client = null;
private static function checkForAccess(){
if(isset(self::$access)){
return true;
}
if(isset($_SESSION['GoogleAuth'])){
self::$access = $_SESSION['GoogleAuth'];
return true;
}
return false;
}
public static function GetClient(){
if(is_null(self::$client)){
$params = [
"client_id" => self::$client_id,
"client_secret" => self::$client_Secret,
"redirect_uri" => self::$redirect_uri,
"application_name" => "Test AdWords System"
];
if(self::checkForAccess() && self::isLoggedIn()){
$param["access_token"] = self::$access['access_token'];
}
//Create and Request to access Google API
$client = new Google_Client($params);
}
return $client;
}
public static function doLogin(){
$scopes = [ 'https://www.googleapis.com/auth/adwords', 'https://www.googleapis.com/auth/dfp', "https://www.googleapis.com/auth/userinfo.email"];
return self::GetClient()->createAuthUrl($scopes);
}
public static function doLoginFinal(){
if (!$code = $_GET['code']) {
throw new Exception("Auth Code is missing.");
}
$authResponse = self::GetClient()->authenticate($code);
if (isset($authResponse['error'])) {
throw new Exception(
"Unable to get access token.",
null,
new Exception(
"{$authResponse['error']} {$authResponse['error_description']}"
)
);
}
$_SESSION['GoogleAuth'] = $authResponse;
self::$access = $authResponse;
}
public static function isLoggedIn(){
if(self::checkForAccess()){
if(isset(self::$access)){
$expiresAt = #self::$access['created']+#self::$access['expires_in'];
return (time() < $expiresAt);
}
}
return false;
}
public static function GetExpiry(){
if(self::checkForAccess()){
return self::$access['created']+self::$access['expires_in'];
}
throw new Exception("The User is not logged into a google account.");
}
}
now this class is working I'm able to log in and I have the scope for google-adwords the problem comes about due to poor documentation for the googleads-php-lib
So from the example to getCampaigns it uses $oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build(); but i don't have a file so i went into the OAuth2TokenBuilder file I'm unable to work out how i could give the already generated access tokens to the googleads objects.
I have double checked the google-php-api-client services repo and there is no adwords Service I can use.
I have been digging through the source files of the googleads-php-lib to see if I can find a method to implement this but so far I'm just getting stuck as everything seems to require specific parameter types so I can rig something to provide the details, but the code always seems to rely on multiple classes so I can't just build one that extends a class. and i pass that through.
Keys will be destoried after this test is working!
Well after days of digging around source files and hacking this and that I finally found an implementation that works.
After creating my manager account:
https://developers.google.com/adwords/api/docs/guides/signup
So this is the two new methods added to my GoogleClient Static Class
private static $developerToken = "";
private static function GetUserRefreshCredentials(){
return new UserRefreshCredentials(
null,
[
'client_id' => self::$client_id,
'client_secret' => self::$client_secret,
'refresh_token' => self::$access['refresh_token']
]
);
}
public function GetAdwordsSession(){
$builder = new AdWordsSessionBuilder();
$builder->defaultOptionals();
$builder->withDeveloperToken(slef::$developerToken);
return $builder->withOAuth2Credential(self::GetUserRefreshCredentials())->build();
}

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

Token Issue with recurring payments with Payum

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.

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

Categories