retrieving authorize.net credit card number in sugarcrm v6.5 - php

I want to retrieve the CC number from authorize.net and display it in sugarcrm v6.5 my problem now is that in the documentation found in authorize.net the code is meant for native PHP. And I just started learning sugarcrm, now what I want to learn is how do I use the code in their document to match sugarcrm.
this it the link to their code I want to use link here
this is my current implementation. And I get this error in sugarcrm: "There was an error processing your request, please try again at a later time."
<?php
require_once("include/MVC/View/views/view.detail.php");
use CB\Integrations\Provider\AuthorizeNet;
class CB_PaymentProfilesViewDetail extends ViewDetail
{
var $contacts_warning;
var $company_logo_path;
var $company_tagline;
var $provider;
public function __construct()
{
global $sugar_config;
$settings = $sugar_config["authorizenet_settings"];
$this->provider = new AuthorizeNet();
$this->provider->auth($settings["appName"], $settings["transactionKey"]);
parent::ViewDetail();
}
function preDisplay() {
$this->contacts_warning = 'Our contacts database is not for personal use. Please do not use it for things not strictly related to company business. You know who you are!';
$this->company_tagline = 'Serving the biggest and brightest stars in Hollywood!';
parent::preDisplay();
}
public function display()
{
$this->provider->setCustomerProfileId(40843288);
echo '<div align="center" style="font-color: red">'.$this->provider->getCustomerPaymentProfileId() .'</div>';
if ($this->bean->name) {
$this->dv->defs['templateMeta']['form']['buttons'][] = array(
"customCode" => '{$CUSTOMER_PROFILE}'
);
$this->ss->assign('CUSTOMER_PROFILE',
$this->bean->provider->getHostedProfilePageButton($this->bean->name)
);
}
parent::display();
}
}

Related

Unreachable variable while working with Google AdWords API in PHP

I have a problem in PHP and I can't seem to solve it. I am using Google AdWords API to create campaigns. So first of all I create a new Campaign, and after that new GroupAd. Problem is that I get campaign ID when creating campaign, and although I save that ID in variable $mycampaignID, I can't use it in another class where I am creating GroupAd. Can someone help me with this? I tried using global variable, public variable, etc., but none of it seems to work properly. Here is just a part of the code, you can see how classes and function look like.
class AddCampaigns
{
public static function runExample(
AdWordsServices $adWordsServices,
AdWordsSession $session
) {
$result = $campaignService->mutate($operations);
foreach ($result->getValue() as $campaign) {
**$mycampaignID** = $campaign->getId();
printf(
"Campaign with name '%s' and ID %d was added.\n",
$campaign->getName(),
$campaign->getId()
);
}
}
}
AddCampaigns::main();
class AddAdGroups
{
const CAMPAIGN_ID = **$mycampaignID**;
public static function runExample(
AdWordsServices $adWordsServices,
AdWordsSession $session,
$campaignId
) {
$adGroupService = $adWordsServices->get($session, AdGroupService::class);
}
}
AddAdGroups::main();

Fatal error: Call to undefined method Mage_Sales_Model_Resource_Order_Status_Collection::addStatusFilter()

I use a finance payment module on my site which redirects the user after placing an order to the finance website to fill in their details.
I've just installed the 'One step checkout' from Magestore and testing the order cycle to make sure it worked like before, it doesn't.
After placing the order I get the error in the title
It's telling me there's an error on line 20 in StatusUpdate.php, below is the code for this file.
Can anyone tell me what's going on? Screengrab of error
<?php
class C3_V12Finance_Helper_StatusUpdate extends Mage_Core_Helper_Abstract
{
public function handleOrderStatusUpdate(Mage_Sales_Model_Order $order, $configPath) {
if ($status = Mage::getStoreConfig($configPath)) {
$state = $this->getStateFromStatus($status);
/* Magento doesn't allow some states to be changed manually ('complete' and 'closed'). This validation only
* occurs however when you change state via setState. The validation doesn't occur on setData, however so
* we use this as a workaround. */
$order->setData('state', $state)
->setStatus($status)
->save();
return true;
}
return false;
}
public function getStateFromStatus($status) {
$collection = Mage::getResourceModel('sales/order_status_collection')
->addStatusFilter($status)
->joinStates();
// Magento will actually prevent you from ever being able to have multiple statuses with the same code, but just to be safe...
if ($collection->getSize() > 1) {
Mage::throwException("Multiple statuses found with code " . $status . ". Ensure only one is present.");
}
$statusModel = $collection->getFirstItem();
return $statusModel->getState();
}
}

php and high latency

I have a php file that previously used to write xml data with tags. Now I'm trying to make it a little remoteobject based. So instead of writing xml I'm trying to return a class object that consists some big multidimensional array. The problem is it is causing a high latency. I'm not sure if it's my php file that is causing latency problem.
My php code :
class output{
public $grid;
public $week;
public $name;
var $_explicitType = "org.test.output";
}
class manager1{
function init($params,$arrayOut)
{
$action = $params[0];
switch ($action)
{
case "reload": return $this->Reload($arrayOut);break;
default:return $this->form($arrayOut);
}
}
private function Reload($arrayOut)
{
$this->getSlice();
$arrayOut->grid = $this->gridValue();
$arrayOut->week = 'no data';
return $arrayOut;
}
private function form($arrayOut)
{
$arrayOut->grid = $this->gridValue();
$arrayOut->week= $this->getAllWeek($this->ThisYear);
return $arrayOut;
}
}
AS-3 code calling php function:
private function init():void{
var _amf:RemoteObject = new RemoteObject();
var params:Array = new Array(); //parameters array
params.push("default");
var arrayOut:output = new output();//strongly typed class
_amf.destination = "dummyDestination";
_amf.endpoint = "http://insight2.ultralysis.com/Amfhp/Amfphp/"; //amfphp home directory
_amf.source = "manager1"; //the php class which will be called
_amf.addEventListener(ResultEvent.Result, handleResult);
_amf.init(params,arrayOut);
}
private function handleResult(event:ResultEvent):void
{
datagrid.dataProvider = event.result.grid;
}
And there is also a class named output in my application:
package org.test{
public class output
{
public var grid:Array;
public var week:Array;
}
}
I'm using this to pass value to flex remoteobject using amfphp.
Actually, it's fairly easy to figure out.
You can use the Network Monitor that is part of Flash Builder. It shows the Request Time and the Response Time, so you can get a pretty good idea if the issue is with the PHP side or the Flex side. You can also see the size of the response.
Be aware that Remote Objects mixed with Multidimentional arrays can be larger than you think, but again the Network Monitor will help you figure out that.

Issues getting my profile picture in a Flash application

I have a PHP script that returns to me my (and my friends) profile pictures, using the following:
http://graph.facebook.com/".$ID."/picture?type=large
where $ID is the ID retrieved using the PHP API. I then use the following for loading the images in my app:
public function LoadProfile()
{
loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onUrlLoaded);
loader.load(new URLRequest(ImageURL));
//ImageURL is the URL provided by the PHP Script
// which is the 'http://graph.facebook.com/XXXX/picture?type=large'
}
private function onUrlLoaded(event:Event)
{
loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onUrlLoaded);
var path:String = LoaderInfo(event.target).url;
loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onReallyComplete);
var lc:LoaderContext = new LoaderContext(true);
lc.checkPolicyFile = true;
loader.load(new URLRequest(path), lc);
}
private function onReallyComplete(event:Event)
{
loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onReallyComplete);
}
This works for ALL of my friends, but does NOT work for me for some reason. I get the following general address for the image of my friends:
http://profile.ak.fbcdn.net/hprofile-ak-snc4/370825_524761447_653077984_n.jpg
But for me I just get
http://profile.ak.fbcdn.net
which is some random person ... NOT me ...
I've verified repeatedly that the ID being sent back from the PHP is in-fact my ID, and I've copy/pasted the address traced BEFORE the loading function into a browser and I get my correct profile picture, but somewhere in there it's bugging out for my ID in the load and only my ID in the load (I should rephrase it to say it bugs out for WHATEVER user is logged in to Facebook, not just me).
Any ideas? Or anyone know of an alternative way to get MY profile picture?
public function loadProfile():void
{
loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loader_completeHandler);
loader.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, loader_securityErrorHandler);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, loader_ioErrorHandler);
loader.load(new URLRequest(_imageURL));
}
private function loader_securityErrorHandler(event:SecurityErrorEvent):void
{
trace(event.toString());
}
private function loader_ioErrorHandler(event:IOErrorEvent):void
{
trace(event.toString());
}
private function loader_completeHandler(event:Event):void
{
loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, loader_completeHandler);
loader.contentLoaderInfo.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, loader_securityErrorHandler);
loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, loader_ioErrorHandler);
addChild(loader);
}

Best way to allow plugins for a PHP application

I am starting a new web application in PHP and this time around I want to create something that people can extend by using a plugin interface.
How does one go about writing 'hooks' into their code so that plugins can attach to specific events?
You could use an Observer pattern. A simple functional way to accomplish this:
<?php
/** Plugin system **/
$listeners = array();
/* Create an entry point for plugins */
function hook() {
global $listeners;
$num_args = func_num_args();
$args = func_get_args();
if($num_args < 2)
trigger_error("Insufficient arguments", E_USER_ERROR);
// Hook name should always be first argument
$hook_name = array_shift($args);
if(!isset($listeners[$hook_name]))
return; // No plugins have registered this hook
foreach($listeners[$hook_name] as $func) {
$args = $func($args);
}
return $args;
}
/* Attach a function to a hook */
function add_listener($hook, $function_name) {
global $listeners;
$listeners[$hook][] = $function_name;
}
/////////////////////////
/** Sample Plugin **/
add_listener('a_b', 'my_plugin_func1');
add_listener('str', 'my_plugin_func2');
function my_plugin_func1($args) {
return array(4, 5);
}
function my_plugin_func2($args) {
return str_replace('sample', 'CRAZY', $args[0]);
}
/////////////////////////
/** Sample Application **/
$a = 1;
$b = 2;
list($a, $b) = hook('a_b', $a, $b);
$str = "This is my sample application\n";
$str .= "$a + $b = ".($a+$b)."\n";
$str .= "$a * $b = ".($a*$b)."\n";
$str = hook('str', $str);
echo $str;
?>
Output:
This is my CRAZY application
4 + 5 = 9
4 * 5 = 20
Notes:
For this example source code, you must declare all your plugins before the actual source code that you want to be extendable. I've included an example of how to handle single or multiple values being passed to the plugin. The hardest part of this is writing the actual documentation which lists what arguments get passed to each hook.
This is just one method of accomplishing a plugin system in PHP. There are better alternatives, I suggest you check out the WordPress Documentation for more information.
So let's say you don't want the Observer pattern because it requires that you change your class methods to handle the task of listening, and want something generic. And let's say you don't want to use extends inheritance because you may already be inheriting in your class from some other class. Wouldn't it be great to have a generic way to make any class pluggable without much effort? Here's how:
<?php
////////////////////
// PART 1
////////////////////
class Plugin {
private $_RefObject;
private $_Class = '';
public function __construct(&$RefObject) {
$this->_Class = get_class(&$RefObject);
$this->_RefObject = $RefObject;
}
public function __set($sProperty,$mixed) {
$sPlugin = $this->_Class . '_' . $sProperty . '_setEvent';
if (is_callable($sPlugin)) {
$mixed = call_user_func_array($sPlugin, $mixed);
}
$this->_RefObject->$sProperty = $mixed;
}
public function __get($sProperty) {
$asItems = (array) $this->_RefObject;
$mixed = $asItems[$sProperty];
$sPlugin = $this->_Class . '_' . $sProperty . '_getEvent';
if (is_callable($sPlugin)) {
$mixed = call_user_func_array($sPlugin, $mixed);
}
return $mixed;
}
public function __call($sMethod,$mixed) {
$sPlugin = $this->_Class . '_' . $sMethod . '_beforeEvent';
if (is_callable($sPlugin)) {
$mixed = call_user_func_array($sPlugin, $mixed);
}
if ($mixed != 'BLOCK_EVENT') {
call_user_func_array(array(&$this->_RefObject, $sMethod), $mixed);
$sPlugin = $this->_Class . '_' . $sMethod . '_afterEvent';
if (is_callable($sPlugin)) {
call_user_func_array($sPlugin, $mixed);
}
}
}
} //end class Plugin
class Pluggable extends Plugin {
} //end class Pluggable
////////////////////
// PART 2
////////////////////
class Dog {
public $Name = '';
public function bark(&$sHow) {
echo "$sHow<br />\n";
}
public function sayName() {
echo "<br />\nMy Name is: " . $this->Name . "<br />\n";
}
} //end class Dog
$Dog = new Dog();
////////////////////
// PART 3
////////////////////
$PDog = new Pluggable($Dog);
function Dog_bark_beforeEvent(&$mixed) {
$mixed = 'Woof'; // Override saying 'meow' with 'Woof'
//$mixed = 'BLOCK_EVENT'; // if you want to block the event
return $mixed;
}
function Dog_bark_afterEvent(&$mixed) {
echo $mixed; // show the override
}
function Dog_Name_setEvent(&$mixed) {
$mixed = 'Coco'; // override 'Fido' with 'Coco'
return $mixed;
}
function Dog_Name_getEvent(&$mixed) {
$mixed = 'Different'; // override 'Coco' with 'Different'
return $mixed;
}
////////////////////
// PART 4
////////////////////
$PDog->Name = 'Fido';
$PDog->Bark('meow');
$PDog->SayName();
echo 'My New Name is: ' . $PDog->Name;
In Part 1, that's what you might include with a require_once() call at the top of your PHP script. It loads the classes to make something pluggable.
In Part 2, that's where we load a class. Note I didn't have to do anything special to the class, which is significantly different than the Observer pattern.
In Part 3, that's where we switch our class around into being "pluggable" (that is, supports plugins that let us override class methods and properties). So, for instance, if you have a web app, you might have a plugin registry, and you could activate plugins here. Notice also the Dog_bark_beforeEvent() function. If I set $mixed = 'BLOCK_EVENT' before the return statement, it will block the dog from barking and would also block the Dog_bark_afterEvent because there wouldn't be any event.
In Part 4, that's the normal operation code, but notice that what you might think would run does not run like that at all. For instance, the dog does not announce it's name as 'Fido', but 'Coco'. The dog does not say 'meow', but 'Woof'. And when you want to look at the dog's name afterwards, you find it is 'Different' instead of 'Coco'. All those overrides were provided in Part 3.
So how does this work? Well, let's rule out eval() (which everyone says is "evil") and rule out that it's not an Observer pattern. So, the way it works is the sneaky empty class called Pluggable, which does not contain the methods and properties used by the Dog class. Thus, since that occurs, the magic methods will engage for us. That's why in parts 3 and 4 we mess with the object derived from the Pluggable class, not the Dog class itself. Instead, we let the Plugin class do the "touching" on the Dog object for us. (If that's some kind of design pattern I don't know about -- please let me know.)
The hook and listener method is the most commonly used, but there are other things you can do. Depending on the size of your app, and who your going to allow see the code (is this going to be a FOSS script, or something in house) will influence greatly how you want to allow plugins.
kdeloach has a nice example, but his implementation and hook function is a little unsafe. I would ask for you to give more information of the nature of php app your writing, And how you see plugins fitting in.
+1 to kdeloach from me.
Here is an approach I've used, it's an attempt to copy from Qt signals/slots mechanism, a kind of Observer pattern.
Objects can emit signals.
Every signal has an ID in the system - it's composed by sender's id + object name
Every signal can be binded to the receivers, which simply is a "callable"
You use a bus class to pass the signals to anybody interested in receiving them
When something happens, you "send" a signal.
Below is and example implementation
<?php
class SignalsHandler {
/**
* hash of senders/signals to slots
*
* #var array
*/
private static $connections = array();
/**
* current sender
*
* #var class|object
*/
private static $sender;
/**
* connects an object/signal with a slot
*
* #param class|object $sender
* #param string $signal
* #param callable $slot
*/
public static function connect($sender, $signal, $slot) {
if (is_object($sender)) {
self::$connections[spl_object_hash($sender)][$signal][] = $slot;
}
else {
self::$connections[md5($sender)][$signal][] = $slot;
}
}
/**
* sends a signal, so all connected slots are called
*
* #param class|object $sender
* #param string $signal
* #param array $params
*/
public static function signal($sender, $signal, $params = array()) {
self::$sender = $sender;
if (is_object($sender)) {
if ( ! isset(self::$connections[spl_object_hash($sender)][$signal])) {
return;
}
foreach (self::$connections[spl_object_hash($sender)][$signal] as $slot) {
call_user_func_array($slot, (array)$params);
}
}
else {
if ( ! isset(self::$connections[md5($sender)][$signal])) {
return;
}
foreach (self::$connections[md5($sender)][$signal] as $slot) {
call_user_func_array($slot, (array)$params);
}
}
self::$sender = null;
}
/**
* returns a current signal sender
*
* #return class|object
*/
public static function sender() {
return self::$sender;
}
}
class User {
public function login() {
/**
* try to login
*/
if ( ! $logged ) {
SignalsHandler::signal(this, 'loginFailed', 'login failed - username not valid' );
}
}
}
class App {
public static function onFailedLogin($message) {
print $message;
}
}
$user = new User();
SignalsHandler::connect($user, 'loginFailed', array($Log, 'writeLog'));
SignalsHandler::connect($user, 'loginFailed', array('App', 'onFailedLogin'));
$user->login();
?>
I believe the easiest way would be to follow Jeff's own advice and have a look around the existing code. Try looking at WordPress, Drupal, Joomla, and other well-known PHP-based CMS to see how their API hooks look and feel. This way you can even get ideas you may have not thought of previously to make things a little more robust.
A more direct answer would be to write general files that they would "include_once" into their file that would provide the usability they would need. This would be broken up into categories and NOT provided in one MASSIVE "hooks.php" file. Be careful though, because what ends up happening is that files that they include end up having more and more dependencies and functionality improves. Try to keep API dependencies low. I.E fewer files for them to include.
There's a neat project called Stickleback by Matt Zandstra at Yahoo that handles much of the work for handling plugins in PHP.
It enforces the interface of a plugin class, supports a command line interface and isn't too hard to get up and running - especially if you read the cover story about it in the PHP architect magazine.
Good advice is to look how other projects have done it. Many call for having plugins installed and their "name" registered for services (like wordpress does) so you have "points" in your code where you call a function that identifies registered listeners and executes them. A standard OO design patter is the Observer Pattern, which would be a good option to implement in a truly object oriented PHP system.
The Zend Framework makes use of many hooking methods, and is very nicely architected. That would be a good system to look at.
I am surprised that most of the answers here seem to be geared about plugins that are local to the web application, ie, plugins that run on the local web server.
What about if you wanted the plugins to run on a different - remote - server? The best way to do this would be to provide a form that allows you to define different URLs that would be called when particular events occur in your application.
Different events would send different information based on the event that just occurred.
This way, you would just perform a cURL call to the URL that has been provided to your application (eg over https) where remote servers can perform tasks based on information that has been sent by your application.
This provides two benefits:
You don't have to host any code on your local server (security)
The code can be on remote servers (extensibility) in different languages other then PHP (portability)

Categories