I am working on PayPal with PHP.
I create Payout from this - http://paypal.github.io/PayPal-PHP-SDK/sample/doc/payouts/CreateSinglePayout.html
Exactly code is like this:
$payouts = new Payout();
$senderBatchHeader = new PayoutSenderBatchHeader();
$senderBatchHeader->setSenderBatchId(uniqid())
->setEmailSubject("You have a Payout!");
$senderItem = new PayoutItem();
$senderItem->setRecipientType('Email')
->setNote('Thanks for your patronage!')
->setReceiver('test#example.com')
->setSenderItemId("2014031400023")
->setAmount(new Currency('{
"value":"1.0",
"currency":"USD"
}'));
$payouts->setSenderBatchHeader($senderBatchHeader)
->addItem($senderItem);
$request = clone $payouts;
try {
$output = $payouts->createSynchronous(PaypalController::$_api_context);
} catch (Exception $ex) {
return 'Error: '. $ex->getMessage();
}
return 'Success Payout!';
But when I run this, it returns error - 'Got Http response code 403 when accessing https://api.sandbox.paypal.com/v1/payments/payouts?sync_mode=true.'
Why it happens, How can I solve this?
Thanks much to anyone help.
Related
I've created a REST API base on this tutorial - note that I am a newbie in php and REST...
Now, I am stuck when calling a POST request. The main return function is as follows:
// Requests from the same server don't have a HTTP_ORIGIN header
if (!array_key_exists('HTTP_ORIGIN', $_SERVER)) {
$_SERVER['HTTP_ORIGIN'] = $_SERVER['SERVER_NAME'];
}
try {
$API = new MyAPI($_REQUEST['request'], $_SERVER['HTTP_ORIGIN']);
$res = $API->processAPI();
echo $res; // contains my json as expected
return $res; // always empty string
} catch (Exception $e) {
echo "Exception: " . json_encode(Array('error' => $e->getMessage()));
}
EDIT
I've just tried something even simpler in the API caller method, namely following:
try {
$res = json_encode(Array('test' => "my message"));
// comment out one or the other to check output...
//echo $res;
return $res;
} catch (Exception $e) {
echo "Exception: " . json_encode(Array('error' => $e->getMessage()));
}
Result with echo is (the way I get responese is below... exact response is between # characters):
#{"test":"my message"}#
Result with return is
##
EDIT 2
Here is how I call the API from C#:
using (HttpClient client = new HttpClient()) {
JObject jo = new JObject();
jo.Add("usr", "username");
jo.Add("pwd", "password");
Uri url = new Uri(string.Format("{0}/{1}", RestUrl, "login"));
StringContent content = new StringContent(jo.ToString(), Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url, content);
bool isOk = response.StatusCode == System.Net.HttpStatusCode.OK;
// this is where I get the result from...
var res = response.Content.ReadAsStringAsync().Result;
}
I really don't understand this - could someone please explain in non-php expert terms??
I have a web application that send payment to the user when they reach some level
That's the class that handle a single payment:
public function pagaSingoloAction(Request $request, $id_richiesta)
{
$richiesta_pagamento = $this->getDoctrine()->getRepository("AppBundle:RichiestaPagamento")->find($id_richiesta);
if ($richiesta_pagamento)
{
$logger = $this->get('logger');
$em = $this->getDoctrine()->getManager();
$tassa = $this->get('application.settings')->ritornaImpostazioneDaNome("percentuale_tasse_pagamenti_richieste");
if (!$tassa)
$tassa = 0;
$totale_richiesta_aggiornato = $richiesta_pagamento->getTotale();
$totale_tassa_decurtata_network = 0;
if ($tassa != 0)
{
$totale_tassa_decurtata_network = (($tassa / 100) * $totale_richiesta_aggiornato);
$totale_richiesta_aggiornato = $totale_richiesta_aggiornato - $totale_tassa_decurtata_network;
}
$imp = new ImpostazioniApplicazione($this->getDoctrine());
$apiContext = new ApiContext(new OAuthTokenCredential(
$imp->getPaypalAppId(),
$imp->getPaypalAppSecret()
));
$apiContext->setConfig(array(
'mode' => $this->getParameter('paypal_mode'),
'log.LogEnabled' => true,
'log.FileName' => 'PayPal.log',
'log.LogLevel' => 'FINE'
));
$logger->info("SETTATA CONFIGURAZIONE API CONTEXT");
$payouts = new Payout();
$sender_batch_header = new PayoutSenderBatchHeader();
$sender_batch_header->setSenderBatchId(uniqid())
->setEmailSubject("New payment from request!");
$sender_item = new PayoutItem();
$sender_item->setRecipientType('EMAIL')
->setNote("Payment request n. " . $richiesta_pagamento->getId())
->setReceiver($richiesta_pagamento->getEmailPaypal())
->setSenderItemId(uniqid())
->setAmount(new Currency('{
"value" : "'. $totale_richiesta_aggiornato .'",
"currency" : "EUR"
}'));
$payouts->setSenderBatchHeader($sender_batch_header)
->addItem($sender_item);
$output = "";
try{
$output = $payouts->createSynchronous($apiContext, null);
$logger->error(var_export($output, true));
}catch (Exception $ex){
$logger->error($ex->getMessage());
}
$payout_item = $output->getItems()[0];
if ($payout_item->getTransactionStatus() == "SUCCESS")
{
//ITS ALL OK
}
return $this->render('pagamento_singolo_richiesta/singolo_pagamento_dettagli.html.twig', array(
'pagamento' => $pagamento_singolo,
));
}
else{
return $this->render('pagamento_singolo_richiesta/pagamento_errore.html.twig');
}
}
When i try to make payment:
try{
$output = $payouts->createSynchronous($apiContext, null);
$logger->error(var_export($output, true));
}catch (Exception $ex){
$logger->error($ex->getMessage());
}
I always get 403 AUTORIZHATION but a month ago all works great!
So i can't understand what's the problem... I have checked with php sample code on paypal documentation and it's all ok like my code.
I use symfony framework in my application.
I get payment without any problem but i can't send money.
I have also tried to upgrade all Bundles and symfony itself but nothink has changed, same problem.
That's the paypal error log:
[25-10-2016 11:21:08] PayPal\Core\PayPalHttpConnection : INFO: Response Status : 403
[25-10-2016 11:21:08] PayPal\Core\PayPalHttpConnection : ERROR: Got Http response code 403 when accessing https://api.paypal.com/v1/payments/payouts?sync_mode=true. {"name":"AUTHORIZATION_ERROR","message":"Authorization error occurred","debug_id":"3676075eac96e","information_link":"https://developer.paypal.com/docs/api/payments.payouts-batch/#errors"}
The 403-response from PayPal API is always if there is something wrong with your credentials. Have you check if the desired PayPal-account is still active? And your client ID en secret ID are still legit?
I am trying to update database.
I have set up the webhook in stripe in test mode and send a "invoice.payment_succeeded" test webhook to file.but it shows response "none" in stripe output.
What have i done wrong, here is the webhook file, please someone help me, i am very stuck at this. any help will be appreciate...
<?php
include '../admin/include/functions.php';
require_once('Stripe/lib/Stripe.php');
require_once 'stripe_secret.php';
// Retrieve the request's body and parse it as JSON
$input = #file_get_contents("php://input");
$event_json = json_decode($input);
$event_id = $event_json->id;
if(isset($event_json->id)) {
try {
Stripe::setApiKey($stripe['secretkey']);
$event = Stripe_Event::retrieve($event_id);
var_dump($event);
$invoice = $event->data->object;
if($event->type == 'invoice.payment_succeeded') {
$customer = Stripe_Customer::retrieve($invoice->customer);
$email = $customer->email;
$customerid = $customer->id;
/*$amount = $invoice->amount / 100;*/
$expiry = $invoice->period->end;
$expiredate = date('Y-d-m', $expiry);
$userup = $obj->run_query("UPDATE users SET Expiry_Date = '$expiredate' WHERE user_stripe_id = '$customerid' ");
if ($userup) {
echo "User Date extended";
}
// send a invoice notice email here
}
if($event->type == 'invoice.payment_failed') {
$obj->run_query("UPDATE users SET Status = '0' WHERE user_stripe_id = '$customerid' ");
echo "User membership expired";
}
}
catch(Stripe_CardError $e) {
}
catch (Stripe_InvalidRequestError $e) {
// Invalid parameters were supplied to Stripe's API
} catch (Stripe_AuthenticationError $e) {
// Authentication with Stripe's API failed
// (maybe you changed API keys recently)
} catch (Stripe_ApiConnectionError $e) {
// Network communication with Stripe failed
} catch (Stripe_Error $e) {
// Display a very generic error to the user, and maybe send
// yourself an email
} catch (Exception $e) {
// Something else happened, completely unrelated to Stripe
}
}
http_response_code(200);
?>
The test webhooks from the test webhook button sends a webhook with the right format but all the values are null / zero / etc. Thus your line that does $obj->run_query("UPDATE users SET Expiry_Date = '$expiredate' WHERE user_stripe_id = '$customerid' "); will return a falsey result. This means you don't echo anything and just send back an empty 200 response.
I have implement the gcm to send notification to my application and its really working perfect.
I am getting notification on device but issue is that I am getting logs detail may be in notification message instead of only human readable message that I am pushing.
Here is my code that I am using to send notification:
$gcmApiKey = GOOGLE_API_KEY;
$pushApi = new PushAPI();
$sender = new \PHP_GCM\Sender($gcmApiKey);
$message = new \PHP_GCM\Message("1", $messsageVal);
try {
$multicastResult = $sender->sendMulti($message, $deviceRegistrationId, 2);
$results = $multicastResult->getResults();
for ($i = 0; $i < count($deviceRegistrationId); $i++) {
$regId = $deviceRegistrationId[$i];
$result = $results[$i];
$messageId = $result->getMessageId();
if ($messageId != null) {
$canonicalRegId = $result->getCanonicalRegistrationId();
if ($canonicalRegId != null) {
// same device has more than on registration id: update it
}
} else {
$error = $result->getErrorCodeName();
if ($error == \PHP_GCM\Constants::$ERROR_NOT_REGISTERED) {
$pushApi->clearDeviceByDeviceId($regId);
}
}
}
} catch (\InvalidArgumentException $e) {
// $deviceRegistrationId was null
} catch (PHP_GCM\InvalidRequestException $e) {
// server returned HTTP code other than 200 or 503
} catch (\Exception $e) {
// message could not be sent
}
Here is the link of whole API that I am using. PHP_GCM
I try to google it but I didn't get anything to rectify this.
Any help will be appreciated.
You have to parse your response same as you parse a webservice response and show only the msg.
Try getting the message from the received intent using:
String msg=intent.getExtras().getString("msg");
Then show the message as :
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.mipmap.app_icon)
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setContentTitle(context.getString(R.string.app_name))
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg);
am using the php api sdk found here: https://github.com/paypal/PayPal-PHP-SDK but am having trouble issuing a refund.
This is the code I am using:
// CAPTURE THE ORIGINAL AUTHORIZATION
try
{
$amount = new Amount();
$amount->setCurrency("USD");
$amount->setTotal($amount_authorized);
$capture = new Capture();
$capture->setId($authorization_id);
$capture->setAmount($amount);
$authorization = Authorization::get($transaction_id, $apiContext);
$capt = $authorization->capture($capture, $apiContext);
if ($capt->state == 'completed')
{
$capture_id = $capt->id;
}
}
catch (PayPal\Exception\PayPalConnectionException $e)
{
$response = json_decode($e->getData());
die('Error capturing funds: '.$response->message);
}
catch (Exception $e)
{
die('Error capturing funds: '.$e->getMessage());
}
// REFUND THE CAPTURE
try
{
$amount = new Amount();
$amount->setCurrency("USD");
$amount->setTotal($refund_amount);
$refund = new Refund();
$refund->setId($capture_id);
$refund->setAmount($amount);
$capture = Capture::get($capture_id, $apiContext);
$captureRefund = $capture->refund($refund, $apiContext);
if ($captureRefund->state == 'completed')
{
die('REFUNDED');
}
}
catch (PayPal\Exception\PayPalConnectionException $e)
{
$response = json_decode($e->getData());
die('There was an error refunding the funds: '.$response->message);
}
catch (Exception $e)
{
die('There was an error refunding the funds: '.$e->getMessage());
}
I get this error everytime: The requested resource ID was not found
I believe I am following the sample code on the developer site but I'll pulling my hair out. It's probably something pretty easy I hope.
Any ideas?
Thanks