Omnipay Paypal set store name and logo (Laravel) - paypal

How can I set the store name and logo using the Omnipay Paypal package for Laravel?
Please see my code below, until now I tried to use the method setBrandName on the gateway variable, but this method was not found. It seems like the class ExpressCheckout has such methods but is like deprecated and one should use this code and checkout procedure. Also tried to add entry to the purchase method array parameter but it didn't work.
<?php
namespace App\Http\Controllers;
..
use Omnipay\Omnipay;
class PurchaseController extends Controller
{
public $gateway;
public function __construct()
{
$this->gateway = Omnipay::create('PayPal_Rest');
$this->gateway->setClientId(...);
$this->gateway->setSecret(...);
$this->gateway->setTestMode(true);
}
protected function makePurchase(Request $request) {
try {
$items = ...;
$response = $this->gateway->purchase(array(
'amount' => $cart->getSum(),
'items' => $items,
'currency' => config('paypal.currency'),
'returnUrl' => route('payment.success'),
'cancelUrl' => route('cart'),
))->send();
if ($response->isRedirect()) {
$response->redirect(); // this will automatically forward the customer
} else {
// not successful
return $response->getMessage() . ", " . $response->getCode();
}
} catch(Exception $e) {
return $e->getMessage();
}
}
protected function purchaseCompleted(Request $request) {
...
}
}

Related

ZF3: ServiceNotFoundException while creating a class with Abstract Factory registered in ServiceManager

I got problem with the Abstract Factories example.
I get ServiceNotFoundException while creating a class with Abstract Factory registered in the ServiceManager.
First I download zend-servicemanager with composer
composer require zendframework/zend-servicemanager
Then I run the ServiceManager example in the single file (for simplicity).
<?php
require_once 'vendor/autoload.php';
use Interop\Container\ContainerInterface;
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\Factory\InvokableFactory;
use Zend\ServiceManager\Factory\FactoryInterface;
use Zend\ServiceManager\Factory\AbstractFactoryInterface;
Class that should be obtained with ServiceManager.
class A
{
public $text;
public function __construct()
{
$this->text = "Default text";
}
}
I use MyAbstractFactory from documentation.
class MyAbstractFactory implements AbstractFactoryInterface
{
public function canCreate(ContainerInterface $container, $requestedName)
{
return in_array('Traversable', class_implements($requestedName), true);
}
public function __invoke(ContainerInterface $container,
$requestedName,
array $options = null)
{
return $requestedName();
}
}
I create ServiceManager with registered Abstract Factory.
$serviceManager = new ServiceManager([
// Neither works
//'abstract_factories' => array('MyAbstractFactory')
'abstract_factories' => array( new MyAbstractFactory() )
//'abstract_factories' => array( MyAbstractFactory::class )
/*
'abstract_factories' => [
MyAbstractFactory::class => new MyAbstractFactory()
]
*/
]);
Finally I try to obtain the instance of class A.
$a = $serviceManager->get(A::class);
var_dump($a);
I get
Fatal error: Uncaught Zend\ServiceManager\Exception\ServiceNotFoundException: Unable to resolve service "A" to a factory; are you certain you provided it during configuration?
with the stack trace
.\vendor\zendframework\zend-servicemanager\src\ServiceManager.php(763): Zend\ServiceManager\ServiceManager->getFactory('A') #1
.\vendor\zendframework\zend-servicemanager\src\ServiceManager.php(200): Zend\ServiceManager\ServiceManager->doCreate('A') #2
.\script.php(53): Zend\ServiceManager\ServiceManager->get('A') #3
My formulation of the problem was wrong. #rkeet's comment made it clear.
As my objective was the working example of the Abstract Factory registration within ServiceManager, I post the single-file script where canCreate() is simplified just to check if the class exists.
<?php
// composer require zendframework/zend-servicemanager
require_once 'vendor/autoload.php';
use Interop\Container\ContainerInterface;
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\Factory\AbstractFactoryInterface;
class A
{
public $text;
public function __construct()
{
$this->text = "Default text";
}
}
class MyAbstractFactory implements AbstractFactoryInterface
{
public function canCreate(ContainerInterface $container, $requestedName)
{
return class_exists($requestedName);
}
public function __invoke(ContainerInterface $container,
$requestedName,
array $options = null)
{
return new $requestedName();
}
}
$serviceManager = new ServiceManager([
//'abstract_factories' => array('MyAbstractFactory') // works
//'abstract_factories' => array( new MyAbstractFactory() ) // works
'abstract_factories' => array( MyAbstractFactory::class ) // also works
]);
try {
$a = $serviceManager->get(A::class);
var_dump($a);
echo "<br/>\n";
$b = $serviceManager->get(B::class);
var_dump($b);
} catch (Exception $e) {
echo $e->getMessage() . "<br/>\n";
echo "{$e->getFile()} ({$e->getLine()})";
}
?>
As #rkeet pointed, if someone needs the original example working, class A should implement Traversable.

Kohana rest api implementaion: how to start with SupersonicAds/kohana-restful-api?

I am new to kohana framework. I need to implement rest api for my application.
I have downloded rest api from https://github.com/SupersonicAds/kohana-restful-api and placed in my localhost. Under modules. now the file structre is
I have enabled module in bootstrap.php as
Kohana::modules(array(
'auth' => MODPATH.'auth', // Basic authentication
'rest' => MODPATH.'rest', // Basic Rest example
// 'cache' => MODPATH.'cache', // Caching with multiple backends
// 'codebench' => MODPATH.'codebench', // Benchmarking tool
'database' => MODPATH.'database', // Database access
// 'image' => MODPATH.'image', // Image manipulation
// 'minion' => MODPATH.'minion', // CLI Tasks
'orm' => MODPATH.'orm', // Object Relationship Mapping
// 'unittest' => MODPATH.'unittest', // Unit testing
// 'userguide' => MODPATH.'userguide', // User guide and API documentation
));
i have created a controller by extending "Controller_Rest" Now according to wiki i should be able to access "$this->_user, $this->_auth_type and $this->_auth_source" variables but in my case its not happening what i am doing wrong?
And i checked in console network it always showing status as "401 Unauthorised"
For using Authorization,you need to extend Kohana_RestUser Class
The module you are using comes with an abstract Kohana_RestUser class, which you must extend in your app. The only function that requires implementation is the protected function _find(). The function's implementation is expected to load any user related data, based on an API key.
I will explain you with an example
<?php
// Model/RestUser.php
class RestUser extends Kohana_RestUser {
protected $user='';
protected function _find()
{
//generally these are stored in databases
$api_keys=array('abc','123','testkey');
$users['abc']['name']='Harold Finch';
$users['abc']['roles']=array('admin','login');
$users['123']['name']='John Reese';
$users['123']['roles']=array('login');
$users['testkey']['name']='Fusco';
$users['testkey']['roles']=array('login');
foreach ($api_keys as $key => $value) {
if($value==$this->_api_key){
//the key is validated which is authorized key
$this->_id = $key;//if this not null then controller thinks it is validated
//$this->_id must be set if key is valid.
//setting name
$this->user = $users[$value];
$this->_roles = $users[$value]['roles'];
break;
}
}
}//end of _find
public function get_user()
{
return $this->name;
}
}//end of RestUser
Now Test Controller
<?php defined('SYSPATH') or die('No direct script access.');
//Controller/Test.php
class Controller_Test extends Controller_Rest
{
protected $_rest;
// saying the user must pass an API key.It is set according to the your requirement
protected $_auth_type = RestUser::AUTH_TYPE_APIKEY;
// saying the authorization data is expected to be found in the request's query parameters.
protected $_auth_source = RestUser::AUTH_SOURCE_GET;//depends on requirement/coding style
//note $this->_user is current Instance of RestUser Class
public function before()
{
parent::before();
//An extension of the base model class with user and ACL integration.
$this->_rest = Model_RestAPI::factory('RestUserData', $this->_user);
}
//Get API Request
public function action_index()
{
try
{
$user = $this->_user->get_name();
if ($user)
{
$this->rest_output( array(
'user'=>$user,
) );
}
else
{
return array(
'error'
);
}
}
catch (Kohana_HTTP_Exception $khe)
{
$this->_error($khe);
return;
}
catch (Kohana_Exception $e)
{
$this->_error('An internal error has occurred', 500);
throw $e;
}
}
//POST API Request
public function action_create()
{
//logic to create
try
{
//create is a method in RestUserData Model
$this->rest_output( $this->_rest->create( $this->_params ) );
}
catch (Kohana_HTTP_Exception $khe)
{
$this->_error($khe);
return;
}
catch (Kohana_Exception $e)
{
$this->_error('An internal error has occurred', 500);
throw $e;
}
}
//PUT API Request
public function action_update()
{
//logic to create
}
//DELETE API Request
public function action_delete()
{
//logic to create
}
}
Now RestUserData Model
<?php
//Model/RestUserData.php
class Model_RestUserData extends Model_RestAPI {
public function create($params)
{
//logic to store data in db
//You can access $this->_user here
}
}
So index.php/test?apiKey=abc returns
{
"user": {
"name": "Harold Finch",
"roles": [
"admin",
"login"
]
}
}
Note: K in apiKey is Capital/UpperCase
I Hope this Helps
Happy Coding :)

Pass a value from controller to partial in ZF2

I want to pass some value from controller to view partial, basically, view partial is set using the placeholder in Application\Module.php, here is the code that does it.
<?php
namespace Application;
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
use Zend\View\Renderer\PhpRenderer;
use Zend\View\Resolver;
use Zend\ServiceManager\ServiceManager;
class Module
{
public function onBootstrap(MvcEvent $e)
{
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$eventManager->attach(\Zend\Mvc\MvcEvent::EVENT_DISPATCH, array($this, 'initBreadcrumbAndActionButtonWidget'));
$moduleRouteListener->attach($eventManager);
$serviceManager = $e->getApplication()->getServiceManager();
}
public function initBreadcrumbAndActionButtonWidget(\Zend\Mvc\MvcEvent $e)
{
$serviceManager = $e->getApplication()->getServiceManager();
$config = $serviceManager->get('config');
$viewHelperManager = $this->getViewHelperManager($e->getApplication()->getServiceManager());
$partialHelper = $viewHelperManager->get('partial');
$partial = $partialHelper('widgets/breadcrumb', array(
'config' => $config,
'actionButtons' => $config['action-buttons']
));
$placeHolder = $viewHelperManager->get('placeholder');
$placeHolder('widgets/breadcrumb')->set($partial);
}
public function getViewHelperManager($serviceManager)
{
$stack = new Resolver\TemplatePathStack(array('script_paths' => array(__DIR__ . '/view/')));
$resolver = new Resolver\AggregateResolver();
$resolver->attach($stack);
$renderer = new PhpRenderer();
$renderer->setResolver($resolver);
$viewHelperManager = $serviceManager->get('ViewHelperManager');
return $viewHelperManager;
}
public function getConfig()
{
return array_merge_recursive(
include __DIR__ . '/config/module.config.php',
);
}
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
}
It is all working good till here, however now i want to pass a value from controller to the partial widgets/breadcrumb, after several attempt i thought implementing a ViewHelper could be a solution, and i implemented following view helper.
<?php
namespace Application\View\Helper;
use Zend\View\Helper\AbstractHelper;
class Variable extends AbstractHelper
{
protected $data;
public function __invoke()
{
return $this;
}
public function set($identifier, $data)
{
$this->data[$identifier] = $data;
return $this;
}
public function get($identifier)
{
return $this->data[$identifier];
}
}
In controller i assign the value to ViewHelper like this.
$viewHelperManager = $this->getServiceLocator()->get('ViewHelperManager');
$variable = $viewHelperManager->get('variable');
$variable->set('stack', 'overflow');
And in partial, to access the value i use the get method.
$this->variable()->get('stack');
Now my problem is that get() is rendered first hence the value set in controller has no effect.
My question is how can i make the set() gets rendered first so i can have the value in partial, or if there is any better approach of passing the value to partial please suggest.
Thanks.
Baaah, i called the view helper in wrong action, it worked when i moved the $variable->set('stack', 'overflow'); in the action where i wanted the value to pass.
Not sure if there can be a better solution, but this does the job for me to pass the value after i found no way in ZF2 that satisfies my requirement.

How do I write unit tests for a REST API built in Slim Framework?

I have an API built in Slim like this:
$app->group('/'.$endpoint, function () use ($app, $endpoint) {
$handler = Api\Rest\Handlers\Factory::load($endpoint);
if (is_null($handler)) {
throw new \Exception('No REST handler found for '.$endpoint);
}
$app->get('(/:id)', function ($id) use ($app, $handler) {
echo json_encode($handler->get($id));
});
$app->post('', function () use ($app, $handler) {
echo json_encode($handler->post($app->request->post()));
});
$app->put(':id', function ($id) use ($app, $handler) {
echo json_encode($handler->put($id, $app->request->put()));
});
$app->delete(':id', function ($id) use ($app, $handler) {
echo json_encode($handler->delete($id));
});
});
$endpoint is a string, for example 'user';
How do I go about writing unit tests for it?
Ideally;
class RestUserTest extends PHPUnitFrameworkTestCase
{
public function testGet()
{
$slim = ''; // my slim app
// set route 'api/user/1' with method GET
// invoke slim
// ensure that what we expected to happen did
}
}
(The REST handler class would make it trivial to mock the results that would ordinarily be backed by a DB.)
It's the nitty gritty of how to spoof the request into Slim that I don't know how to do.
You can have a try with this guidelines. It may help you. I tried it for one of my slim project.
Let me know if that helps.
Codes
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use Slim\Environment;
class RoutesTest extends PHPUnit_Framework_TestCase
{
public function request($method, $path, $options = array())
{
// Capture STDOUT
ob_start();
// Prepare a mock environment
Environment::mock(array_merge(array(
'REQUEST_METHOD' => $method,
'PATH_INFO' => $path,
'SERVER_NAME' => 'slim-test.dev',
), $options));
$app = new \Slim\Slim();
$this->app = $app;
$this->request = $app->request();
$this->response = $app->response();
// Return STDOUT
return ob_get_clean();
}
public function get($path, $options = array())
{
$this->request('GET', $path, $options);
}
public function testIndex()
{
$this->get('/');
$this->assertEquals('200', $this->response->status());
}
}
full code hosted in Gist . see this

ZF using placeholders inside plugins

I'm trying to implement a plugin that handles responses to the user on success or failure in a persistance transaction. When the response is false I use a _forward to the action that performed the form's submit and get my placeholder message shown but when the response is true I use a _redirect to the browse with the new record shown.
My problem is that when I use _redirect the browser doesn't show the placeholder message. I'll show the code here:
/**
* Plugin
*/
class Application_Plugin_PostMessage extends Zend_Controller_Plugin_Abstract
{
public function postDispatch(Zend_Controller_Request_Abstract $request)
{
$message = $request->getParam('message');
$error = $request->getParam('error');
if (null !== $message || null !== $error) {
$layout = Zend_Layout::getMvcInstance();
$view = $layout->getView();
$placeHolder = $view->placeholder('message');
$placeHolder->setPostfix('</div>');
if (null !== $error) {
$placeHolder->setPrefix('<div class="errorMessage">')
->append($error);
}
elseif (null !== $message) {
$placeHolder->setPrefix('<div class="infoMessage">')
->append($message);
}
}
}
}
/**
* Controller
*/
class My_FooController extends Zend_Controller_Action
{
public function init()
{
$front = Zend_Controller_Front::getInstance();
$front->registerPlugin(new Application_Plugin_PostMessage());
}
...
public function browseAction()
{
...
// No message is shown here on redirect
...
}
public function newAction()
{
...
// This code shows the placeholder on _forward call
...
}
public function insertAction()
{
if(true) {
return $this->_redirect('/my/foo/browse?message='
. urlencode("success message"));
}
else {
return $this->_forward('new', null, null, array(
'error' => 'error messsage'
));
}
}
}
I can't use _forward on success because I don't want the use of [F5] key repeats the insert action
Thanks in advance
This is what Flash Messenger is for:
http://framework.zend.com/manual/en/zend.controller.actionhelpers.html#zend.controller.actionhelper.flashmessenger.basicusage
It stores messages in your session removing the need for passing messages as you are.