Separate Payment Integeration For Selected plan type using Drupal Form with Paypal API - forms

I have used a normal class as an API and in that U am passing all the parameters to paypal and i am getting success.
Only thing i am missing is that amount is not being deducted from the sandbox account.
Where as if i pay amount for buying a product by using checkout with paypal the actual amount is being deducted in my sandbox account.
What could be the reason? Is there any other alternative way where i can able to use paypal to receive money through passed arguments in payment details form.
In the submit function of the drupal form i am calling like this.
$paypalDoDirect = new PaypalDoDirect();
// passing all parameters to $paypalDoDirect
$response= $paypalDoDirect->MakePayment();
I am getting transaction is successful and every parameters are getting passed sucessfully.
This is my class api-
class PaypalDoDirect
{
/**Declared all fields **/
function MakePayment()
{
$API_Endpoint = "https://api-3t.paypal.com/nvp";
if ("sandbox" === $this->environment || "beta-sandbox" === $this->environment) {
$API_Endpoint = "https://api-3t.$this->environment.paypal.com/nvp";
}
// Add request-specific fields to the request string.
$nvpStr = "&PAYMENTACTION=$this->paymentType&AMT=$this->amount&CREDITCARDTYPE=$this->cc_type&ACCT=$this->cc_number" .
"&EXPDATE=$this->expdate_month$this->expdate_year&CVV2=$this->cvv2_number&FIRSTNAME=$this->first_name&LASTNAME=$this->last_name&EMAIL=$this->email" .
"&STREET=$this->address1&CITY=$this->city&STATE=$this->state&ZIP=$this->zip&COUNTRYCODE=$this->country&CURRENCYCODE=$this->currencyID";
//$httpParsedResponseAr = PPHttpPost('DoDirectPayment', $nvpStr);
$methodName_ = 'DoDirectPayment';
$nvpStr_ = $nvpStr;
// Set the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
// Turn off the server and peer verification (TrustManager Concept).
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
// Set the API operation, version, and API signature in the request.
$nvpreq = "METHOD=$methodName_&VERSION=$this->version&PWD=$this->API_Password&USER=$this->API_UserName&SIGNATURE=$this->API_Signature$nvpStr_";
// Set the request as a POST FIELD for curl.
curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
// Get response from the server.
$httpResponse = curl_exec($ch);
if (!$httpResponse) {
return ("$methodName_ failed: " . curl_error($ch) . '(' . curl_errno($ch) . ')');
}
// Extract the response details.
$httpResponseAr = explode("&", $httpResponse);
$httpParsedResponseAr = array();
foreach ($httpResponseAr as $i => $value) {
$tmpAr = explode("=", $value);
if (sizeof($tmpAr) > 1) {
$httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];
}
}
if ((0 == sizeof($httpParsedResponseAr)) || !array_key_exists('ACK', $httpParsedResponseAr)) {
exit("Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint.");
}
if ("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
return "success";
} else {
return (urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]));
}
}
}

Yes there is a paypal API module in drupal. It's a nice structured module to extend paypal IPN in some custom module.
If you use this module, IPN callback will be handled by this module & you can get notification of it by hook_paypal_api_ipn() at your instance. If you go though paypal documentation about handling payment with paypal & look into the module code, you will understand the mechanism to use it well. I will recommend you to use this module.
Though you can create your own module to handle paypal payment either express or forward users there. I have done it once with drupal instance long ago. You will have to send users or data(for express) at given URL for your account with some information & what ever happens in there(pass/fail/terminate), paypal will inform you at your mentioned callback URL of your instance. Receive the info & do work accordingly..

This might be what you looking for,
Paypal Direct pay not working
Exerpt:
The DoDirectPayment call charges credit cards directly; it does not deduct from a PayPal account - even if that card is attached to an existing PayPal account. Therefore it doesn't show up as a transaction in our 'buyer' PayPal account.

Related

PayPal List Transactions API for subscriptions takes too long to respond with new subscriptions' data

I am using the PayPal REST API to get information about a subscription after the user purchases.
The JS of Paypal suggests that on the onApprove event, we can for example redirect to a thank you page, and it provides us the Subscription ID.
Thus, one would assume the Subscription is done at this point, and one would assume that calling this REST route https://developer.paypal.com/docs/api/subscriptions/v1/#subscriptions_transactions would return results. Yet, it does not -- initially.
It takes up to 10 minutes for the https://developer.paypal.com/docs/api/subscriptions/v1/#subscriptions_transactions call to return anything else than an empty JSON string.
My code is pretty simple:
On onApprove I pass the approved subscription ID in a redirect to a page. When that page loads, I use https://developer.paypal.com/docs/api/subscriptions/v1/#subscriptions_transactions via PHP cURL to get details of that transaction (buyer email) and check in my database if that email exists. If it exists, I redirect to another page, if not, I stay on this page.
Dead simple, and it works just fine - apart of course that PayPal takes about 10 minutes to actually return the transaction results.
Yes, I could add delays, but this is not the point. The point is that PayPal says the transaction is made, when the onApprove event happens. Thus, the data must be available in the REST API too. Is this a known issue? What can be done to avoid this delay? I fear the delay is probably arbitrary and might be more than 10 minutes for other users?
Here is the code I use:
JS button approval flow
<div id="paypal-button-container-P-1UU44524AX8090809MMVRJ3Y"></div>
<script src="https://www.paypal.com/sdk/js?client-id=AS-0AbQhD8wSxv0XMvjeRTAUsa-aZtSZm3fSq-qDp_ibhlq9S5XrkgCVDjchICdKS2IZP7IKVo-MTdz7&vault=true&intent=subscription" data-sdk-integration-source="button-factory" data-namespace = "paypal_sdk"></script>
<script>
paypal_sdk.Buttons({
style: {
shape: 'rect',
color: 'white',
layout: 'vertical',
label: 'subscribe'
},
createSubscription: function(data, actions) {
return actions.subscription.create({
/* Creates the subscription */
plan_id: 'P-1UU44524AX8090809MMVRJ3Y'
});
},
onApprove: function(data, actions) {
window.location.replace("https://www.my-site.com/create-account/?subscription_id=" + data.subscriptionID);
}
}).render('#paypal-button-container-P-1UU44524AX8090809MMVRJ3Y'); // Renders the PayPal button
</script>
Server-side process when loading https://www.my-site.com/create-account/?subscription_id=" + data.subscriptionID
<?php
if ( isset( $_GET['subscription_id'] )
&& ! empty( $_GET['subscription_id'] )
&& is_page( 'create-account' )
) {
/**
* Get Access Token
*/
$ch_auth = curl_init();
curl_setopt($ch_auth, CURLOPT_URL, 'https://api-m.sandbox.paypal.com/v1/oauth2/token');
curl_setopt($ch_auth, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch_auth, CURLOPT_POST, 1);
curl_setopt($ch_auth, CURLOPT_POSTFIELDS, "grant_type=client_credentials");
curl_setopt($ch_auth, CURLOPT_USERPWD, 'USR' . ':' . 'PWD');
$headers_auth = array();
$headers_auth[] = 'Content-Type: application/x-www-form-urlencoded';
curl_setopt($ch_auth, CURLOPT_HTTPHEADER, $headers_auth);
$result_auth = curl_exec($ch_auth);
if (curl_errno($ch_auth)) {
echo 'Error:' . curl_error($ch_auth);
}
curl_close($ch_auth);
$auth_arr = json_decode($result_auth);
$auth = $auth_arr->access_token;
/**
* Get Subscription details
*/
$ch_sub = curl_init();
curl_setopt($ch_sub, CURLOPT_URL, 'https://api-m.sandbox.paypal.com/v1/billing/subscriptions/'.$_GET['subscription_id'].'/transactions?start_time=2022-01-21T07:50:20.940Z&end_time=2022-09-24T07:50:20.940Z');
curl_setopt($ch_sub, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch_sub, CURLOPT_CUSTOMREQUEST, 'GET');
$headers_sub = array();
$headers_sub[] = 'Content-Type: application/json';
$headers_sub[] = 'Authorization: Bearer ' . $auth;
curl_setopt($ch_sub, CURLOPT_HTTPHEADER, $headers_sub);
$result_sub = curl_exec($ch_sub);
if (curl_errno($ch_sub)) {
echo 'Error:' . curl_error($ch_sub);
}
curl_close($ch_sub);
$first = end(json_decode($result_sub)->transactions)->payer_name->given_name;
$last = end(json_decode($result_sub)->transactions)->payer_name->surname;
$mail = end(json_decode($result_sub)->transactions)->payer_email;
$exists = email_exists( $mail );
if ( $exists ) {
header('Location: '.'https://www.my-site.com/account/?subscription_id=' . $_GET['subscription_id'] . '&account=' . $exists);
die();
}
}
This always fails until I reload the page something between once and 100 times (it varies)
Don't use list transactions, use the get subscription details API to confirm the status of a subscription after approval.
To log all transactions, implement webhooks for the event PAYMENT.SALE.COMPLETED. This is the only webhook you need to listen to for subscriptions, it will record every transaction made and when it does you can update your "good until" date for the subscription to 1 month in the future or whatever.
To aid in reconciliation, add a unique custom_id value during subscription creation (alongside the plan_id) that correlates with the user (in your system) who subscribed. This value will be returned in all future webhooks for the subscription, and can be referenced if for whatever reason you don't have a record of which user a subscription ID (I-xxxxxxxxxxxx) belongs to
I don't know exactly what you are doing, but I recently worked with a frontend application that used a PayPal drop-in form and subscribed to its relative events to trigger calls to our backend.
The calls would take several seconds at max.
Maybe have a look at your event subscribers and make sure they are subscribed to the correct events?
You could incorporate an optimistic redirect and collect the REST reference via a webhook to have it update your existing record once it's ready on their end.
Although I'm not really familiar with the flow you are using, and I have not heard about these delays, you can trust that the transaction is (being) processed if PayPal returns you with an approved event.

Get Email state using codeigniter & sendgrid Webhook

I have integrated sendgrid for send mail. I also want to track whether a user has opened the mail and click the link inside the mail or not.
that's why I used sendgrid.
using it I can send mail, but can't track mail states(mail is opened or not, the link is clicked or not).
I tried the below code for sending mail.
function sendMail($toMails, $body, $subject, $ccMails = array(), $bccMails = array()) {
$ci = &get_instance();
if (empty($toName)) {
$toName = $toMails;
}
$sendMail = $ci->config->item('sendMail');
$email = new \SendGrid\Mail\Mail();
$email->setFrom($ci->config->item('from'), "From User name");
$email->setSubject($subject);
$email->addTos($toMails); //for multiple user pass array with emails and names
$email->addCcs($ccMails);
$email->addBccs($bccMails);
$email->addContent("text/html", $body);
$email->setFooter(false, "", "<strong>If you don't want to receive this type of email in the future, please <a href='http://w3schools.com'>Unsubscribe</a>.</strong>");
//$email->setSpamCheck(true, 1, "http://localhost:8081/");
// Tracking Settings
$email->setClickTracking(true, true);
//$email->setOpenTracking(true, true);
$sendgrid = new \SendGrid($ci->config->item('key'));
try {
$response = $sendgrid->send($email);
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
if ($sendMail) :
if (!$response->statusCode()) :
_pre($response->headers());
return false;
else :
return true;
endif;
endif;
}
which is working fine, except it is going in the spam.
now below code, I am using to get details as per email id.
$sendgrid = new \SendGrid($this->config->item('key'));
$query_params = json_decode('{"start_date": "2019-10-07","end_date": "2019-10-07","to_email": "cadmin1#getnada.com","subject":"This is a subject test"}');
$response = $sendgrid->client->stats()->get(null, $query_params);
_pre($response->body());
exit;
above code only gives me date wise data, but I also want email id wise.
but in spite of adding a parameter for that, still, I am not getting desired output.
https://sendgrid.com/docs/for-developers/sending-email/getting-started-email-activity-api/#filter-by-recipient-email
I have used the above demo, in that demo, they have used curl but I am using CodeIgniter's way.
I am not sure about sendgrid version that's why I added both version tag, I used API one.
anyone having a proper solution regarding it?
I have implemented webhooks to archive my desire output.
for that need to follow steps as per documentation shows
after that need to create a page from where we can get mails status.
on executing that page it returns data as per activity.
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: *');
$data = file_get_contents("php://input");
$events = json_encode($data, true);
$requestData = array('response' => $events);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "<url which we earlier set for webhook as per documentation>");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close($ch);
?>
i have used Curl for getting desire output.

How to pay with paypal and then save parameters from my form?

I have a working website (HTML, bootstrap)
It has a form where I collect various data regarding the user (e.g. email, dates). Upon clicking "Finish" button, the form sends all data to server (which I have developed on python). The server registers the user by saving all the data collected from the form.
I would like to add a PayPal payment system so that the user will pay for registration and then my server-side script will be initiated and all the data that was in the form will be saved. i.e. the same as now, I just want the user to pay and then save the data.
As far members over here adviced, I have to do "Express Checkout Payment Method" (Am I right?). But the explanations I saw in the web were not clear and I cant figure out how to do it.
How can it be done?
Explanation of how Express Checkout works:
Express Checkout Method is a paypal transaction method which is basically split into 3 phases, namely:
SetExpressCheckout: To use Express Checkout, you would call the SetExpressCheckout API. In the API call, you specify the details of
the products, amounts, and the RETURNURL.
GetExpressCheckout: Once the buyer has agreed to your purchase, he is redirected back to the URL you specified in the RETURNURL. You
should now show the order confirmation, and call the
GetExpressCheckoutDetails API**. When calling
GetExpressCheckoutDetails, supply the token. In the
GetExpressCheckoutDetails API response you'll find a PayerID.
DoExpressCheckout: Now you're ready to call DoExpressCheckoutPayment, and charge the buyer. Remember to include both the token and the payerID when calling DoExpressCheckoutPayment.
First goes the cancel function. If a payment is cancelled, then this method will be called.
function payment_failure()
{
echo "payment cancelled by the user";
}
Now comes the payment successful method:
function payment_success()
{
// Obtain the token from PayPal.
if(!array_key_exists('token', $_REQUEST))
exit('Token is not received.');
// Set request-specific fields.
$token = urlencode(htmlspecialchars($_REQUEST['token']));
// Add request-specific fields to the request string.
$nvpStr = "&TOKEN=$token";
// Execute the API operation; see the PPHttpPost function above.
$httpParsedResponseAr = $this->PPHttpPost('GetExpressCheckoutDetails', $nvpStr);
if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"]))
{
$payerID = urlencode($httpParsedResponseAr["PAYERID"]);
$paymentType = urlencode('Sale'); // or 'Sale' or 'Order'
$paymentAmount = urlencode($_SESSION['total_amount']);
$currencyID = urlencode($_SESSION['cur']); // or other currency code ('GBP', 'EUR', 'JPY', 'CAD', 'AUD')
$nvpStr = "&TOKEN=$token&PAYERID=$payerID&PAYMENTACTION=$paymentType&AMT=$paymentAmount&CURRENCYCODE=$currencyID";
$httpParsedResponseAr = $this->PPHttpPost('DoExpressCheckoutPayment', $nvpStr);
if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"]))
{
$transaction_secret=md5(uniqid());
unset($_SESSION['fname']);
unset($_SESSION['lname']);
unset($_SESSION['email']);
unset($_SESSION['password']);
// save the data in the database along with a secret key to uniquely identify the user later(if needed).
}
else
{
exit('DoExpressCheckoutDetails failed: ' . print_r($httpParsedResponseAr, true));
//echo "Payment failed for unknown reason";
}
}
}
else
{
//exit('GetExpressCheckoutDetails failed: ' . print_r($httpParsedResponseAr, true));
echo "Payment failed for unknown reason";
}
}
The first two are the success method and the cancel methods.
Now comes the function which accepts the data from the submit form, and calls the ExpressCheckout methods by passing the parameter to the ExpressCheckout method...
function paypal_order()
{
$_SESSION['fname'] = $_POST['fname']; // fetching the data submitted from the form
$_SESSION['lname'] = $_SESSION['lname']);
$_SESSION['email'] = $_SESSION['email']);
$_SESSION['password'] = $_SESSION['password'];
if($_SESSION['cur']=='USD')
$currencyID = urlencode('USD');
else if($_SESSION['cur']=='INR')
{
$_SESSION['cur'] = 'USD';
$currencyID = urlencode('USD');
}
else if($_SESSION['cur']=='EUR')
$currencyID = urlencode('EUR');
else if($_SESSION['cur']=='GBP')
$currencyID = urlencode('GBP');
$paymentType = urlencode('Order');
$returnURL = (base_url()."paypal-payment-success"); // this call the payment_success() method using the router technique;
$cancelURL = (base_url()."paypal-payment-failure"); // this call the payment_failure() method using the router technique;
$nvpStr="&METHOD=SetExpressCheckout
&RETURNURL=$returnURL
&CANCELURL=$cancelURL";
$i=0;
$str = "
&L_PAYMENTREQUEST_0_NAME$i=User-Registration
&L_PAYMENTREQUEST_0_NUMBER$i=1
&L_PAYMENTREQUEST_0_AMT$i=20
&L_PAYMENTREQUEST_0_DESC$i=User-Registration";
$nvpStr=$nvpStr.$str;
$nvpStr=$nvpStr."&PAYMENTREQUEST_0_AMT=20&PAYMENTREQUEST_0_CURRENCYCODE=$currencyID";
$httpParsedResponseAr = $this->PPHttpPost('SetExpressCheckout', $nvpStr);
if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"]))
{
$token = urldecode($httpParsedResponseAr["TOKEN"]);
$payPalURL = "https://www.paypal.com/webscr&cmd=_express-checkout&token=$token";
if("sandbox" === $environment)
{
$payPalURL = "https://www.$environment.paypal.com/webscr&cmd=_express-checkout&token=$token";
}
header("Location: $payPalURL");
exit;
}
else
{
exit('SetExpressCheckout failed: ' . print_r($httpParsedResponseAr, true));
}
}
And ultimately, the following is the httppost method which is called by the pasing params like, SetExpressCheckout, GetExpressCheckout and DoExpressCheckout.
The following function is called thrice in a scuccessful Express Checkout Transaction:
private function PPHttpPost($methodName_, $nvpStr_)
{
// Set up your API credentials, PayPal end point, and API version.
$environment = "sandbox"; //or "live" for original live transaction;
$API_UserName = "expresscheckout API username goes here";
$API_Password = "expresscheckout API password goes here";
$API_Signature = "expresscheckout API signature goes here";
//$API_UserName = urlencode('saswat_paypay_business_api1.gmail.com');
//$API_Password = urlencode('1365495686');
//$API_Signature = urlencode('AfOa1sjCuxeiTRYj4tqlG6nUGUmhAvv0pzdavzgFM3272hn8CqS5OY0A');
$API_Endpoint = "https://api-3t.paypal.com/nvp";
if("sandbox" === $environment)
{
$API_Endpoint = "https://api-3t.$environment.paypal.com/nvp";
}
$version = urlencode('65.0');
// Set the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
// Turn off the server and peer verification (TrustManager Concept).
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
// Set the API operation, version, and API signature in the request.
$nvpreq = "METHOD=$methodName_&VERSION=$version&PWD=$API_Password&USER=$API_UserName&SIGNATURE=$API_Signature$nvpStr_";
// Set the request as a POST FIELD for curl.
curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
// Get response from the server.
$httpResponse = curl_exec($ch);
if(!$httpResponse)
{
exit("$methodName_ failed: ".curl_error($ch).'('.curl_errno($ch).')');
}
// Extract the response details.
$httpResponseAr = explode("&", $httpResponse);
$httpParsedResponseAr = array();
foreach ($httpResponseAr as $i => $value)
{
$tmpAr = explode("=", $value);
if(sizeof($tmpAr) > 1)
{
$httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];
}
}
if((0 == sizeof($httpParsedResponseAr)) || !array_key_exists('ACK', $httpParsedResponseAr))
{
exit("Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint.");
}
return $httpParsedResponseAr;
}
Your form submission should make the data flow to, or redirect to the function paypal_order() which is responsible for calling all the other functions.

Is it possible to pass the amount back to my site

I am new to developer.paypal.com and i am creating a subscribe button in www.sandbox.paypal.com,is it possible to pass back the amount paid for the subscription by the customer to my website or the details that have been made in www.sandbox.paypal.com?if it is, can you show me some example on how to do this.
after i tried the subscription button this are the value returned i could not find some value in the link that you provided.or the subscription variable how can i show them up?
I could not get the start date and the ending date of my subscription
Thank you.
You could do this one of two ways. You could use IPN or PDT to return information to your site once a payment completes. The better of the two ways, would be to use IPN, or atleast use IPN in conjunction with PDT.
Instant Payment Notification (IPN) is a message service that notifies you of events related to PayPal transactions. You can use it to automate back-office and administrative functions, such as fulfilling orders, tracking customers, and providing status and other information related to a transaction.
You can find more on IPN the page here. Also on that page, off to the left hand side are some more links that are useful as well. There are pages for creating a listener, setup, testing, IPN history, IPN with FMF, IPN/PDT variables, and sample code here. There are also a few more examples of sample code here as well.
PayPal’s PDT system sends order confirmations to merchant sites that use PayPal Payments Standard and lets them authenticate this information. Such sites can then display this data locally in an “order confirmation” page. IPN is more reliable than PDT, and also with PDT it is dependent on the buyer clicking a button to return to your site. If they they dont click on the button to return to your site, no information is sent back and you can not resend this information like you can with IPN. You can find more on PDT here.
I personally only use PDT for crating a dynamic thank you page on my site, and use IPN for updating my database and automating some tasks. Hope this helps. :)
SAMPLE PHP (v5.2) IPN SCRIPT
<?php
// STEP 1: Read POST data
// reading posted data from directly from $_POST causes serialization
// issues with array data in POST
// reading raw POST data from input stream instead.
$raw_post_data = file_get_contents('php://input');
$raw_post_array = explode('&', $raw_post_data);
$myPost = array();
foreach ($raw_post_array as $keyval) {
$keyval = explode ('=', $keyval);
if (count($keyval) == 2)
$myPost[$keyval[0]] = urldecode($keyval[1]);
}
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';
if(function_exists('get_magic_quotes_gpc')) {
$get_magic_quotes_exists = true;
}
foreach ($myPost as $key => $value) {
if($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) {
$value = urlencode(stripslashes($value));
} else {
$value = urlencode($value);
}
$req .= "&$key=$value";
}
// STEP 2: Post IPN data back to paypal to validate
$ch = curl_init('https://www.paypal.com/cgi-bin/webscr');
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'));
// In wamp like environments that do not come bundled with root authority certificates,
// please download 'cacert.pem' from "http://curl.haxx.se/docs/caextract.html" and set the directory path
// of the certificate as shown below.
// curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem');
if( !($res = curl_exec($ch)) ) {
// error_log("Got " . curl_error($ch) . " when processing IPN data");
curl_close($ch);
exit;
}
curl_close($ch);
// STEP 3: Inspect IPN validation result and act accordingly
if (strcmp ($res, "VERIFIED") == 0) {
// check whether the payment_status is Completed
// check that txn_id has not been previously processed
// check that receiver_email is your Primary PayPal email
// check that payment_amount/payment_currency are correct
// process payment
// assign posted variables to local variables
$item_name = $_POST['item_name'];
$item_number = $_POST['item_number'];
$payment_status = $_POST['payment_status'];
$payment_amount = $_POST['mc_gross'];
$payment_currency = $_POST['mc_currency'];
$txn_id = $_POST['txn_id'];
$receiver_email = $_POST['receiver_email'];
$payer_email = $_POST['payer_email'];
} else if (strcmp ($res, "INVALID") == 0) {
// log for manual investigation
}
?>
SAMPLE PDT PHP (v5.3) SCRIPT
<?php
$pp_hostname = "www.paypal.com"; // Change to www.sandbox.paypal.com to test against sandbox
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-synch';
$tx_token = $_GET['tx'];
$auth_token = "GX_sTf5bW3wxRfFEbgofs88nQxvMQ7nsI8m21rzNESnl_79ccFTWj2aPgQ0";
$req .= "&tx=$tx_token&at=$auth_token";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://$pp_hostname/cgi-bin/webscr");
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);
//set cacert.pem verisign certificate path in curl using 'CURLOPT_CAINFO' field here,
//if your server does not bundled with default verisign certificates.
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Host: $pp_hostname"));
$res = curl_exec($ch);
curl_close($ch);
if(!$res){
//HTTP ERROR
}else{
// parse the data
$lines = explode("\n", $res);
$keyarray = array();
if (strcmp ($lines[0], "SUCCESS") == 0) {
for ($i=1; $i<count($lines);$i++){
list($key,$val) = explode("=", $lines[$i]);
$keyarray[urldecode($key)] = urldecode($val);
}
// check the payment_status is Completed
// check that txn_id has not been previously processed
// check that receiver_email is your Primary PayPal email
// check that payment_amount/payment_currency are correct
// process payment
$firstname = $keyarray['first_name'];
$lastname = $keyarray['last_name'];
$itemname = $keyarray['item_name'];
$amount = $keyarray['payment_gross'];
echo ("<p><h3>Thank you for your purchase!</h3></p>");
echo ("<b>Payment Details</b><br>\n");
echo ("<li>Name: $firstname $lastname</li>\n");
echo ("<li>Item: $itemname</li>\n");
echo ("<li>Amount: $amount</li>\n");
echo ("");
}
else if (strcmp ($lines[0], "FAIL") == 0) {
// log for manual investigation
}
}
?>
Your transaction has been completed, and a receipt for your purchase has been emailed to you.<br> You may log into your account at <a href='https://www.paypal.com'>www.paypal.com</a> to view details of this transaction.<br>

How to use dodirect payment paypal on form submission?

I have to use dodirect payment method after the form submission. The form will be displayed on the site for all the card detail such as card type (visa or master), card card no, security number, expiration date, name on card, address, state, postal, country, phone, email etc.
I searched how to use the dodirect method and found as below
<?php
/** DoDirectPayment NVP example; last modified 08MAY23.
*
* Process a credit card payment.
*/
$environment = 'sandbox'; // or 'beta-sandbox' or 'live'
/**
* Send HTTP POST Request
*
* #param string The API method name
* #param string The POST Message fields in &name=value pair format
* #return array Parsed HTTP Response body
*/
function PPHttpPost($methodName_, $nvpStr_) {
global $environment;
// Set up your API credentials, PayPal end point, and API version.
$API_UserName = urlencode('my_api_username');
$API_Password = urlencode('my_api_password');
$API_Signature = urlencode('my_api_signature');
$API_Endpoint = "https://api-3t.paypal.com/nvp";
if("sandbox" === $environment || "beta-sandbox" === $environment) {
$API_Endpoint = "https://api-3t.$environment.paypal.com/nvp";
}
$version = urlencode('51.0');
// Set the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
// Turn off the server and peer verification (TrustManager Concept).
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
// Set the API operation, version, and API signature in the request.
$nvpreq = "METHOD=$methodName_&VERSION=$version&PWD=$API_Password&USER=$API_UserName&SIGNATURE=$API_Signature$nvpStr_";
// Set the request as a POST FIELD for curl.
curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
// Get response from the server.
$httpResponse = curl_exec($ch);
if(!$httpResponse) {
exit("$methodName_ failed: ".curl_error($ch).'('.curl_errno($ch).')');
}
// Extract the response details.
$httpResponseAr = explode("&", $httpResponse);
$httpParsedResponseAr = array();
foreach ($httpResponseAr as $i => $value) {
$tmpAr = explode("=", $value);
if(sizeof($tmpAr) > 1) {
$httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];
}
}
if((0 == sizeof($httpParsedResponseAr)) || !array_key_exists('ACK', $httpParsedResponseAr)) {
exit("Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint.");
}
return $httpParsedResponseAr;
}
// Set request-specific fields.
$paymentType = urlencode('Authorization'); // or 'Sale'
$firstName = urlencode('customer_first_name');
$lastName = urlencode('customer_last_name');
$creditCardType = urlencode('customer_credit_card_type');
$creditCardNumber = urlencode('customer_credit_card_number');
$expDateMonth = 'cc_expiration_month';
// Month must be padded with leading zero
$padDateMonth = urlencode(str_pad($expDateMonth, 2, '0', STR_PAD_LEFT));
$expDateYear = urlencode('cc_expiration_year');
$cvv2Number = urlencode('cc_cvv2_number');
$address1 = urlencode('customer_address1');
$address2 = urlencode('customer_address2');
$city = urlencode('customer_city');
$state = urlencode('customer_state');
$zip = urlencode('customer_zip');
$country = urlencode('customer_country'); // US or other valid country code
$amount = urlencode('example_payment_amuont');
$currencyID = urlencode('USD'); // or other currency ('GBP', 'EUR', 'JPY', 'CAD', 'AUD')
// Add request-specific fields to the request string.
$nvpStr = "&PAYMENTACTION=$paymentType&AMT=$amount&CREDITCARDTYPE=$creditCardType&ACCT=$creditCardNumber".
"&EXPDATE=$padDateMonth$expDateYear&CVV2=$cvv2Number&FIRSTNAME=$firstName&LASTNAME=$lastName".
"&STREET=$address1&CITY=$city&STATE=$state&ZIP=$zip&COUNTRYCODE=$country&CURRENCYCODE=$currencyID";
// Execute the API operation; see the PPHttpPost function above.
$httpParsedResponseAr = PPHttpPost('DoDirectPayment', $nvpStr);
if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
exit('Direct Payment Completed Successfully: '.print_r($httpParsedResponseAr, true));
} else {
exit('DoDirectPayment failed: ' . print_r($httpParsedResponseAr, true));
}
?>
I didn't get an idea how to use this code on submission of the form that I have on my site. Can anyone help me out how to use this after submitting form.
Thanks in advance :)
That's really not a very well built function. It's basically wanting you to just fill in the values within the function rather than pass them in. It's a pretty rough example and you can see it was last updated in 2008 according to the comments.
If you want to use it, though, you can simply fill in all those placeholders where they show things like "my_api_username" with the data that you want to actually include.
If you want something a lot easier to work with, I would recommend using this PHP library for PayPal that I developed and have maintained for years. It's current and contains straight forward samples for running DoDirectPayment. You could have it up-and-running within minutes.
I offer 30 min of free training via screen share, too, if you're interested in that.
Actually there are samples available for DoDirectPayment as part of the official SDKs available at https://www.x.com/developers/paypal/documentation-tools/paypal-sdk-index#expresscheckoutnew
Suggest using the official SDK and check the samples inside them. In case of any issues please post back here or open an issue at https://github.com/paypal/merchant-sdk-php/issues