cakephp-sms not working transport class not found - php

I am trying to send sms using cakephp-sms plugin
The documentation is quite clear and brief. I installed it using Composer in my app/Plugin directory. I also installed xi-sms using composer. This was installed in the Vendor directory. In my controller for sending sms. I included App::uses('CakeSms', 'Sms.Network/Sms') and implemented an InfobipSmsTransport class in the Sms/Lib/Network/Sms. Below is my class
<?php
use Xi\Sms\Gateway\InfobipGateway;
App::uses('AbstractSmsTransport', 'Sms.Network/Sms');
class InfobipSmsTransport extends AbstractSmsTransport {
const INFOBIP_USER = 'XXXXX';
const INFOBIP_PASSWORD = 'XXXXXXX';
/**
*
* #param CakeSms $sms
* #return bool Success
*/
public function send(CakeSms $sms) {
$gw = new InfobipGateway(
self::INFOBIP_USER,
self::INFOBIP_PASSWORD
);
$service = new Xi\Sms\SmsService($gw);
$msg = new Xi\Sms\SmsMessage(
$sms->message(),
$sms->from(),
$sms->to()
);
$response = $service->send($msg);
return !empty($response);
}
}
?>
When I try to send an SMS however I get the following error
Class "InfobipSmsTransport" not found.. I have no idea what am doing wrong? Any clues or suggestions are welcome.

The CakeSms class was not loading the plugin. This is the line of code where it was failing.
App::uses($transportClassname, $plugin . 'Network/Sms');.
In my app/Config/sms.php I just changed this 'transport' =>'Infobip' to
'transport' =>'Sms.Infobip'. The plugin is now being loaded properly and the class is found.

Related

How to "mock" Sentry client in the PHPUnit tests

In case if you need to test PHP application error handlers, you have to "mock" or just disable sending errors on remote servers in the Sentry client. What is the right way to do this?
This is the example for Laravel, but this approach should work for any framework.
use Sentry\Client;
use Sentry\EventFactory;
use Sentry\Options;
use Sentry\Serializer\RepresentationSerializer;
use Sentry\Serializer\Serializer;
use Sentry\Transport\NullTransport;
private function mockSentry(): void
{
/** #var \Sentry\State\Hub $sentry */
$sentry = $this->app['sentry']; // Get sentry object from Laravel's container
$client = new Client(
new Options(),
new NullTransport(),
new EventFactory(
new Serializer(new Options()),
new RepresentationSerializer(new Options()),
new Options(),
'1',
'1',
),
);
$sentry->bindClient($client);
}

Fatal error: Class '\PayPal\Log\PayPalDefaultLogFactory' not found

I'm first in using Paypal REST SDK when I want to create a payment. This error occurs.
Fatal error: Class '\PayPal\Log\PayPalDefaultLogFactory' not found in /xxx/xxx/xxx/xxx/xxx/xxx/xxx/xxx/vendor/paypal/rest-api-sdk-php/lib/PayPal/Core/PayPalLoggingManager.php on line 62
The error occurs while executing this code.
try {
$payment->create($apiContext);
// Get PayPal redirect URL and redirect the customer
$approvalUrl = $payment->getApprovalLink();
// Redirect the customer to $approvalUrl
} catch (PayPal\Exception\PayPalConnectionException $ex) {
echo $ex->getCode();
echo $ex->getData();
die($ex);
} catch (Exception $ex) {
die($ex);
}
How to solve this problem ??
** SDK version 1.14.0
Line 62 contains the code $factoryInstance->getLogger($loggerName)
private function __construct($loggerName)
{
$config = PayPalConfigManager::getInstance()->getConfigHashmap();
// Checks if custom factory defined, and is it an implementation of #PayPalLogFactory
$factory = array_key_exists('log.AdapterFactory', $config) && in_array('PayPal\Log\PayPalLogFactory', class_implements($config['log.AdapterFactory'])) ? $config['log.AdapterFactory'] : '\PayPal\Log\PayPalDefaultLogFactory';
/** #var PayPalLogFactory $factoryInstance */
$factoryInstance = new $factory();
$this->logger = $factoryInstance->getLogger($loggerName);
$this->loggerName = $loggerName;
}
If you look further up the code it is looking for the 'log.AdapterFactory' setting. This is normally not included in your ApiContext settings located in your config file.
Insert the log.AdapterFactory setting into your ApiContext settings located in your config file or bootstrap file whichever you have decided to create.
This is normally associated with the AdapterFactory that you are using.
Here is a very useful sample from the Github Repository illustrating the various settings that you can use with the new logger feature available in PayPal. Look in particular at line 94
$apiContext->setConfig(
array(
'mode' => 'sandbox',
'log.LogEnabled' => true,
'log.FileName' => '../PayPal.log',
'log.LogLevel' => 'DEBUG', // PLEASE USE `INFO` LEVEL FOR LOGGING IN LIVE ENVIRONMENTS
'cache.enabled' => true,
//'cache.FileName' => '/PaypalCache' // for determining paypal cache directory
// 'http.CURLOPT_CONNECTTIMEOUT' => 30
// 'http.headers.PayPal-Partner-Attribution-Id' => '123123123'
//'log.AdapterFactory' => '\PayPal\Log\DefaultLogFactory' // Factory class implementing \PayPal\Log\PayPalLogFactory
)
);
You will normally also have to create a Class MonologLogFactory using the official Paypal recommendations here. Remember to include a suitable namespace at the top of your file relative to path/folder/file/location. Here is the code from Paypal:
use PayPal\Log\PayPalLogFactory;
use Psr\Log\LoggerInterface;
class MonologLogFactory implements PayPalLogFactory
{
/**
* Returns logger instance implementing LoggerInterface.
*
* #param string $className
* #return LoggerInterface instance of logger object implementing LoggerInterface
*/
public function getLogger($className)
{
$logger = new Monolog\Logger($className);
$logger->pushHandler(new Monolog\Handler\StreamHandler("mail.log"));
return $logger;
}
}
If you are still encountering problems double check that you actually have the file located in C:\wamp32\www\projectfoldername\web\vendor\paypal\rest-api-sdk-php\lib\PayPal\Log\PayPalDefaultLogFactory on your testing platform. I am using wampserver.
If the file is not located here ensure that your composer.json file has "paypal/rest-api-sdk-php": "*" under it and then update composer.

php - Stripe Usage Record class not found

I'm trying to add usage records to my subscription. using the stripe create usage record endpoint (https://stripe.com/docs/api#usage_record_create).
running my function im getting an error returning saying Class 'Stripe\UsageRecord' not found in file I havent defined the namespace because I have beeen accessing it directly referencing stripe using \Stripe\ which I brought in using composer. I've tried a composer update but that didnt seem to do the trick. I'm guessing it's missing the UsageRecord.php file from the composer install but I have no clue where to add a copy of the file to the stripe package
public function stripeUsageRecord()
{
$authUser = auth()->user();
$business = $authUser['business_id'];
$user_amount = Transactions::select("user_id")
->where("business_id", "=", $business)
->groupBy("user_id")->count();
$current_time = Carbon::now()->toDateTimeString();
\Stripe\Stripe::setApiKey(env("STRIPE_SECRET"));
\Stripe\UsageRecord::create(array(
"quantity" => $user_amount,
"timestamp" => $current_time,
"subscription_item" => 'sub_DnAKVwNY2Sc4zf',
"action" => 'set'
));
}
Most likely you're using too old version of this library. Stripe\UsageRecord was introduced in version 6.6.0, so I suggest to update library to the last version:
composer require "stripe/stripe-php:^6.19"
You definitely should not modify content of vendor directory and copy&paste classes from different version of library.
Seemed like I was missing a part of the stripe package.
I found a copy of UsageRecord.php online and created the file in path vendor\stripe\stripe-php\lib\UsageRecord.php
I then added the contents of the code that I found online and added them to the file and it worked. The contents are posted below:
<?php
namespace Stripe;
/**
* Class UsageRecord
*
* #package Stripe
*
* #property string $id
* #property string $object
* #property bool $livemode
* #property int $quantity
* #property string $subscription_item
* #property int $timestamp
*/
class UsageRecord extends ApiResource
{
const OBJECT_NAME = "usage_record";
/**
* #param array|null $params
* #param array|string|null $options
*
* #return \Stripe\ApiResource The created resource.
*/
public static function create($params = null, $options = null)
{
self::_validateParams($params);
if (!array_key_exists('subscription_item', $params)) {
throw new Error\InvalidRequest("Missing subscription_item param in request", null);
}
$subscription_item = $params['subscription_item'];
$url = "/v1/subscription_items/$subscription_item/usage_records";
$request_params = $params;
unset($request_params['subscription_item']);
list($response, $opts) = static::_staticRequest('post', $url, $request_params, $options);
$obj = \Stripe\Util\Util::convertToStripeObject($response->json, $opts);
$obj->setLastResponse($response);
return $obj;
}
}

Soap and laravel don't work together

I'm trying to connect my client soap to my serve soap without sucess on Laravel. My SO is ubuntu 16.
I've searched on google and here on stackoverflow and I didn't find anything.
This is my route:
Route::get('/server.wsdl','SOAP\WsdlController#index');
Route::any('/server','SOAP\ServidorController#server');
Route::get('/client','SOAP\ClientController#client');
This is my ClientController:
use Zend\Soap\Client;
public function client(){
$client = new Client('http://localhost:8080/server.wsdl',[
'soap_version'=> SOAP_1_1
]);
$array = array(
"num1" => 10,
"num2" => 10
);
print_r($client->sum($array));
}
This is my ServidorController:
use Zend\Soap\Server;
class ServidorController extends Controller
{
public $serverUrl = "http://localhost:8080/server";
public function server()
{
$soap = new Server($this->serverUrl . '.wsdl');
$soap->setClass('App\Http\Controllers\Classes\Hello');
$soap->handle();
}
}
This is my WsdlController:
use Zend\Soap\AutoDiscover;
class WsdlController extends Controller
{
public $serverUrl = "http://localhost:8080/server";
public function index()
{
$soapAutoDiscover = new AutoDiscover(new
\Zend\Soap\Wsdl\ComplexTypeStrategy\ArrayOfTypeSequence());
$soapAutoDiscover->setBindingStyle(array('style' => 'document'));
$soapAutoDiscover->setOperationBodyStyle(array('use' =>
'literal'));
$soapAutoDiscover->setClass('App\Http\Controllers\Classes\Hello');
$soapAutoDiscover->setUri($this->serverUrl);
$soapAutoDiscover->handle();
}
}
Finally this is my class Hello:
class Hello
{
/**
* #param int $num1
* #param int $num2
* #return int
*/
function soma($num1, $num2)
{
return $num1 + $num2;
}
}
My framework shows this error:
SoapFault
Too few arguments to function App\Http\Controllers\Classes\Hello::soma(), 1 passed and exactly 2 expected
But in the function's declaration I putted the 2 arguments. What's happened whith this?
Ah, I take it soma is actually sum, and you translated before posting?
Look here:
$client->sum($array);
You pass one argument, an array, whereas your class expects two arguments.
Instead:
$client->sum($array['num1'], $array['num2']);
This were my errors: I was running the command on terminal 1 "php artisan serve" and in the terminal 2, I was running "php artisan serve --port:8080" and as you can see bellow, the $client was pointing to 'http://localhost:8080/server.wsdl'.
$client = new Client('http://localhost:8080/server.wsdl',[
'soap_version'=> SOAP_1_1
]);
I've solved my ask when I installed, start and setting the apache2 server on ubuntu 16. I've pointed the default folder to my laravel aplication and it works fine.

Symfony2 : get current directory error

When I try to get the current directory with :
$this->container->getParameter('kernel.root_dir').'/../web/
I've got this error : Fatal error: Using $this when not in object context in C:\XXX on line 124
Code :
class AdminController {
/**
* Add event controller.
*
* #param Request $request Incoming request
* #param Application $app Silex application
*/
public function addEventAction(Request $request, Application $app) {
$event = new Event();
$types= $app['dao.type']->findAllSelectList();
$eventForm = $app['form.factory']->create(new EventType($types), $event);
$eventForm->handleRequest($request);
if ($eventForm->isSubmitted() && $eventForm->isValid()) {
var_dump($event->getCoverImageLink());
$file = $event->getCoverImageLink();
$fileName = md5(uniqid()).'.'.$file->guessExtension();
var_dump($fileName);
//$path = $this->container->getParameter('kernel.root_dir').'/../web';//$this->get('kernel')->getRootDir() . '/../web';
var_dump($this);
$app['dao.event']->save($event);
$app['session']->getFlashBag()->add('success', 'The event was successfully created.');
}
return $app['twig']->render('event_form.html.twig', array(
'title' => 'New event',
'eventForm' => $eventForm->createView()));
}
How to fix this error please? What is the correct function to use?
It appears that you are using Silex, not Symfony 2. Being a very minimalistic framework, silex doesn't give you all the configuration and dependency injection goodies that Symfony does.
The easiest approach to be able to retrieve the application root, would be to define it yourself in bootstrap.php. Simply add something like this at the top:
define('APP_ROOT', __DIR__ . '/../');
Now you can just use the constant in your controller:
public function addEventAction(Request $request, Application $app) {
...
$path = APP_ROOT . '/../web';
...
}

Categories