I need some help to figure out paypal's API, all I'm trying to do is run a cc charge to my sandbox account, I've been looking at their documentation and code samples but I just can't find the right information right now, like where to add the sandbox endpoint. So, when I run the function below I get the following error:
string(213) "{"name":"MALFORMED_REQUEST","message":"Incoming JSON request does not map to API request","information_link":"https://developer.paypal.com/webapps/developer/docs/api/#MALFORMED_REQUEST","debug_id":"6eb15180f8d92"}"
This is the function I'm calling:
public static function ccPayment($paymentInfo, $credentials)
{
$apiContext = new \PayPal\Rest\ApiContext(
new \PayPal\Auth\OAuthTokenCredential(
$credentials['clientId'],
$credentials['secret']
)
);
$card = new CreditCard();
$card->setType("visa")
->setNumber("xxxxxxxxxxxxxxxx")
->setExpireMonth("11")
->setExpireYear("2019")
->setCvv2("012")
->setFirstName("Joe")
->setLastName("Shopper");
$fi = new FundingInstrument();
$fi->setCreditCard($card);
$payer = new Payer();
$payer->setPaymentMethod("credit_card")
->setFundingInstruments(array($fi));
$item1 = new Item();
$item1->setName('Ground Coffee 40 oz')
->setDescription('Ground Coffee 40 oz')
->setCurrency('USD')
->setQuantity(1)
->setTax(0.3)
->setPrice(7.50);
$itemList = new ItemList();
$itemList->setItems(array($item1));
$transaction = new Transaction();
$transaction->setAmount(489)
->setItemList($itemList)
->setDescription("Payment description")
->setInvoiceNumber(uniqid());
$payment = new Payment();
$payment->setIntent("sale")
->setPayer($payer)
->setTransactions(array($transaction));
// $request = clone $payment;
try
{
$payment->create($apiContext);
}
catch (Exception $ex)
{
dd($ex->getData());
}
dd($paymentInfo);
}
Been coding since the morning so I need another set of eyes right now because I just can't see what I'm doing wrong. I will appreciate any help.
PS. Apologies if it's something dumb. Eg. a missing comma.
Thanks.
Got it working !! Here's the working code:
$apiContext = new \PayPal\Rest\ApiContext(
new \PayPal\Auth\OAuthTokenCredential(
$credentials['clientId'],
$credentials['secret']
)
);
$apiContext->setConfig(
array(
'log.LogEnabled' => true,
'log.FileName' => '../app/storage/paypal/PayPal.log',
'log.LogLevel' => 'FINE'
)
);
$card = new CreditCard();
$card->setType("visa")
->setNumber("xxxxxxxxxxxxxxxxx")
->setExpireMonth("11")
->setExpireYear("2019")
->setCvv2("012")
->setFirstName("Joe")
->setLastName("Shopper");
$fi = new FundingInstrument();
$fi->setCreditCard($card);
$payer = new Payer();
$payer->setPaymentMethod("credit_card")
->setFundingInstruments(array($fi));
$item1 = new Item();
$item1->setName('Ground Coffee 40 oz')
->setDescription('Ground Coffee 40 oz')
->setCurrency('USD')
->setQuantity(1)
->setPrice(49.99);
$itemList = new ItemList();
$itemList->setItems(array($item1));
$details = new Details();
$details->setSubtotal(49.99);
$amount = new Amount();
$amount->setCurrency("USD")
->setTotal(49.99)
->setDetails($details);
$transaction = new Transaction();
$transaction->setAmount($amount)
->setItemList($itemList)
->setDescription("Payment description")
->setInvoiceNumber(uniqid());
$payment = new Payment();
$payment->setIntent("sale")
->setPayer($payer)
->setTransactions(array($transaction));
try
{
$payment->create($apiContext);
}
catch (Exception $ex)
{
dd($ex->getData());
}
dd($payment);
I was missing new Amount & new Details. Also, for the sake of documentation, your monetary totals must add up. Eg. tax, subtotal, total.
Related
I use the PayPal SDK for PHP and want to go to the checkout without showing details and total instead of subtotal (like on the picture left).
Thanks!
Example Picture
This is the Code i use.
$arrPrices = $this->getPrices();
$apiContext = $this->getApiContext();
$payer = new \PayPal\Api\Payer();
$payer->setPaymentMethod("paypal");
$arrItems = [];
$item = new \PayPal\Api\Item();
$item->setName($saveValues['title'])->setCurrency('EUR')->setQuantity(1)->setPrice($arrPrices['raw']);
$arrItems[] = $item;
$itemList = new \PayPal\Api\ItemList();
$itemList->setItems($arrItems);
$details = new \PayPal\Api\Details();
$details->setTax($arrPrices['tax'])->setSubtotal($arrPrices['raw']);
$amount = new \PayPal\Api\Amount();
$amount->setCurrency("EUR")->setTotal($arrPrices['total'])->setDetails($details);
$transaction = new \PayPal\Api\Transaction();
$transaction->setAmount($amount)->setItemList($itemList)->setDescription("Vielen Dank für Deine Buchung & bis bald!");
$redirectUrls = new \PayPal\Api\RedirectUrls();
$url = \Environment::get('url') . '/' . $GLOBALS['SCRIPT_URL'];
$redirectUrls->setReturnUrl("$url?success=true")->setCancelUrl("$url?success=false");
$payment = new \PayPal\Api\Payment();
$payment->setIntent("sale")->setPayer($payer)->setRedirectUrls($redirectUrls)->addTransaction($transaction);
try {
$payment->create($apiContext);
}
catch (\Exception $ex) {
return $ex->getData();
}
return $payment->getApprovalLink();
If you don't provide the details you will not see the details ? there isn't a way by which you will provide the details and then not have display it on the paypal approval page (of which you are showing the screen shot)
I am using PHP SDK for constant contact plugin. I want to move contact from one list to another. I have tried following code it will generate BAD response error.
$action = "Updating Contact";
$contact = $response->results[0];
foreach ($contact->lists as $key => $value) {
unset($contact->lists[$key]);
}
$cc->contactService->updateContact(WPYog_ACCESS_TOKEN, $contact,true);
$contact->addList((string)$_POST['list_id']);
$contact->first_name = 'Sudhir';
$contact->status = 'ACTIVE';
$contact->email_addresses[0]->status = 'ACTIVE';
$contact->last_name = 'Pandey';
try {
$cc->contactService->updateContact(WPYog_ACCESS_TOKEN, $contact,true);
}catch (CtctException $ex) {
var_dump($ex->getErrors());
}
I have found answer. First of all fetch the record by using this
$action = "Updating Contact";
$contact = $response->results[0];
// Now empty the list
$contact->lists = array();
$contact->addList((string)$_POST['list_id']);
$contact->first_name = 'Sudhir';
$contact->status = 'ACTIVE';
$contact->email_addresses[0]->status = 'ACTIVE';
$contact->last_name = 'Pandey';
try {
$cc->contactService->updateContact(WPYog_ACCESS_TOKEN, $contact,true);
}catch (CtctException $ex) {
var_dump($ex->getErrors());
}
I have problems retrieving Lead Ads.
I have the Ad-ID and the Page-ID. I haven't created them, but was added as a developer.
I was trying to use the PHP SDK and this https://developers.facebook.com/docs/marketing-api/guides/lead-ads/v2.9
Nothing is working. I cannot find a nice tutorial about that.
I just want to retrieve the leading Ads!
Anyone?
Assuming you have already installed FB API SDK and configured your FB app, you can use this to get all results from all LeadAds of your $page_id
use FacebookAds\Api;
use FacebookAds\Object\Page;
use FacebookAds\Object\Ad;
$access_token = 'YOUR TOKEN';
$app_id = 'YOUR APP ID';
$app_secret = 'YOUR APP SECRET';
$page_id = 'YOUR PAGE ID';
Api::init($app_id, $app_secret, $access_token);
$ads = getAllLeadsAds($page_id);
$result = array();
foreach ($ads->data as $item) {
$leads = getLeadAdInfo($item->id);
$i = 0;
foreach ($leads->data as $value) {
$result[$i]['ad_id'] = $item->id;
$result[$i]['lead_id'] = $value->id;
$result[$i]['form'] = $value->field_data;
$i++;
}
}
print_r($result);
function getAllLeadsAds($page)
{
$page = new Page($page);
return $page->getLeadgenForms()->getResponse()->getBody();
}
function getLeadAdInfo($ad)
{
$ad = new Ad($ad);
return $ad->getLeads()->getResponse()->getBody();
}
Its possible that you not calling all ads inside adset.
You can use facebook cursor.
$cursor->fetchAfter();
use FacebookAds\Object\AdAccount;
use FacebookAds\Object\Values\ArchivableCrudObjectEffectiveStatuses;
use FacebookAds\Object\Fields\CampaignFields;
use FacebookAds\Object\AdCampaign;
use FacebookAds\Object\Fields\AdSetFields;
use FacebookAds\Object\AdSet;
use FacebookAds\Object\Fields\AdFields;
use FacebookAds\Object\Ad;
use FacebookAds\Object\Campaign;
function getadsetname($adset_id,$acc_id){
$adset = new AdSet($adset_id, $acc_id);
$adset->read(array(
AdSetFields::NAME,
));
return $adset->name; // Outputs name of adset.
}
function get_campaignname($campaign_id){
$campaign = new Campaign($campaign_id);
$campaign->read(array(
CampaignFields::NAME,
));
return $campaign->name;
}
$account = new AdAccount($account_id);
echo $adset_name = getadsetname($adset_id,$account_id);
echo $campaign_name = get_campaignname($campaign_id);
echo "<hr>";
$adcampaign = new AdAccount($campaign_id);
$adset = new AdSet($adset_id);
$ads = $adset->getAds(array(
AdFields::NAME,
AdFields::CONFIGURED_STATUS,
AdFields::EFFECTIVE_STATUS,
AdFields::CREATIVE,
));
$ads->fetchAfter();
foreach ($ads as $ad) {
$ad_id = $ad->id;
$ad_name = $ad->name;
if($ad->configured_status=="ACTIVE"){
$ad1 = new Ad($ad_id);
$leads = $ad1->getLeads();
$leads->fetchAfter();
foreach ($leads as $lead) {
$fname = $lead->field_data;
//var_dump($fname);
$data = array();
$data['lead_id'] = $lead->id;
$data['created_time'] = $lead->created_time;
$data['ad_id'] = $ad_id;
$data['ad_name'] = $ad_name;
$data['adset_id'] = $adset_id;
$data['adset_name'] = $adset_name;//$adset_name;
$data['campaign_id'] = $campaign_id;
$data['campaign_name'] = $campaign_name;
$data['form_id'] = $lead->form_id;//$lead->id;
$data['is_organic'] = $lead->is_organic;//$lead->id;
}
}
}
$ads->fetchAfter(); will get the next list of ads and
$leads->fetchAfter(); will get the next list of leads
I created a PHP script with PayPal Rest API. When I complete the payment the site redirect to the finish page with the label of the payment success, but when I go to the sandbox paypal site, I can't see any transactions. What I can do for solve this issue?
Here there are the 3 scripts:
start.php
<?php
require 'vendor/autoload.php';
define('SITE_URL', 'http://192.168.1.105/Fenix/Include/pay.php');
$paypal = new \PayPal\Rest\ApiContext(
new \PayPal\Auth\OAuthTokenCredential(
'AX5IC3G3s-XRzfMgmSUjEPGbHAjD6PL80skf7Xck50OKWXQ2nGf-9NWk5FjSaMCh1FPpxFvUioqZEbjy',
'EJ8GDd08PwnRM1VxYzT2-fBmxAYzykYZ_zlwHi_zqmFGOQzaoXHAffM5DSiBDTcd8L6OpyDzGt5gtmMU'
)
);
?>
checkout.php
<?php
include "./vendor/autoload.php";
use PayPal\Api\Payer;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Details;
use PayPal\Api\Amount;
use PayPal\Api\Transaction;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Payment;
require 'start.php';
/*
if (!isset($_POST['product'], $_POST['price'])){
die();
}
*/
$product = "Fenix ID";
$price = 0.01;
$shipping = 0;
$total = $price+$shipping;
$payer = new Payer();
$payer->setPaymentMethod('paypal');
$item = new Item();
$item->setName($product)
->setCurrency('EUR')
->setQuantity(1)
->setPrice($price);
$itemList = new ItemList();
$itemList->setItems([$item]);
$details = new Details();
$details->setShipping($shipping)
->setSubtotal($price);
$amount = new Amount();
$amount->setCurrency('EUR')
->setTotal($total)
->setDetails($details);
$transaction = new Transaction();
$transaction->setAmount($amount)
->setItemList($itemList)
->setDescription('Fenix ID')
->setInvoiceNumber(uniqid());
$redirectUrls = new RedirectUrls();
$redirectUrls->setReturnUrl(SITE_URL . '/pay.php?success=true')
->setCancelUrl(SITE_URL . '/pay.php?success=false');
$payment = new Payment();
$payment->setIntent('sale')
->setPayer($payer)
->setRedirectUrls($redirectUrls)
->setTransactions([$transaction]);
try {
$payment->create($paypal);
}catch (Exception $e){
die($e);
}
$approvalUrl = $payment->getApprovalLink();
header("Location: {$approvalUrl}");
?>
pay.php
<?php
use PayPal\Api\Payment;
use PayPal\Api\PaymentExecution;
require 'start.php';
if (!isset($_GET['success'], $_GET['paymentId'], $_GET['PayerID'])) {
die();
}
if ((bool)$_GET['success'] === false) {
die();
}
$paymentId = $_GET['paymentId'];
$payment = Payment::get($paymentId, $paypal);
$execution = new PaymentExecution();
$execution->setPayerId($_GET['PayerID']);
echo "Payment success!";
?>
Thanks for the help.
This is the most frustrating ever. It is nearly impossible to find errors when all you get is a white screen!!!
This code is used on other projects and it works fine there so syntactically, it is correct. But SOMETHING must be wrong in the configuration...
Here is the code:
protected function _process($values)
{
// Get our authentication adapter and check credentials
$adapter = $this->_getAuthAdapter();
$adapter->setIdentity($values['username']);
$adapter->setCredential($values['password']);
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($adapter);
if ($result->isValid()) {
$user = $adapter->getResultRowObject();
$auth->getStorage()->write($user);
return true;
}
return false;
}
protected function _getAuthAdapter()
{
$dbAdapter = Zend_Db_Table::getDefaultAdapter();
$authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
$authAdapter->setTableName('Users')
->setIdentityColumn('username')
->setCredentialColumn('password')
->setCredentialTreatment('md5(?)');
return $authAdapter;
}
This is in my auth controller and gets called after I set up the adapter, etc. If I put a die("foo"); right before the $result line, I see it. If I put it right after the $result line, I get a WSOD and the system stops. I know there is not enough here for anyone to debug my code but I was hoping someone else had had this problem and could give me a hint as to what to try to fix this??? I have double checked the database, the column names, etc. I need to know what kinds of things may make the line:
$result = $auth->authenticate($adapter);
result in a white screen of death??? Any ideas? I have all error display turned on in application.ini.
I am running Zend 1.11.12 on this server. Does that make a difference? The server where it is working is running is running 1.12.0-9
Thanks for any ideas you might have.
EDIT::: I added code for my _getAuthAdapter.
Enable the error reporting for your app. Set all error reporting to 1 in your configs/application.ini file -
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
resources.frontController.params.displayExceptions = 1
Also, instead of returning true or false, try to print a message, or redirect to a different page to know.
Try a var_dump on the $adapter to see the resulting object.
I've never used Zend_Auth to authenticate. You should be able to do that with your adapter. (assuming your $adapter is an instance of Zend_Auth_Adapter_DbTable for example)
$adapter = $this->_getAuthAdapter();
// this will tell you if there's something wrong with your adapter
if (!($adapter instanceof Zend_Auth_Adapter_DbTable)) {
throw new Exception('invalid adapter');
}
$adapter->setIdentity($values['username']);
$adapter->setCredential($values['password']);
$result = $adapter->authenticate();
if ($result->isValid()) {
}
I tried like below,
public function loginAction() {
$this->_helper->layout->disableLayout();
$users = new Application_Model_DbTable_Admin();
$this->_redirector = $this->_helper->getHelper('Redirector');
$form = new Application_Form_LoginForm();
$this->view->form = $form;
if ($this->getRequest()->isPost()) {
if ($form->isValid($_POST)) {
$consumer = new Zend_OpenId_Consumer();
$username = $this->_request->getPost('username');
$password = $this->_request->getPost('password');
if ($username <> '' && $password <> '') {
$auth = Zend_Auth::getInstance();
$authAdapter = new Zend_Auth_Adapter_DbTable($users->getAdapter(), 'admin');
$authAdapter->setIdentityColumn('username')
->setCredentialColumn('password');
$authAdapter->setIdentity($username)
->setCredential(md5($password));
$result = $auth->authenticate($authAdapter);
if ($result->isValid()) {
$storage = new Zend_Auth_Storage_Session();
$storage->write($authAdapter->getResultRowObject());
$this->_auth_user = $auth->getStorage()->read();
$this->_redirect('admin/index/');
}
else
$this->view->errorMessage = "Invalid username or password. Please try again.";
}
else
$this->view->errorMessage = "Username or password should not be empty!!!.";
}
}
}
If your Adapter doesn't work try it:
public function _getAuthAdapter() {
$authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter());
$authAdapter->setTableName('table_name')
->setIdentityColumn('user_name')
->setCredentialColumn('password');
return $authAdapter;
}
And in application.ini
resources.db.isDefaultTableAdapter = true