I've been looking at several examples of utilizing paypal's API to develop a simple script to be able to use it to checkout, and in each one I keep running across cURL, and I really don't understand it at all. Is it just different PHP functions from a library, or something all together different? More importantly, can I copy and paste cURL commands into my document and it will work, or do I need to download something to get it work on my local server and shared hosting server where my live site will go? Lastly, where can I go to learn this? I've done some searching but haven't found any solid material on it. I really appreciate any help.
A basic understanding of cURL example from PHP Manual
<?php
$ch = curl_init("http://www.example.com/");
$fp = fopen("example_homepage.txt", "w");
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
?>
PHP Manual
cURL with PayPal API . [Found it on the internet]
<?php
$ch = curl_init();
$clientId = "myId";
$secret = "mySecret";
curl_setopt($ch, CURLOPT_URL, "https://api.sandbox.paypal.com/v1/oauth2/token");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $clientId.":".$secret);
curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials");
$result = curl_exec($ch);
if(empty($result))die("Error: No response.");
else
{
$json = json_decode($result);
print_r($json->access_token);
}
curl_close($ch);
?>
You can use a simple form to the checkout. To use via cURL you need to enable cURL and use it in your PHP code.
The following is the simple way.
<form action="https://paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="business" value="sandy_1314264698_biz#gmail.com ">
<input type="hidden" name="cmd" value="_xclick-subscriptions">
<input type="hidden" name="item_name" value="sand bag">
<input type="hidden" name="item_number" value="1234">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="notify_url" value="http://abc.com/xyz.php">
<input type="hidden" name="return" value="http://google.com">
<!-- Display the payment button. -->
<input type="image" name="submit" border="0" src="btn_subscribe_LG.gif" alt="PayPal - The safer, easier way to pay online">
<img alt="" border="0" width="1" height="1" src="https://www.paypal.com/en_US/i/scr/pixel.gif" >
Related
I am trying to use Namecheap's API for domain information, although their API documentation doesn't explain very well and it would be the first time that I am using XML data, I'm trying to return the data from the XML file.
I am currently using a form to add variables and POST/GET data to this XML request, on submit, the XML page displays and that is the end of that.
I am wondering how it is possible to send and receive this data using PHP?
Here is what I have so far...
Very Simple:
<form action="https://api.namecheap.com/xml.response" method="POST">
<input type="hidden" id="ApiUser" name="ApiUser" value="user" />
<input type="hidden" id="UserName" name="UserName" value="user" />
<input type="hidden" id="ApiKey" name="ApiKey" value="###" />
<input type="hidden" id="Command" name="Command" value="namecheap.domains.check" />
<input type="hidden" id="ClientIp" name="ClientIp" value="<? echo $_SERVER['REMOTE_ADDR']; ?>" />
<input type="text" id="DomainList" name="DomainList" />
</form>
Like I said, this sends me straight through to the XML file. I am thinking that I probably need to perform a POST ISSET or something...
<?
if(isset($_POST['domain_check'])){
PERFORM XML STUFF HERE
}
?>
Yet I don't have a clue how to send or receive data in this way as I am a beginner. The data is returned like so:
<ApiResponse xmlns="http://api.namecheap.com/xml.response" Status="OK">
<Errors/>
<Warnings/>
<RequestedCommand>namecheap.domains.check</RequestedCommand>
<CommandResponse Type="namecheap.domains.check">
<DomainCheckResult Domain="test.com" Available="false" ErrorNo="0" Description="" IsPremiumName="false" PremiumRegistrationPrice="0" PremiumRenewalPrice="0" PremiumRestorePrice="0" PremiumTransferPrice="0" IcannFee="0" EapFee="0"/>
</CommandResponse>
<Server>PHX01APIEXT01</Server>
<GMTTimeDifference>--4:00</GMTTimeDifference>
<ExecutionTime>1.061</ExecutionTime>
</ApiResponse>
Please inform me with the best way to do this? Thanks.
To parse the response try using simple_xml,
$xml=simplexml_load_string($myXMLData) or die("Error: Cannot create object");
print_r($xml);
Try using cURL so you don't have to submit a form manually, I haven't tested this but this example should help get you going
<?php
$ch = curl_init();
$baseUrl = 'https://api.sandbox.namecheap.com/xml.response?ApiUser=ncuser&ApiKey=apikey&UserName=ncuser&ClientIp=121.22.123.22&Command=namecheap.domains.check&DomainList=domain1.com,domain2.com';
$url = $baseUrl . $query;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec($ch);
if ($output === false) {
die(curl_error($ch));
}
//print_r(curl_getinfo($ch));
curl_close($ch);
return $output;
I am using a third party payment service.
<form name="form1" method="post" action="https://exampledomain.com/postpayment.php">
<input type="hidden" name="CRESecureID" value="1"/>
<input type="hidden" name="trans_type" value=" 2"/>
<input type="hidden" name="content_template_url" value="https://example.com/enterpaymentdetails.html"/>
<input type="hidden" name="allowed_types" value=" 3"/>
<input type="hidden" name="total_amt" value="$payment->amount"/>
<input type="hidden" name="collect_total_amt" value="$payment->total"/>
<input type="hidden" name="sess_id" value="e91dd8af53j35k072s0bubjtn7"/>
<input type="hidden" name="sess_name" value="session"/>
<input type="hidden" name="return_url" value="https://example.com/return.html"/>
<p><label> <input type="submit" name="submit" value="submit"/> </label></p>
How can I correctly send these variables to an external URL? Should I do it in the controller? An example would be helpful.
Thanks
Best method to implement this is:
Post form data to one of your own URL, then post this data to the required external URL using Guzzle client or curl request.
This approach will help you to track the response from the external URL and manipulate or use it if required.
Hope this helps.
You can do it on controller, a good approach will be to get these variables on controller, pass them to repository/service layer, perform all the validation checks and once everything is good, send them via CURL POST.
You can use Request to validate the form fields. Validate, process and send.
Here is the code to send data via CURL post
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "URL_OF_API");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 100);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFieldsArray);
$data = curl_exec($ch);
curl_close($ch);
Try adding double forward-slash in your form action
E.g. <form action="{{'//newsite.com/whatever'}}" >
That is all.
I'm trying to use the refund API of Paypal. I am currently using sandbox accounts. payment is working fine. refund is working fine when I use form fields to post the data to paypal like below
<form action="https://api-3t.sandbox.paypal.com/nvp" METHOD="GET">
<input type="text" name="USER" value="**********"/>
<input type="text" name="PWD" value="**********"/>
<input type="text" name="SIGNATURE" value="**********"/>
<input type="text" name="METHOD" value="RefundTransaction"/>
<input type="text" name="VERSION" value="94"/>
<input type="text" name="TRANSACTIONID" value="<?php echo $data['transaction_id']; ?>"/>
<input type="text" name="REFUNDTYPE" value="Partial"/>
<input type="text" name="AMT" value="<?php echo $amount; ?>"/>
<input type="text" name="CURRENCYCODE" value="GBP"/>
<input type="text" name="NOTE" value="refund"/>
<input type="submit" value="pay"/>
</form>
the response is printed on the screen automatically and it shows refund success.
but I need to compare the ACK of the response to do other actions after refund. so I tried using curl like below.
$req = array(
'USER' => urlencode('**************'),
'PWD' => urlencode('***************'),
'SIGNATURE' => ************'),
'METHOD' => 'RefundTransaction',
'VERSION' => urlencode(119),
'TRANSACTIONID' => $data[transaction_id],
'REFUNDTYPE' => 'Partial',
'AMT' => urlencode($amount),
'CURRENCYCODE' => 'GBP',
'NOTE' => urlencode('test'),
);
$ch = curl_init('https://api-3t.sandbox.paypal.com/nvp');
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
if(!($res = curl_exec($ch)) ) {
error_log("Got " . curl_error($ch) . " when processing IPN data");
curl_close($ch);
exit;
}
curl_close($ch);
echo "response is : ".urldecode($res);
curl call is made successfully, but the response is always internal error (10001) from paypal. what I am doing wrong. Please help
NOTE : I just replaced the credentials with asterisks.
I don't believe you need to urlencode the AMT value. It should be sent as a properly formatted decimal. Also, the version number doesn't have to be urlencoded either, and as far as I know, the current highest version is 95, not 119
I need to dinamically generate PayPal links with customized payment amounts and recipients. I don't know much about PayPal's way of handling this kind of stuff, and I actually wonder whether it is possible. I have a table with user's email address and payment value and, on the last column, I need to put that link that, clicked, takes to the PayPal's page where, after security checks and everything, the amount of money by me given can be directly transferred to the email address of the user.
Is it possible to do something like this? I'm working in PHP.
Thanks.
please, read documentation - it's all very well described. you will need to register at https://developer.paypal.com/; refer to https://www.paypal.com/documentation for more information.
I believe paypal standard payments would suffice your needs. read this https://cms.paypal.com/cms_content/US/en_US/files/developer/PP_WebsitePaymentsStandard_IntegrationGuide.pdf -- it has all sorts of samples.
when we integrate paypal, we usually do like this: user picks goods to purchase, then proceeds to checkout. at this point, form is created as per documentation, and that form includes merchant account to use for processing the payment. in the form you also specify: notify_url and cancel_url, so you would get notification from the paypal as to what happened and to which account. that should address your needs.
sample form:
<form action="https://www.'.$this->isSandbox().'paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="business" value="'.$this->api->getConfig('billing/paypal/merchant').'">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="rm" value="2">
<input type="hidden" name="item_name" value="'.addslashes($_GET['descr']).'">
<input type="hidden" name="item_number" value="'.addslashes($_GET['id']).'">
<input type="hidden" name="amount" value="'.addslashes($_GET['amount']).'">
<input type="hidden" name="no_shipping" value="1">
<input type="hidden" name="notify_url" value="http://' . $_SERVER['HTTP_HOST'].$this->api->getDestinationURL('/ppproxy',array('ipn'=>$_GET['id'])).'">
<input type="hidden" name="cancel_return" value="http://' . $_SERVER['HTTP_HOST'].$this->api->getDestinationURL('/ppproxy',array('cancel'=>$_GET['id'])).'">
<input type="hidden" name="return" value="http://' . $_SERVER['HTTP_HOST'].$this->api->getDestinationURL('/ppproxy',array('success'=>$_GET['id'])).'">
<input type="hidden" name="currency_code" value="'.addslashes($_GET['currency']).'">
</form>
sample callback handler:
....
if($_POST){
// might be getting adta from paypal! better log!
foreach ($_POST as $key=>$value) $postdata.=$key."=".urlencode($value)."&";
$postdata.="cmd=_notify-validate";
$curl = curl_init("https://www.".$this->isSandbox()."paypal.com/cgi-bin/webscr");
curl_setopt ($curl, CURLOPT_HEADER, 0);
curl_setopt ($curl, CURLOPT_POST, 1);
curl_setopt ($curl, CURLOPT_POSTFIELDS, $postdata);
curl_setopt ($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($curl, CURLOPT_SSL_VERIFYHOST, 1);
$response = curl_exec ($curl);
curl_close ($curl);
$this->api->logger->logLine($response);
if ($response != "VERIFIED"){
$this->api->logger->logLine('FAILED: post='.print_r($_POST,true));
exit;
}else{
$this->api->logger->logLine('VERIFIED: post='.print_r($_POST,true));
}
if($_POST['payment_status']=='Completed' and $_POST['txn_type']!='reversal')return true; // or perform your desired actions
exit;
}
excerpt from agiletoolkit.org paypal billing addon
I'm using Webex's URL API and for some reason, when writing a simple PHP cURL request to the URL, the API returns failure. But if I pass in the same post parameters into a form, and the form's action attribute equals that API endpoint, the API returns success.
Here's the form method:
<form action="xxxxxxx987" name="hidden_form" method="post">
<input value="EN" name="AT" type="hidden" />
<input value="xxxxxxx987" name="MK" type="hidden" />
<input value="<?php echo $email; ?>" name="AE" type="hidden" />
<input value="<?php echo $firstname; ?>" name="FN" type="hidden" />
<input value="<?php echo $lastname; ?>" name="LN" type="hidden" />
<input value="<?php echo $company; ?>" name="CO" type="hidden" />
<input value="http://mysite.com/resources/thank_you" name="BU" type="hidden" />
</form>
And here's the cURL method:
$url = "https://mysite.com/m.php";
//Data Array
$postParams = array("AT"=>"EN",
"MK"=>"xxxxxxx987",
"AE"=>"my#email.com",
"FN"=>"fname",
"LN"=>"lname",
"CO"=>"my company",
"BU"=>"http://192.168.x.x/resources/thank_you");
//Encode Query Data
$data = http_build_query($postParams);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true); //True For Regular HTTP Post
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: application/x-www-form-urlencoded", "Content-length: ".strlen($data)));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
if($result) {
echo '<h3>Status: Curl Succeeded</h3>';
print 'Result: '.$result;
}
The question: Why does the API fail when I curl it and why does it succeed when using it as the form post action? What's wrong with the cURL method?
You don't need http_build_query because CURLOPT_POSTFIELDS accepts an array