PHP Braintree Gateway API - php

Be patient with me, I am trying to create a Braintree Gateway for my wordpress booking system with no knowledge of php. i have downloaded the php library files from Braintree and ive implemented the area for api connection and creating a transaction using the following code below. This code was taken and tweaked from another gateway! Is this a good method to use? Would this work?
My Code
$config = new Braintree\Configuration();
$config->environment($api_keys_merchant_id);
$config->merchantId(trim($api_keys_merchant_id));
$config->publicKey(trim($api_keys_public_key));
$config->privateKey(trim($api_keys_private_key));
$gateway = new Braintree\Gateway($config);
// Create transaction
$result = $gateway->transaction()->sale([
'amount' => $price,
'paymentMethodNonce' => 'nonceFromTheClient',
'options' => [ 'submitForSettlement' => true ]]);
if ($result->success) {
print_r("success!: " . $result->transaction->id);
} else if ($result->transaction) {
print_r("Error processing transaction:");
print_r("\n code: " . $result->transaction->processorResponseCode);
print_r("\n text: " . $result->transaction->processorResponseText);
} else {
print_r("Validation errors: \n");
print_r($result->errors->deepAll());
} ```

Personally, I do not understand what the problem is, so please state it, if any. In terms of adjustments, from the code sample attached, I would say:
don't reference unknown variables or share context about them (eg: $parsedCredentials is initialised but not used; also what is $request?)
use "use" statements at the top of the file instead of using the FQCN; it makes it easier to understand what the dependencies are and what the code does.

$gateway = new Braintree_Gateway([
'environment' => $api_keys_merchant_id,
'merchantId' => trim($api_keys_merchant_id),
'publicKey' => 'use_your_public_key',
'privateKey' => 'use_your_private_key'
]);
$result = $gateway->transaction()->sale([
'amount' => $price,
'paymentMethodNonce' => 'nonceFromTheClient',
'options' => [ 'submitForSettlement' => true ]]);
if ($result->success) {
print_r("success!: " . $result->transaction->id);
} else if ($result->transaction) {
print_r("Error processing transaction:");
print_r("\n code: " . $result->transaction->processorResponseCode);
print_r("\n text: " . $result->transaction->processorResponseText);
} else {
print_r("Validation errors: \n");
print_r($result->errors->deepAll());
}

Related

Uploaded video status via Facebook PHP Business SDK for advertisements

I'm trying to create a ad via the Facebook Business SDK. Everything works well until I'm trying to create a AdCreativeVideoData. Code:
protected function createAdVideoCreative($thumbnail_url, $video_id, $name){
$video_data = new AdCreativeVideoData();
$video_data->setData(array(
AdCreativeVideoDataFields::IMAGE_URL => $thumbnail_url,
AdCreativeVideoDataFields::VIDEO_ID => $video_id,
AdCreativeVideoDataFields::CALL_TO_ACTION => array(
'type' => AdCreativeCallToActionTypeValues::LIKE_PAGE,
'value' => array(
'page' => FbAds::PAGE_ID,
),
),
));
$object_story_spec = new AdCreativeObjectStorySpec();
$object_story_spec->setData(array(
AdCreativeObjectStorySpecFields::PAGE_ID => FbAds::PAGE_ID,
AdCreativeObjectStorySpecFields::VIDEO_DATA => $video_data,
));
$creative = new AdCreative(null, FbAds::AD_ACCOUNT_ID);
$creative->setData(array(
AdCreativeFields::NAME => $name,
AdCreativeFields::OBJECT_STORY_SPEC => $object_story_spec,
));
try {
$creative->create();
return $creative;
} catch (Exception $e) {
print("Create Ad Video Creative Exception: " . $e->getMessage() . " (" . $e->getCode() . ")");
exit;
}
}
The above method is called when the selected video is uploaded to Facebook via the following method:
protected function createAdVideo($video_path){
$video = new Advideo(null, FbAds::AD_ACCOUNT_ID);
$video->{AdVideoFields::SOURCE} = $video_path;
try {
$video->create();
return $video->{AdVideoFields::ID};
} catch (Exception $e) {
print("Create Ad Video Exception: " . $e->getMessage() . " (" . $e->getCode() . ")");
exit;
}
}
The problem is that when I'm trying to create the AdCreativeVideoData, the following error is thrown:
[message] => Invalid parameter
[type] => OAuthException
[code] => 100
[error_subcode] => 1885252
[is_transient] =>
[error_user_title] => Video not ready for use in an ad
[error_user_msg] => The video is still being processed. Please wait for the video to finish processing before using it in an ad.
[fbtrace_id] => AwW0d9+Piz1
As you can see, the video is not yet processed. My question is: how can I check the status of the video? Is there a endpoint available somewhere which I can ping to check the status? The documentation states that I can check the status, but the AdVideo object in the createAdVideo() method doesn't have a status field:
I'm at a loss here so I hope someone can shed a light on this problem. Thanks in advance!
AdVideo does not have a status field since then, but Video does: https://developers.facebook.com/docs/graph-api/reference/video
Internally it's the same id, so you can request https://graph.facebook.com/v4.0/{video-id}?fields=id,status which will return the status of the uploaded (Ad)Video.
I'll assume it is because the video is not uploaded at all.
Instead of using "source" try using "file_url". You may also want to add a parameter "title" so it will not be named untitled video- but it is not required.
And try using the SDK smarter like so:
$myVideoUpload = (new AdAccount("act_123456676"))-
>createAdVideo(
array() //fields
array( //params
"file_url"=>"http://whatever.com",
"title"=>"my title"
)
);
if this works, it'll return a json_encodes string with id=video_id.
If you want to be able to retrieve errors- if any- and a general method for all api calls, do use the graph api as such:
$fb = new Facebook(array(
"app_id"=>"blalaa",
"app_secret"=>"blaaaaa",
"default_graph_version"=>"v9.0"
));
$url = "/act_123456789/advideos";
$access_token = "my token";
$params =
array("file_url"=>"https://whatever.com","title"=>"some video");
try{
$response = $fb->post(
$url,
$params,
$access_token
)
$response = $response->getGraphNode();
} catch(FacebookResponseException $e) {
return "graph error:: " . $e->getMessage();
} catch(FacebookSDKException$e) {
return "sdk error:: " . $e->getMessage();
}
The last one can be applied to everything given that you have an access_token that has access to the specific edge that you are requesting thus only he URL needs to be changed accordingly along with the parameters.
Note:
While using the graph-api: Use POST if you want to change or create something, and GET if you only want to read.

if "message" is protected, how do I retrieve SOAP response called "message"?

I'm really stuck on this one. At the bottom of this post, I've attached the API documentation I'm working with. I want to catch the "message" when the response ("ask") isn't "Success". Seems reasonable enough, right? But when I do something like:
sfcSendError('Something went wrong. This is the message from the API: ' . $result->message);
I get a fatal error:
PHP Fatal error: Cannot access protected property SoapFault::$message
I found this seemingly related question on SO, so I tried changing "message" to "getMessage()" but (no surprise) that results in a different fatal error about calling an undefined function.
Here's my code snippet:
$client = mySoapClient(MODULE_SHIPPING_SFC_API_URL);
if (!$client) {
sfcSendError('could not make a SOAP connection. Halting until next CRON. [' . __FILE__ . ':' . __LINE__ . ']', 'SOAP Failure in cron job');
exit; //halt and wait for the next time cron runs
} else {
$HeaderRequest = array(
'customerId' => MODULE_SHIPPING_SFC_ACCOUNT,
'appToken' => MODULE_SHIPPING_SFC_TOKEN,
'appKey' => MODULE_SHIPPING_SFC_KEY
);
$reg = array(
'HeaderRequest' => $HeaderRequest,
'detailLevel' => 1,
'ordersCode' => $_query->fields['sfc_ordersCode']
);
$result = $client->getOrderByCode($reg);
if ($result->ask != "Success") {
sfcSendError('Something went wrong. This is the message from SFC: ' . $result->message, 'SOAP Failure in cron job');
$_query->MoveNext();
continue;
}
}
This is the referenced function:
function mySoapClient($url)
{
try {
$client = #new SoapClient($url, array(
'trace' => 1,
'exceptions' => 0,
'encoding' => 'UTF-8'
));
} catch (SoapFault $e) {
return 0;
}
return $client;
}
What am I doing wrong? Or is this a "bug" with the API where they really shouldn't be using "message" in their response?

braintree payment gateway integration with PHP step by step

I am new to braintree integration with PHP, i have searched in the internet i am not able to get correct one to implement in my website.
Can anyone help to to integration of braintree for my website with step by step including the sandbox creation .
Thanks in advance.
<?php
require_once 'lib/Braintree.php';
Braintree_Configuration::environment('sandbox'); /* this is sandbox or production */
Braintree_Configuration::merchantId('Your ID');
Braintree_Configuration::publicKey('Your Public Key');
Braintree_Configuration::privateKey('Your Private key');
$result = Braintree_Transaction::sale(array(
'amount' => $amount,
'orderId' => 'Your Order ID' , /* It should be unique */
'creditCard' => array(
'number' => '41111111111111111',
'expirationDate' => '07/16',
'cardholderName' => 'NAME',
)
));
if ($result->success) {
/* your success condition */
}else if ($result->transaction) {
$msg .= "Error processing transaction:<br>" ;
$msg .="\n code: " . $result->transaction->processorResponseCode ;
$msg .="\n text: " . $result->transaction->processorResponseText ;
echo $msg ;
}

Client server application in nuSOAP

I am new to the programming area and this is my first nusoap-0.9.5 client and server program. Although the the server looks correct the client keeps giving me this warning:
PHP Fatal error: SoapClient::SoapClient(): Invalid parameters in /var/www/client.php on line 5
PHP Fatal error: Uncaught SoapFault exception: [Client] SoapClient::SoapClient(): Invalid parameters in /var/www/client.php:5
Stack trace:
#0 /var/www/client.php(5): SoapClient->SoapClient('http://localhos...', true)
#1 {main}
thrown in /var/www/client.php on line 5
Anybody knows the reason? I am trying to find a solution over the net more than a week now and I can not understand what is wrong with my program why it is not working.
Client code:
Thanks again Davey, I have read all the tutorials that you recommend and I am still a bit confused but at least less confused than before. I have modified my code again, I hope it makes more sense now. So here it is:
<?php
include "conf_client.php";
require_once('nusoap.php');
$client = new soapclient('http://localhost:8048/server.php?wsdl',true);
class Data {
public $acro = acro;
public $note = note;
public $prio = prio;
public $date = date;
public function Delete() {
$create = array ($acro,
$date,
$note,
$prio);
return $create;
}// End of Function Delete
}// End of class Data
$data = new Data();
$delete = $data->Delete();
$response = $client->call('Lists.DeleteToDo',$delete);
var_dump($response);
?>
directory: {file:///var/www/server.php}
Any help is much appreciated.
'List.DeleteToDo'
Is the class: List and the Function: DeleteToDo on the side of the server that I am calling.
I manage to find more about my problem and I have solved it. I am posting my server code here maybe it can help also someone else.
As a beginner I have simplified the code as much as possible. I am not including to my answer the configuration file, but if anybody needs it please let me know and I will post it as well.
I would also like to say thank you to everyone who answered my query at this forum and help me understand my errors.
<?php
include "conf.php";
require_once('nusoap/lib/nusoap.php');
$server = new soap_server();
$server->configureWSDL('This is my First nuSoapServer', 'urn:nuSoapServer');
$server->wsdl->addComplexType('Data',
'compexType',
'struct',
'all',
'',
array('id' => array('name' => 'id', 'type' => 'xsd:int'),
'acro' => array('name' => 'acro', 'type' => 'xsd:string'),
'time' => array('name' => 'time', 'type' => 'xsd:string'),
'date' => array('name' => 'date', 'type' => 'xsd:string'),
'note' => array('name' => 'note', 'type' => 'xsd:string'),
'prio' => array('name' => 'prio', 'type' => 'xsd:int'),
'data' => array('name' => 'data', 'type' => 'xsd:string')
)
);
$server->wsdl->addComplexType(
'DataArray', // Name
'complexType', // Type Class
'array', // PHP Type
'', // Compositor
'SOAP-ENC:Array', // Restricted Base
array(), // Elements
array( // Atributes
array('ref' => 'SOAP-ENC:arrayType',
'wsdl:arrayType' => 'tns:Data[]')
),
'tns:Data'
);
$server->register('GetTodoList', // method name
array('acro' => 'xsd:string'), // input parameters
array('DataResult' => 'tns:DataArray'), // output parameters
'urn:nuSoapServer', // namespace($namespace)
'urn:nuSoapServer#GetTodoList', // soap action
'rpc', // style
'encoded', // use
'Return Get to do list'); // documentation
function GetMyConnection() {
global $InputArray;
$dbase_link = mysql_connect($InputArray['host'],$InputArray['mysql_user'],$InputArray['mysql_password']);
//check if connected
if (!$dbase_link) {
die("Can not connect: " . mysql_error());
}
//return $this->myconn;
//http://se1.php.net/manual/en/function.mysql-create-db.php
$dbase_select = mysql_select_db($InputArray['mysql_dbase']);
if (empty($dbase_select)) {
$sql = "CREATE DATABASE IF NOT EXISTS ".$InputArray['mysql_dbase']."\n";
if (mysql_query($sql)) {
echo "Database: " . $InputArray['mysql_dbase'] . " was created succesfully\n";
}
else {
echo "Error creating database: " . mysql_error() . "\n";
}
}
$dbase_select = mysql_select_db($InputArray['mysql_dbase']);
$sql = "CREATE TABLE IF NOT EXISTS ".$InputArray['mysql_dbase_table']." (
`id` int(11) NOT NULL AUTO_INCREMENT,
`acro` varchar(25) NOT NULL,
`time` varchar(25) NOT NULL,
`date` varchar(25) NOT NULL,
`note` varchar(1024) NOT NULL,
`prio` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1";
$create = mysql_query($sql);
if (!$create) {
echo "Error creating table: " . mysql_error() . "\n";
}
}// End of Function GetMyConnection
function closeConnection() {
$terminate = mysql_close();
if ($terminate) {
echo "Connection terminated\n";
}
else {
echo "Error terminating connection: " . mysql_error() . "\n";
}
}//End of function closeConnection
// create the function
function GetTodoList($acro) {
global $InputArray;
GetMyConnection();
if (!$acro) {
return new soap_fault('Client', '', 'No data received!');
}
else {
$dbase_select = mysql_select_db($InputArray['mysql_dbase']);
$get = mysql_query("SELECT * FROM " . $InputArray['mysql_dbase_table'] . " WHERE `acro` = '" . $acro . "'");
if($get === FALSE) {
echo "Could not retrieve data from: " . $InputArray['mysql_dbase_table'] . " due to: " . mysql_error() . "\n";
}
else {
while($total = mysql_fetch_array($get)) {
$Data[] = array('id' => $total['id'],
'acro' => $total['acro'],
'time' => $total['time'],
'date' => $total['date'],
'note' => $total['note'],
'prio' => $total['prio']);
}
}
}
return $Data;
closeConnection();
}
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
exit();
?>
Your URL for the SOAP is trying to access a local file path rather than a URL
If you open the URL you've specified in a browser you should get back a (possibly large) chunk of XML. I can almost guarantee that you would get nothing apart from a 404 error
For the SOAP connection you have to use the URL specified by the webserver rather than a local file path (unless you replace http:// with file:/// - that may work).
If your webserver exposes a URL (e.g., http://localmachine) and the WSDL is hosted in a subfolder (e.g., soapstuff) then the URL you would need to enter into the $client=new soapclient line would be something like http://localmachine/soapstuff?wsdl

Class not found (using lastfm api) Laravel 4

I am trying to print out the album information for a certain artist and album using the last.fm api. I have used dump-autoload for the api library (so the classes should be available). In one of my controllers, LastFMController.php, I have the following:
public function some_function() {
$authVars['apiKey'] = '************************';
$auth = new lastfmApiAuth('setsession', $authVars);
$artistName= "Coldplay";
$albumName = "Mylo Xyloto";
$album = Album::getInfo($artistName, $albumName);
echo '<div>';
echo 'Number of Plays: ' . $album->getPlayCount() . ' time(s)<br>';
echo 'Cover: <img src="' . $album->getImage(4) . '"><br>';
echo 'Album URL: ' . $album->getUrl() . '<br>';
echo '</div>';
}
I have a route that runs this code. When I run this, I get the following error:
Class 'Album' not found
Any idea what I'm doing wrong? Thank you.
You you are using this package: https://github.com/fxb/php-last.fm-api
You might have forgotten to autoload api classes:
require __DIR__ . "/src/lastfm.api.php";
Or you can add it to composer.json, as an example:
"autoload": {
"files": [
"/var/www/yourproject/libraries/lastfm.api/src"
],
},
And execute:
composer dump-autoload
EDIT:
You are using one package and the example from another one. There is no Album class in the package you are using, here is a full example of it:
<?php
// Include the API
require '../../lastfmapi/lastfmapi.php';
// Get the session auth data
$file = fopen('../auth.txt', 'r');
// Put the auth data into an array
$authVars = array(
'apiKey' => trim(fgets($file)),
'secret' => trim(fgets($file)),
'username' => trim(fgets($file)),
'sessionKey' => trim(fgets($file)),
'subscriber' => trim(fgets($file))
);
$config = array(
'enabled' => true,
'path' => '../../lastfmapi/',
'cache_length' => 1800
);
// Pass the array to the auth class to eturn a valid auth
$auth = new lastfmApiAuth('setsession', $authVars);
// Call for the album package class with auth data
$apiClass = new lastfmApi();
$albumClass = $apiClass->getPackage($auth, 'album', $config);
// Setup the variables
$methodVars = array(
'artist' => 'Green day',
'album' => 'Dookie'
);
if ( $album = $albumClass->getInfo($methodVars) ) {
// Success
echo '<b>Data Returned</b>';
echo '<pre>';
print_r($album);
echo '</pre>';
}
else {
// Error
die('<b>Error '.$albumClass->error['code'].' - </b><i>'.$albumClass->error['desc'].'</i>');
}
?>

Categories