I have tried everything I can possibly think of, and nothing I do helps. I have even gone so far as to download the sample "Pizza Store" application they have on github. Every time, when I replace the "EndPoint" in the sdk-config.ini with "live" and then put in my clientID and clientSecret, and update the bootstrap.php file with that information, that I get from the "my Apps" section I get the error "Got Http response code 400 when accessing https://api.paypal.com/v1/vault/credit-cards."
I am even just using the sample application they provide, and I get that error. I have been searching and searching, and it look slike there are a good 40 different end points, but no documentation on how to use them, how to set them, or anything about it. The only thing I can gather from the sample app is that you can set the "mode" to live in the "setConfig" call, but that just results in the 400 error. I am desperate, I need some help here. I have even emailed their support, and haven't gotten a response. I am trying to help a friend out and get a website up where people can buy things, but this 400 error is driving me insane. Here is a direct copy of my code I am using to try this out...
$config = Config::getItem('merchant_settings', 'paypal');
$config = $config['production'];
$sdkConfig = array('mode' => 'live');
$apiContext = new ApiContext(new OAuthTokenCredential($config['client_id'], $config['client_secret']));
$apiContext->setConfig($sdkConfig);
$card = new CreditCard();
$card->setType('visa');
$card->setNumber('4446283280247004');
$card->setExpireMonth('11');
$card->setExpireYear('2018');
$card->setFirstName('Joe');
$card->setLastName('Shopper');
$funding_instrument = new FundingInstrument();
$funding_instrument->setCreditCard($card);
$payer = new Payer();
$payer->setPaymentMethod('credit_card');
$payer->setFundingInstruments($funding_instrument);
$amount = new Amount();
$amount->setCurrency('USD');
$amount->setTotal('15.85');
$transaction = new Transaction();
$transaction->setAmount($amount);
$transaction->setDescription('A test purchase');
$payment = new Payment();
$payment->setIntent('sale');
$payment->setPayer($payer);
$payment->setTransactions(array($transaction));
try {
$res = $payment->create($apiContext);
$this->set('data' , $res);
} catch(PayPalConnectionException $ex) {
$this->set('data', $ex);
} catch(Exception $e) {
$this->set('data', $e);
}
echo '<pre>';
print_r($data);
echo '</pre>';
And the error I am getting back is...
{"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":"2c61b8ecedfc6"}
I don't understand, I am using the exact same code as the sample application. Why am I getting that error. I have gone to that link, no help what so ever. Please, I am begging please help.
Yes, I realize that card information is fake, but I should be getting a credit card declined error, not a malformed request error. Please.
I don't know PHP but I think funding instrument is supposed to an array:
"payer":{
"payment_method":"credit_card",
"funding_instruments":[
{
"credit_card":{
If you create a funding instrument array ($fiArray) of length one, and set the first element to $funding_instrument, and pass the array to $payer->setFundingInstruments(fiArray).
Related
I am trying to check for toll-free numbers, and it is working as expected. However, my problem is that some countries don't have the TollFree numbers.
Using the same code on these countries throws a 404 error and stops the code there.
The only way I could think of is making a massive if statement and adding each country manually which offers toll-free option, but I don't like this solution at all as it will be hardcoded. Is there a way to overcome this issue, so it works for the countries that has the .json and ignore the ones that doesn't (instead of crashing the code)?
$twilio = new Client(env('TWILIO_ID'), env('TWILIO_TOKEN'));
$iso = 'CY';
$params = ["excludeLocalAddressRequired" => "true"];
$tollFreeNumbers = $twilio->availablePhoneNumbers($iso)->tollFree->read($params);
This is the response:
"[HTTP 404] Unable to fetch page: The requested resource /2010-04-01/Accounts/ACxxxxx/AvailablePhoneNumbers/CY/TollFree.json was not found"
Using this code will crash with CY but will work with UK, US, CA and many more. Should I add an if statement with hardcoded countries? (I really dislike this solution, but this is what I can think of). What I mean is:
if ($iso == 'GB' || $iso == 'US' || $iso == 'CA') { // and many more
$tollFreeNumbers = $twilio->availablePhoneNumbers($iso)->tollFree->read($params);
}
Twilio developer evangelist here.
Rather than guarding up front with a conditional (which could become out of date as we add toll free numbers in other countries in the future), why not catch the error and return a message to the user to say that toll free numbers are not available in the country they are searching in.
Something like:
try {
$tollFreeNumbers = $twilio->availablePhoneNumbers($iso)->tollFree->read($params);
} catch (Exception $e) {
$tollFreeNumbers = [];
$message = "Toll free numbers are not available in this country.";
}
Let me know if that helps at all.
Why not just wrap it in a try catch?
try {
$tollFreeNumbers = $twilio->availablePhoneNumbers($iso)->tollFree->read($params);
} catch(\Exception $e) {
$tollFreeNumbers = [];
}
We are using authorize.net as payment gateway and we need to send the amount to two different merchants in single transaction. In order to achieve it, we are using the below code.
<?php
require_once 'anet_php_sdk/AuthorizeNet.php';
define("AUTHORIZENET_API_LOGIN_ID", "12345");
define("AUTHORIZENET_TRANSACTION_KEY", "abcde");
define("AUTHORIZENET_SANDBOX", true);
$sale = new AuthorizeNetAIM;
$amount = $_POST['ordertotal'];
$bill_to_cardholder = $_POST['bill_to_cardholder'];
$bill_to_card_number = trim($_POST['bill_to_card_number']);
$bill_to_cvv2 = $_POST['bill_to_cvv2'];
$exp_date = $_POST['bill_to_exp_month'].$_POST['bill_to_exp_year'];
//add information to authorize
$sale->first_name = $_SESSION['bill_to_first_name'];
$sale->last_name=$_SESSION['bill_to_last_name'];
$response1 = $sale->authorizeOnly($amount,$bill_to_card_number,$exp_date);
if ($response1->approved) {
define("AUTHORIZENET_API_LOGIN_ID", "678910"); define("AUTHORIZENET_TRANSACTION_KEY", "fghij");
$response2 = $sale->authorizeOnly($amount,$bill_to_card_number,$exp_date);
echo "<pre>"; print_r($response2); exit;
}
?>
But here the problem is that first transaction is completed successfully and second one is denied. Because, once the constant is defined, we could not able to overwrite through PHP script. We have tried by defining as variable for the parameters that supposed to pass on authorize.net such as $AUTHORIZENET_API_LOGIN_ID and $AUTHORIZENET_TRANSACTION_KEY but the authorize.net not accepted the normal variables. Could anyone please provide the solution how to transfer the amount to two different merchants in single transaction using authorize.net? Thanks.
I've been trying to post an image with a simple message onto twitter using PHP and twitteroauth.php.
However, every time I run my code, I only get the $tweetMessage published on the twitter feed without any image.
I searched and searched and read their own documentation but don't even get me started on their own documentation! its like someone who's had a sleepwalk was writing their documentation. Just a bunch of jargon..
And most of the information on STO is either outdated or pointing to a library!
I do not want to use any library as I will have to try to learn someone else's code as well and Surely twitter would allow publishing photo's using their own API without the use of any third party Library?!
Any way, This is my full code:
// Include twitteroauth
require_once('inc/twitteroauth.php');
// Set keys
$consumerKey = 'xxxxxxxxxxxxxxxxxxx';
$consumerSecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$accessToken = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$accessTokenSecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
// Create object
$tweet = new TwitterOAuth($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret);
// Set status message
$tweetMessage = 'This is a tweet to my Twitter account via PHP.';
$image_path="https://www.google.co.uk/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";
$handle = fopen($image_path,'rb');
$image = fread($handle,filesize($image_path));
fclose($handle);
// Check for 140 characters
if(strlen($tweetMessage) <= 140)
{
// Post the status message
$tweet->post('statuses/update', array('media[]' => "{$image};type=image/jpeg;filename={$image_path}", 'status' => $tweetMessage));
}
Could someone please advise on this issue?
Thanks in advance.
EDIT:
I've changed my code to the following and I get this error:
{"errors":[{"code":195,"message":"Missing or invalid url parameter."}]}
But I'm sure the image is on the specified URL/directory!
This is the code:
require_once 'inc/twitteroauth.php';
define("CONSUMER_KEY", "xxxxxxxxxxxxxxxxx");
define("CONSUMER_SECRET", "xxxxxxxxxxxxxxxxxxxxxxxxxx");
define("OAUTH_TOKEN", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
define("OAUTH_SECRET", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_SECRET);
$content = $connection->get('images/sign-in-with-twitter-l.png');
$image = 'images/sign-in-with-twitter-l.png';
$status_message = 'Attaching an image to a tweet';
$status = $connection->post('statuses/update_with_media', array('status' => $status_message, 'media[]' => file_get_contents($image)));
echo json_encode($status);
Any idea why this error is being shown?
Uploading media to Twitter is slightly complicated. Essentially, it's a three stage process.
Upload the photo to Twitter.
Receive a media_id back from Twitter.
Post your status and media_id to Twitter.
This is described in great detail at https://dev.twitter.com/rest/reference/post/media/upload
Generally speaking, it is easier for use to use a library like CodeBird as they've already done the hard work of finding all the edge cases.
But, assuming you don't want to do that...
POST the image to /1.1/media/upload.json
Receive back some JSON like
{
"media_id": 553656900508606464,
"media_id_string": "553656900508606464",
"size": 998865,
"image": {
"w": 2234,
"h": 1873,
"image_type": "image/jpeg"
}
}
* Use that media_id_string when you post the status. e.g.
tweet->post('statuses/update', array('media_ids' => $media_id_string, 'status' => $tweetMessage));
Hopefully that gives you enough to understand what's going on.
I solved it like this:
$tweet_img = 'Path/to/image';
$handle = fopen($tweet_img,'rb');
$image = fread($handle,filesize($tweet_img));
fclose($handle);
$parameters = array('media[]' => "{$image};type=image/jpeg;filename={$tweet_img}",'status' => 'Picture time');
$returnT = $connection->post('statuses/update_with_media', $parameters, true);
Horrible twitter API documentation needs improving!! it needs to be written by humans as opposed to a bunch of sleepwalking zombies!!!
This is a very frustrating situation that they put us in when we try to use their API...
They either need stop their API support and remove it all from the public or simply improve their documentation and write it for the public and not just for their own use using jargon words.
Any way, the above code works just fine using the latest twitteroauth
I hope this helps others in my situation.
I feel like i wasted 5 hours for something that should be clear and mentioned in plain English on their site!!!
Rant and Answer over & good luck.. :)
I'm trying to access my Google Analytics data using a service account. I've created one in the Developers Console and I've enabled the Google Analytics API in that same console, but somehow, I can't manage to pull data from the API.
I've used the script on this page.
My code is as follows:
<?php
$keyfile = 'google/key.p12';
// Initialise the Google Client object
$client = new Google_Client();
$client->setApplicationName('MyNAME');
$client->setAssertionCredentials(
new Google_AssertionCredentials(
'XXXX#developer.gserviceaccount.com', array('https://www.googleapis.com/auth/analytics.readonly'), file_get_contents($keyfile)
)
);
$client->setClientId('XXXX.apps.googleusercontent.com');
$client->setAccessType('offline_access');
$analytics = new Google_AnalyticsService($client);
$analytics_id = 'ga:UA-XXXXXX-1'; // http://productforums.google.com/forum/#!topic/analytics/dRuAr1K4waI
// get data for the last 2 weeks
$lastWeek = date('Y-m-d', strtotime('-2 week'));
$today = date('Y-m-d');
// Test connection
try {
$results = $analytics->data_ga->get($analytics_id, $lastWeek, $today, 'ga:visits');
echo '<b>Number of visits this week:</b> ';
echo $results['totalsForAllResults']['ga:visits'];
} catch (Exception $e) {
echo 'There was an error : - ' . $e->getMessage();
}
?>
Note: if it says "XXXX", that means I've removed part of the string for security purposes; the proper strings are in my actual script.
It should either display the number of users or a error, but I just get a blank screen. I'm sure the URL to the keyfile is correct.
Does anybody have suggestions on how to fix this? That would be much appreciated.
It looks like you are using your property Id (UA-XXXXX-1) in place of your view (profile) id. If you go to Google Analytics Query Explorer it makes it easy to see what your actual ga:XXXX view (profile) id is. Any given property can have multiple view's (profiles). This reference guide gives a good description of the parameters that this request requires.
I'm trying to use Paypal's adaptive payments API and having a tough time switching it to production. Everything works as expected on sandbox mode and I get a proper response, but when I switch to my live APP ID it doesn't work.
These are the configuration values I'm using for sandbox
PayPal URL : https://www.sandbox.paypal.com/webapps/adaptivepayment/flow/pay?paykey=[TOKEN_HERE]
Application ID : APP-80W284485P519543T
These values work for me in sandbox mode. But when I switch to the below production values, it stops working
PayPal URL : https://www.paypal.com/webapps/adaptivepayment/flow/pay?paykey=[TOKEN_HERE]
Application ID : [ACTUAL APP ID]
This is what I mean by stops working.
In production mode, the application gets the paykey
Appends it to the Paypal URL and then redirects it to their site
On site load, I get the following message
This transaction has already been approved. Please visit your PayPal Account Overview to see the details
The final URL it ends up on - https://ic.paypal.com/webapps/adaptivepayment/flow/payinit?execution=e6s1
Screenshot - http://screencast.com/t/28qJZ9CIk
There is also a 'Return' button there, and when I click on it I get taken to a different site each time (Looks like I get sent to random failUrls)
I've included the code I use below
$payRequest = new PayRequest();
$payRequest->actionType = "PAY";
$payRequest->cancelUrl = $cancelURL; //my success and fail urls
$payRequest->returnUrl = $returnURL;
$payRequest->clientDetails = new ClientDetailsType();
$payRequest->clientDetails->applicationId = $this->config['application_id'];
$payRequest->clientDetails->deviceId = $this->config['device_id'];
$payRequest->clientDetails->ipAddress = $this->CI->input->ip_address();
$payRequest->currencyCode = $currencyCode;
$payRequest->requestEnvelope = new RequestEnvelope();
$payRequest->requestEnvelope->errorLanguage = "en_US";
//I set the receiver and the amounts. I also define that these are digital goods payments
$receiver1 = new receiver();
$receiver1->email = $opts['receiver_email'];
$receiver1->amount = $opts['amount'];
$receiver1->paymentType = 'DIGITALGOODS';
$payRequest->receiverList = new ReceiverList();
$payRequest->receiverList = array($receiver1);
//Then I make the call
$ap = new AdaptivePayments();
$response = $ap->Pay($payRequest);
if(strtoupper($ap->isSuccess) == 'FAILURE') {
log_message('error', "PAYMENT_FAIL : " . print_r($ap->getLastError(), true));
return false;
} else {
if($response->paymentExecStatus == "COMPLETED") {
header("Location: " . $this->config['success_url']);
exit;
} else {
$token = $response->payKey;
$payPalURL = $this->config['paypal_redirect_url'] . 'paykey='.$token;
header("Location: ".$payPalURL);
exit;
}
}
This is code taken from their sample implementation, so not really sure what's going wrong here. Other information that might be relevant
I'm using adaptive payments to make sure that the sender and receiver
actually did the transaction
I have set the payment type as 'DIGITAL GOODS'
EDIT
I've included a sample URL with the pay key attached
https://www.paypal.com/webapps/adaptivepayment/flow/pay?paykey=AP-0H388650F08226841
I found the issue that was giving me all of this grief.
The Paypal SDK uses a couple of constants which are defined in /sdk/lib/Config/paypal_sdk_clientproperties
The constants contain the username, password, application_id the API url and a few others. These are used directly in the file /sdk/lib/CallerServices,php. So contrary to what you would expect in an API, these values are not injected in the setup phase so if you don't notice that file and change the values, the above code will not work.
To fix the issue, simply update the values defined in the file and you should be good to go.