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?
Related
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.
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 am integrating warehouse management system (which is based on PHP) with PrestaShop1.6 and I am using PrestaShop Web Service for integration.
I have to make new products (which are created in warehouse management system) appear on PrestaShop 1.6 online store. Warehouse management system asks PrestaShop WebService to create new product on PrestaShop online store.
I have written this function showed below. It works good at my localhost, but on test server it receives HTTP status 503 after trying to update stock availability. All WebService methods (GET, PUT, DELETE, etc) are enabled on all WebService entities. I don't know how to debug this problem, can you help me?
By the way, I used this code as example: https://github.com/xabikip/PrestaShopWebService/blob/master/examples/createProduct.php
private function saveProduct($update, $webService, $root_path, $n_id, $n_id_category_default, $n_id_category, $n_price, $n_active, $n_avail4order, $n_show_price, $n_l_id, $n_name, $n_desc, $n_desc_short, $n_link_rewrite, $n_meta_title, $n_meta_description, $n_meta_keywords, $n_available_now, $n_available_later, $idtaglist, $cod, $quantity) {
$webService = new PrestaShopWebservice($this->ps_shop_path, $this->ps_ws_auth_key, $this->ps_ws_debug);
$xml = $webService->get(array('url' => $root_path . '/api/products?schema=blank'));
$resources = $xml->children()->children();
/*
many values of attributes of XML object $resources are assigned here, instead of this comment
*/
$id = "";
try {
$opt = array('resource' => 'products');
if(!$update){
$opt['postXml'] = $xml -> asXML();
$xml = $webService -> add($opt);
$id = $xml->product->id;
}
else{
$opt['putXml'] = $xml -> asXML();
$opt['id'] = $n_id;
$xml = $webService -> edit($opt);
$id = $n_id;
}
}
catch (PrestaShopWebserviceException $ex) {
echo '<b>Error : '.$ex->getMessage().'</b>';
}
$resources = $xml->children()->children();
$stock_available_id = $resources->associations->stock_availables->stock_available[0]->id;
/*
Here we get the sotck available with were product id
*/
try
{
$opt = array('resource' => 'stock_availables');
$opt['id'] = $stock_available_id;
$xml = $webService->get($opt);
}
catch (PrestaShopWebserviceException $e)
{
$trace = $e->getTrace();
if ($trace[0]['args'][0] == 404) die('1:Bad ID');
else if ($trace[0]['args'][0] == 401) die('1:Bad auth key');
else die('1:Other error '.$e->getMessage());
}
$resources = $xml->children()->children();
$resources->quantity = $quantity;
/*
There we call to save our stock quantity.
*/
try
{
$opt = array('resource' => 'stock_availables');
$opt['putXml'] = $xml->asXML();
$opt['id'] = $stock_available_id;
$xml = $webService->edit($opt);
echo "Successfully updated.";
}
catch (PrestaShopWebserviceException $e)
{
$trace = $e->getTrace();
if ($trace[0]['args'][0] == 404) die('2:Bad ID');
else if ($trace[0]['args'][0] == 401) die('2:Bad auth key');
else echo('Other error: '.$e->getMessage()); // function echoes this PrestaShopWebServiceException: "Other error: This call to PrestaShop Web Services returned an unexpected HTTP status of:503"
}
}
PUT request are closed by default in most of hosting. Did you check this with your hosting manager??
Anyway, you must activate Prestashop DEBUG MODE in order to know the exact reason of your error (after you solve this of course).
Good luck.
I am using SOAP to call a web servicefrom a Linux Centos 6 server and a php client. In this week I have been getting could not connect to host error from soapCall method. My code is as below and I have not changed it at all for some months but recently it gets this error most of the time. I have read most answers to related questions here but my problem have not been solved.
$wsdl="http://x.x.x.x:x/gw/services/Service?wsdl";
//Set key as HTTP Header
$aHTTP['http']['header'] = "key:" .$key ."\r\n";
$context = stream_context_create($aHTTP);
try
{
$client = new SoapClient($wsdl,array("soap_version" => SOAP_1_2,'trace' => 1,"stream_context" => $context));
}
catch(Exception $e)
{
return "something";
}
//I make $parametrs
try
{
$res = $client->__soapCall("send",array($parametrs));
}
catch(Exception $e)
{
print_r($e->getMessage()); //Most of the time it prints could not connect to host
}
I changed SOAP from _1_1 to _1_2 but nothing changed.
This is how I call SOAP webservice, please note Service?wsdl should be Service.wsdl
Example
//Initialize values
$wsdl = "Service.wsdl";
$url = "http://x.x.x.x:x/gw/services/";
$username = "********"; //add username
$password = "********"; //add password
$client = new SoapClient("$url".$wsdl);
$params = array(
"username"=>$username,
"password"=>$password
);
$response = $client->UserLogIn($params); //UserLogIn is the function name
var_dump($response); // to see webservice response
Everybody.
Have a question about ebay trading api.
I'm trying to get all orders for authorized user.
I'm developing my web application using PHP.
So, I use this sdk:
https://github.com/davidtsadler/ebay-sdk-php
I'm getting list using getOrders method:
http://developer.ebay.com/devzone/xml/docs/Reference/ebay/GetOrders.html
Here is my code example:
public function getOrders(){
$service = $this->getTradingService();
$args = array(
//"OrderStatus" => "Completed",
"OrderStatus" => "All",
"SortingOrder" => "Ascending",
"OrderRole" => "Seller",
//"CreateTimeFrom" => new \DateTime('2015-01-01'),
"CreateTimeFrom" => new \DateTime('2000-01-01'),
"CreateTimeTo" => new \DateTime(),
);
$request = new Types\GetOrdersRequestType($args);
$request->RequesterCredentials = new Types\CustomSecurityHeaderType();
$request->RequesterCredentials->eBayAuthToken = $this->userToken;
$request->IncludeFinalValueFee = true;
$request->Pagination = new Types\PaginationType();
$request->Pagination->EntriesPerPage = 100;
$pageNum = 1;
$orders = [];
do {
$request->Pagination->PageNumber = $pageNum;
$response = $service->getOrders($request);
if (isset($response->Errors)) {
$message = '';
foreach ($response->Errors as $error) {
$message .= $error->ShortMessage;
}
throw new Exception($message);
}
if ($response->Ack !== 'Failure' && isset($response->OrderArray)) {
foreach ($response->OrderArray->Order as $order) {
$orders[] = $order->toArray();
}
}
$pageNum += 1;
}
while(isset($response->OrderArray) && $pageNum <= $response->PaginationResult->TotalNumberOfPages);
return $orders;
}
It works fine for me except one issue.
I can't get buyer email.
$orders[0]['ShippingAddress']['ExternalAddressID']
Is empty.
$orders[0]['TransactionArray']['Transaction'][0]['Buyer']['Email']
Is string value "Invalid Request"
If somebody knows way to get buyers emails.
Or just get informatioan about many users in one request(so I could simply merge them).
UPDATE:
Also tried to do the same without SDK.
public function getOrders2(){
$xml = '<?xml version="1.0" encoding="utf-8"?>
<GetOrdersRequest xmlns="urn:ebay:apis:eBLBaseComponents">
<CreateTimeFrom>2000-01-01T00:00:00</CreateTimeFrom>
<CreateTimeTo>2015-10-22T00:00:00</CreateTimeTo>
<IncludeFinalValueFee>true</IncludeFinalValueFee>
<OrderRole>Seller</OrderRole>
<OrderStatus>All</OrderStatus>
<DetailLevel>ReturnAll</DetailLevel>
<RequesterCredentials>
<eBayAuthToken>' . $this->userToken . '</eBayAuthToken>
</RequesterCredentials>
</GetOrdersRequest>';
$url = 'https://api.ebay.com/ws/api.dll';
$results = $this->sendPostRequest($xml,$url);
$results = new SimpleXMLElement($results);
return $results;
}
Get the same issue.
Thanks
Need change SiteID to id User Registration.
$config = [
'apiVersion' => Services\TradingService::API_VERSION,
'siteId' => Constants\SiteIds::US,
'credentials' => [
'appId' => getenv('EBAY_APP_ID'),
'certId' => getenv('EBAY_CERT_ID'),
'devId' => getenv('EBAY_DEV_ID')
],
'sandbox' => false
];
If the order is too old then it will will result in Invalid Request ( Simply saying " This orders is XX days old and we wont provide email address for it )
Ebay withholds their user's email information 14 days after the order is placed.
If you are using their APIs to pulling order info after that you get:
Email = 'Invalild Request'
Example response ...
...
'TransactionArray': {'Transaction': [...
'Buyer': {'Email': 'Invalid Request',
'UserFirstName': None,
'UserLastName': None},
...
The thing to do is
Pull the data before that, and then
Do not update the order email data on subsequent data pulls.
I found this out the hard way. I don't recall reading about that in the API docs.