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 ;
}
Related
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());
}
I have integrate paypal with my Laravel application. I'm able to make payment successfully from Paypal, but after successful payment I'm not able to receive any type of response in my site.
My code is as below:
public function aCoolFunction(CreateDistrictRequest $request)
{
$data = $request->only('city_id', 'name', 'latitude', 'longitude');
$district = $this->districtRepository->create($data);
$payment = 'sandbox';
$values = [
'charest' => 'utf-8',
'lc' => 'US',
'cmd' => '_xclick',
'amount' => $product->price, // PRICE
'business' => 'test-facilitator#gmail.com', // PAYPAL EMAIL
'item_name' => $product->name, // NAME
'item_number' => $product->id, // ITEM ID
'currency_code' => 'USD',
'no_note' => '0',
'tax_rate' => 0, // 0- TO NOT ADD ANY FEES
'no_shipping' => 1, // NO ADDRESS
'rm' => '1',
'page_style' => 'paypal',
'custom' => '1', // ANY VALUES TO RETURN IT AFTER PAYMENT SUCCESS
'return' => url('payment-status'), // RETURN - MUST BE A VALID URL
'cancel_return' => url('payment-cancel'),
'notify_url' => url('payment-ipn') // IPN PAYPAL - CHECK IF IS PAID
];
$pay_url = "https://www.paypal.com/cgi-bin/webscr";
// CREATE $payment TO CHECK IF IS SANDBOX or LIVE - FROM CONFIG FILE FOR EXAMPLE
if ($payment == 'sandbox') :
$pay_url = "https://www.sandbox.paypal.com/cgi-bin/webscr";
endif;
return view('paypalpayment', ['pay_url' => $pay_url, 'values' => $values]);
}
public function paymentInfo(Request $request)
{
$myfile = fopen("paypalog.txt", "w") or die('Cannot open file: ' . $my_file);
$data = 'Transaction id = ' . $request;
fwrite($myfile, $data);
if ($request->tx)
{
if ($payment = Payment::where('transaction_id', $request->tx)->first())
{
$payment_id = $payment->id;
}
else
{
$payment = new Payment;
$payment->item_number = $request->item_number;
$payment->transaction_id = $request->tx;
$payment->currency_code = $request->cc;
$payment->payment_status = $request->st;
$payment->save();
$payment_id = $payment->id;
}
return 'Pyament has been done and your payment id is : ' . $payment_id;
}
else
{
return 'Payment has failed';
}
}
public function payment_success(Request $req)
{
$myfile = fopen("paypalog1.txt", "w") or die('Cannot open file: ' . $my_file);
$data = 'Transaction id = ' . $request->tx;
fwrite($myfile, $data);
}
from above code paymentinfo() is call in success or failure of payment from paypal. but here I'am not able to get any type of response from Paypal regarding payment.
This are my routes
Route::get('payment-status',array('as'=>'payment.status','uses'=>'PaymentController#paymentInfo'));
Route::get('payment',array('as'=>'payment','uses'=>'PaymentController#payment'));
Route::get('payment-cancel', function () {
return 'Payment has been canceled';
});
Route::get('payment-success' , 'PaymentController#payment_success');
Can anyone help me to solve this issue?
While dealing with PayPal you have to implement the IPN (Instant payment Notification) to get the status of the payment whether it is successful or failed.
For that you have to activate the IPN under the setting in your PayPal account and provide an url of your system to receive the IPN data, and that url must be of post type.
If I am not wrong, you have created this url for the same:
Route::get('payment-success' , 'PaymentController#payment_success');
but the issue is, it is of get type, so change it to 'post' and try again. If this url is not for the same purpose then create a url for the same.
P.S.: for testing purpose, PayPal provides an IPN simulator to test the same process, use that one it will be very helpful.
IPN simulator reference
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.
I'm struggling with a piece of code for more than a week.
I implemented Braintree, using the PHP SDK, in my Codeigniter app and I have this issue:
The user selects the product he wants, enters the shipping method then the Credit Card info;
The Credit Card is processed on the Braintree servers and returns a success or error flag;
If successful the order is added in the Database and a confirmation email is sent both to the merchant and the customer
Finally, the user is redirected to the success page or the error page if the transaction failed.
Everything works as expected in sandbox mode but when I go into production mode, the redirect fails, the page is redirected back to the order confirmation, even though the CC was charged and both emails sent.
Here is my controller:
function order_confirmation()
{
require_once('application/libraries/braintree/lib/Braintree.php');
Braintree_Configuration::environment('production');
Braintree_Configuration::merchantId('MY_MERCHANT_ID');
Braintree_Configuration::publicKey('MY_PUBLIC_KEY');
Braintree_Configuration::privateKey('MY_PRIVATE_KEY');
if ($this->input->post('checkout'))
{
$price = 24.99;
$quantity = 1;
if ($this->input->post('shipping') == 1)
$shipping_price = 0;
elseif ($this->input->post('shipping') == 2)
$shipping_price = 6.99;
$amount = $price * $quantity + $shipping_price;
//BrainTree payment process
$result = Braintree_Transaction::sale(array(
'amount' => $amount,
'creditCard' => array(
'number' => $this->input->post('credit_card_number'),
'expirationDate' => $this->input->post('expiration_month') . '/' . $this->input->post('expiration_year'),
'cvv' => $this->input->post('cvv')
),
'options' => [
'submitForSettlement' => True
]
));
if ($result->success)
{
// I left only the first and last name field to save up space
$first_name = $this->db->escape($this->session->userdata('first_name'));
$last_name = $this->db->escape($this->session->userdata('last_name'));
$date_created = $this->db->escape(time());
// Add the order
$this->shop_model->add_order($first_name, $last_name, $transaction_id, $date_created);
$order_id = $this->db->insert_id();
$product_id = $this->db->escape($this->input->post('product_id'));
// Add the order items
$this->shop_model->add_order_items($order_id, $product_id, $quantity, $price);
$data['site_name'] = $this->config->item('website_name');
$data['order'] = $this->shop_model->get_order($order_id);
$data['order_items'] = $this->shop_model->get_order_items($order_id);
$customer_email = $this->session->userdata('email');
// Send the email notification to the merchant
send_html_email('order_confirmation_merchant', $this->config->item('primary_email'), $this->config->item('website_name'), $this->config->item('primary_email'), 'shop', $data);
// Send the order confirmation to the customer
send_html_email('order_confirmation_customer', $this->config->item('primary_email'), $this->config->item('website_name'), $customer_email, 'shop', $data);
redirect(SHOP . '/checkout-success');
// header("Location: checkout-success");
// echo '<script language="JavaScript">document.location.href="' . base_url() . SHOP . '/checkout-success' . '"</script>' . "\n";
}
else
{
redirect(SHOP . '/checkout-error');
}
}
$this->template->set_template('no_sidebar');
$this->template->write('meta_description', 'Order confirmation');
$this->template->write('meta_keywords', 'Order confirmation');
$this->template->write('title', 'Order confirmation');
$this->template->write_view('header', 'frontend/header');
$this->template->write_view('section', 'frontend/shop/order_confirmation'/*, $data*/);
$this->template->write_view('footer', 'frontend/footer');
$this->template->render();
}
As you can see I tried serveral redirect methods (Codeigniter redirect(), native PHP, Javascript) with no success. As mentioned before, I do see the success page in sandbox mode and the error page if I enter a bogus CC, but no success page, only my order confirmation form, in production mode, even though the CC is charged, the order added in the database and the emails sent.
I would like to mention that the website has a SSL certificate and I tested using Mozilla Firefox, Google Chrome, Microsoft Edge. There are no JS errors, no PHP warnings.
Any answer would be greatly appreciated.
Thank you!
I am basically trying to use the PAY call of Adaptive Payments to programmatically and immediately send funds from my own paypal account to other accounts. According to the documentation, so long as I specify the senderEmail (my own paypal address, used to set up the Adaptive Payments), this should work verbatim.
However, when I make the call, I always get result "CREATED" instead of "COMPLETED". Created means the system still wants me to manually log into PayPal and approve the payments. I really need these payments to occur automatically on the spot. Any help would be appreciated.
Here is my request string:
currencyCode=USD&
returnUrl=http%3A%2F%2Fwww.website.com%2F&
actionType=PAY&
cancelUrl=http%3A%2F%2Fwww.website.com%2F&
receiverList.receiver%280%29.email=receiver%40gmail.com&
receiverList.receiver%280%29.amount=1.00&
requestEnvelope.senderEmail=me%40gmail.com&
clientDetails.deviceId=mydevice&
clientDetails.ipAddress=127.0.0.1&
clientDetails.applicationId=APP-ZZZZZZZZZZZZZ&
requestEnvelope.errorLanguage=en_US&
memo=memo&
feesPayer=EACHRECEIVER&
ipnNotificationUrl=http%3A%2F%2Fwww.website.com%2Fpay.php
And here is the response from PayPal:
[responseEnvelope.timestamp] => 2012-03-01T19:09:57.290-08:00
[responseEnvelope.ack] => Success
[responseEnvelope.correlationId] => 71efd416a2100
[responseEnvelope.build] => 2486531
[payKey] => AP-ZZZZZZZZZZZZZZZ
[paymentExecStatus] => CREATED
Forget everything I said earlier. The problem isn't an inconsistency between Sandbox and Live either, but rather a wrong parameter for 'senderEmail'.
Simply change:
requestEnvelope.senderEmail=me#gmail.com&
To:
senderEmail=me#gmail.com&
For example, the following returns a 'COMPLETED' implicit payment.
<?php
function AdaptiveCall($bodyparams, $method, $payKey) {
try
{
$body_data = http_build_query($bodyparams, "", chr(38));
$url = trim("https://svcs.sandbox.paypal.com/AdaptivePayments/".$method."");
$params = array("http" => array(
"method" => "POST",
"content" => $body_data,
"header" => "X-PAYPAL-SECURITY-USERID: xxxxxxxxx\r\n" .
"X-PAYPAL-SECURITY-SIGNATURE: xxxxxxxxxxx\r\n" .
"X-PAYPAL-SECURITY-PASSWORD: xxxxxxx\r\n" .
"X-PAYPAL-APPLICATION-ID: APP-80W284485P519543T\r\n" .
"X-PAYPAL-REQUEST-DATA-FORMAT: NV\r\n" .
"X-PAYPAL-RESPONSE-DATA-FORMAT: NV\r\n"
)
);
//create stream context
$ctx = stream_context_create($params);
//open the stream and send request
$fp = #fopen($url, "r", false, $ctx);
//get response
$response = stream_get_contents($fp);
//check to see if stream is open
if ($response === false) {
throw new Exception("php error message = " . "$php_errormsg");
}
//close the stream
fclose($fp);
//parse the ap key from the response
$keyArray = explode("&", $response);
foreach ($keyArray as $rVal){
list($qKey, $qVal) = explode ("=", $rVal);
$kArray[$qKey] = $qVal;
}
//print the response to screen for testing purposes
If ( $kArray["responseEnvelope.ack"] == "Success") {
echo "<strong>".$method ."</strong><br>";
foreach ($kArray as $key =>$value){
echo $key . ": " .$value . "<br/>";
}
// Return payKey
global $payKey;
if(!empty($kArray['payKey'])) { $payKey = $kArray['payKey']; return($payKey); }
}
else {
echo 'ERROR Code: ' . $kArray["error(0).errorId"] . " <br/>";
echo 'ERROR Message: ' . urldecode($kArray["error(0).message"]) . " <br/>";
}
}
catch(Exception $e) {
echo "Message: ||" .$e->getMessage()."||";
}
}
//Create Pay body
$bodyparams = array ( "requestEnvelope.errorLanguage" => "en_US",
'actionType' => 'PAY',
'currencyCode' => 'USD',
'receiverList.receiver(0).email' => 'another_account#domain.tld',
'receiverList.receiver(0).amount' => '1.00',
'senderEmail' => 'xxxxxxxxx',
'memo' => 'Test memo',
'ipnNotificationUrl' => 'http://xxxxxxxx',
'cancelUrl' => 'http://xxxxxxxxx',
'returnUrl' => 'http://xxxxxxxxxx'
);
// Call Pay API
AdaptiveCall($bodyparams, "Pay");
?>
Pay response:
responseEnvelope.timestamp: 2012-03-03T09%3A10%3A22.900-08%3A00
responseEnvelope.ack: Success
responseEnvelope.correlationId: 4bc5cfc4a7514
responseEnvelope.build: 2486531
payKey: AP-1XJ7636763429720C
paymentExecStatus: COMPLETED