My code:
function paiement_echec()
{
echo "payment cancelled by the user";
}
function paiement_succes()
{
// 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"]))
{
//print_r($httpParsedResponseAr);
$payerID = urlencode($httpParsedResponseAr["PAYERID"]);
//$token = urlencode("token");
$paymentType = urlencode('Sale'); // or 'Sale' or 'Order'
$paymentAmount = urlencode("4.39");
$currencyID = urlencode("USD"); // or other currency code ('GBP', 'EUR', 'JPY', 'CAD', 'AUD')
// Add request-specific fields to the request string.
$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"]))
{
$this->load->model('payment_model');
$this->payment_model->paypal_payment();
$msg = "<label>Thank you !! your payment is successfully done</label>
<a href='".base_url()."envoie_de_photos/envoyer_vos_photos"."'>Go To Photo Uploading</a>";
echo $msg;
}
else
{
exit('GetExpressCheckoutDetails 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";
}
}
function pay_by_paypal()
{
$environment = 'sandbox';
$_SESSION['item_name']=$this->input->post('item_name');
$_SESSION['amount']=$this->input->post('amount');
$_SESSION['currency_code']=$this->input->post('currency_code');
$_SESSION['no_of_photo']=$this->input->post('no_of_photo');
$qty=urlencode("1");
$product_name=urldecode($_SESSION['item_name']);
$price=urlencode($_SESSION['amount']);
//$currencyID = urlencode($_SESSION['currency_code']);
$currencyID = urlencode("USD");
// or other currency code ('GBP', 'EUR', 'JPY', 'CAD', 'AUD')
$paymentType = urlencode('Order');
$nvpStr="";
$returnURL = (base_url()."paiement/paiement_succes");
$cancelURL = (base_url()."paiement/paiement_echec");
$i=0;
$total_amount=0;
$str = "&METHOD=SetExpressCheckout
&RETURNURL=$returnURL
&CANCELURL=$cancelURL
&L_PAYMENTREQUEST_0_NAME0=$product_name
&L_PAYMENTREQUEST_0_NUMBER0=$qty
&L_PAYMENTREQUEST_0_AMT0=$price
&L_PAYMENTREQUEST_0_DESC0=$product_name
&PAYMENTREQUEST_0_AMT=$price
&PAYMENTREQUEST_0_PAYMENTACTION=$paymentType
&PAYMENTREQUEST_0_CURRENCYCODE=$currencyID";
$nvpStr=$nvpStr.$str;
$httpParsedResponseAr = $this->PPHttpPost('SetExpressCheckout', $nvpStr);
if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"]))
{
// Redirect to paypal.com.
$token = urldecode($httpParsedResponseAr["TOKEN"]);
$payPalURL = "https://www.$environment.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));
}
}
/** SetExpressCheckout NVP example; last modified 08MAY23.
*
* Initiate an Express Checkout transaction.
*/
/**
* 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
*/
private function PPHttpPost($methodName_, $nvpStr_) {
//global $environment;
$environment = 'sandbox'; // or 'beta-sandbox' or 'live'
// Set up your API credentials, PayPal end point, and API version.
$API_UserName = urlencode('saswat_1360720799_biz_api1.gmail.com');
$API_Password = urlencode('1360720821');
$API_Signature = urlencode('ApDCeFez-N1Gd1-O3ubTGdpyiow4AlNlRemm8XJFcbsA.WbSMtlMSqHf');
$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;
}
I have three accounts in the Paypal sandbox: two business and one personal. All of my Paypal accounts have USD as default currency.
In the above code I was using EUR as a currency.
When I am carrying out transaction, if I am paying from my personal (buyer) account in EUR, then my buyer account is getting money deducted (equivalent amount of USD is getting subtracted from my buyer account). This is totally fine, there is no issue with that.
The problem is that no amount is getting added to my business or (seller) account.
I found a post on Stack Overflow that reads:
if the currencycode of the transaction and the seller account doesnt
match, then money doesnt get aded to sellers account
I changed the euro to USD, (since my sandbox seller test account is in USD) and found out that, after converting it into USD, then my money is getting added to my seller account.
Is this a problem with the sandbox only, or does it apply to live paypal as well?
I have a site where buyers can pay in GBP, EUR, MYN, SGD, AUD.
If the transaction needs to be carried out in particular currency, that is the currency set as per the seller account, then there's no need to use different currencies.
Since the currencyCode which is passed in SetExpressCheckOut should match with the DoExpressCheckout, and as I have faced problem, currencyCode needs to be same as that of sandbox seller account, so even if buyers are selecting GBP, I have to send it to SetExpressCheckout as the currencyCode of the seller account.
You should add the currencies you would like to receive payments in through the control panel of your business account in question.
Go to Profile -> My Settings -> Financial Information tab and Currency Balances. From there select a currency and add it to the list. Your received payments are then kept in the respective currency balance they were made until you convert them to whatever you want.
By default, transactions that take place in a currency you don't hold are held until you decide what to do with them. If you log into the seller account in question, you should see the transaction listed under your history. You should be able to accept it or deny it from there.
There are two ways around this:
Add Euros as a currency balance to your seller's account, as Alderis noted.
Have all transactions that take place in a currency you don't hold automatically accepted and converted to USD. To do this, log into the seller's account, click on Profile, then click on Payment Receiving Preferences (in the Selling preferences column), then set Block payments sent to me in a currency I do not hold to No, accept them and convert them to U.S. Dollars, then click Save.
Related
I am using Codeigniter to integrate the PayPal payment gateway on my website.
//This is my buy method
public function buy($id){
$course = $this->course_model->fetch_course_details_for_buy($id);
$returnURL = base_url().'paypal/success'; //payment success url
$cancelURL = base_url().'paypal/cancel'; //payment cancel url
$notifyURL = base_url().'paypal/ipn'; //ipn url
$userID = $this->session->userdata('student_id'); //current user id
$_SESSION['course_id'] = $course->course_id;
$logo = base_url().'assets/images/test-logo.png';
$this->paypal_lib->add_field('return', $returnURL);
$this->paypal_lib->add_field('cancel_return', $cancelURL);
$this->paypal_lib->add_field('notify_url', $notifyURL);
$this->paypal_lib->add_field('item_name', $course->title);
$this->paypal_lib->add_field('custom', $userID);
$this->paypal_lib->add_field('item_number', $course->course_id);
$this->paypal_lib->add_field('amount', $course->amount);
$this->paypal_lib->image($logo);
$this->paypal_lib->paypal_auto_form();
}
This is my PayPal's class method of success
function success(){
//get the transaction data
$paypalInfo = $this->input->get();
$data['item_number'] = $paypalInfo['item_number'];
$data['txn_id'] = $paypalInfo["tx"];
$data['payment_amt'] = $paypalInfo["amt"];
$data['currency_code'] = $paypalInfo["cc"];
$data['status'] = $paypalInfo["st"];
//pass the transaction data to view
$this->load->view('paypal/success', $data);
}
This is my IPN method
function ipn(){
//paypal return transaction details array
$paypalInfo = $this->input->post();
$data['user_id'] = $paypalInfo['custom'];
$data['product_id'] = $paypalInfo["item_number"];
$data['txn_id'] = $paypalInfo["txn_id"];
$data['payment_gross'] = $paypalInfo["mc_gross"];
$data['currency_code'] = $paypalInfo["mc_currency"];
$data['payer_email'] = $paypalInfo["payer_email"];
$data['payment_status'] = $paypalInfo["payment_status"];
$paypalURL = $this->paypal_lib->paypal_url;
$result = $this->paypal_lib->curlPost($paypalURL,$paypalInfo);
//check whether the payment is verified
if(preg_match("/VERIFIED/i",$result)){
//insert the transaction data into the database
$this->product->insertTransaction($data);
}
}
My payment is successful done from the sandbox account. But When I click the return to merchant button after payment it's throwing error of undefined indexes as mention in the success method. I apply first a time payment gateway and don't know what is missing in my code. Any help is appreciable.
You should log what $paypalInfo contains.
If you have enabled PDT, information may be coming as a POST rather than a GET.
In any case, make your code be able to check for and handle the missing data/indices or put it in a try/catch equivalent; it should not error.
By clicking verify button I want the status of payment to change from pending to verified, then the pending amount (in payments table) to sum up with the wallet balance amount in users table and the final balance updated in users table using Laravel. This is my controller. Please help
public function verify_payment($user_id,$payment_data,$id){
$wallet = Mpesa::findOrFail($id);
$wallet->status = 'verified';
if($wallet->save()){
flash(__('Payment has been approved successfully'))->success();
return redirect()->route('all.payments');
}
$top_up = User::findOrFail($user_id);
$top_up->amount = $payment_data['amount'];
$top_up->balance = $top_up->balance + $payment_data['amount'];
$top_up->save();
flash(__('Something went wrong'))->error();
return back();
}
public function verify_payment($user_id,$payment_data,$id){
$wallet = Mpesa::findOrFail($id);
$wallet->status = 'verified';
if($wallet->save()){
flash(__('Payment has been approved successfully'))->success();
}
$top_up = User::findOrFail($user_id);
$top_up->amount = $payment_data['amount'];
$top_up->balance = $top_up->balance + $payment_data['amount'];
$top_up->save();
flash(__('Something went wrong'))->error();
return redirect()->route('all.payments');
}
I'm currently integrating the paypal recurring payment process in my website. i used this code
function process()
{
include_once("config.php");
include_once("paypal.class.php");
if($_POST) //Post Data received from product list page.
{
//Mainly we need 4 variables from an item, Item Name, Item Price, Item Number and Item Quantity.
$ItemName = $_POST["itemname"]; //Item Name
$ItemPrice = $_POST["itemprice"]; //Item Price
$ItemNumber = $_POST["itemnumber"]; //Item Number
$ItemQty = $_POST["itemQty"]; // Item Quantity
$ItemTotalPrice = ($ItemPrice*$ItemQty); //(Item Price x Quantity = Total) Get total amount of product;
//Data to be sent to paypal
$padata = '&CURRENCYCODE='.urlencode($PayPalCurrencyCode).
'&PAYMENTACTION=Sale'.
'&ALLOWNOTE=1'.
'&PAYMENTREQUEST_0_CURRENCYCODE='.urlencode($PayPalCurrencyCode).
'&PAYMENTREQUEST_0_AMT='.urlencode($ItemTotalPrice).
'&PAYMENTREQUEST_0_ITEMAMT='.urlencode($ItemTotalPrice).
'&L_PAYMENTREQUEST_0_QTY0='. urlencode($ItemQty).
'&L_PAYMENTREQUEST_0_AMT0='.urlencode($ItemPrice).
'&L_PAYMENTREQUEST_0_NAME0='.urlencode($ItemName).
'&L_PAYMENTREQUEST_0_NUMBER0='.urlencode($ItemNumber).
'&AMT='.urlencode($ItemTotalPrice).
'&L_BILLINGTYPE0='.urlencode('RecurringPayments').
'&L_BILLINGAGREEMENTDESCRIPTION0='.urlencode('message plan').
'&RETURNURL='.urlencode($PayPalReturnURL ).
'&CANCELURL='.urlencode($PayPalCancelURL);
//We need to execute the "SetExpressCheckOut" method to obtain paypal token
$paypal= new MyPayPal();
$httpParsedResponseAr = $paypal->PPHttpPost('SetExpressCheckout', $padata, $PayPalApiUsername, $PayPalApiPassword, $PayPalApiSignature, $PayPalMode);
//Respond according to message we receive from Paypal
if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"]))
{
// If successful set some session variable we need later when user is redirected back to page from paypal.
$_SESSION['itemprice'] = $ItemPrice;
$_SESSION['totalamount'] = $ItemTotalPrice;
$_SESSION['itemName'] = $ItemName;
$_SESSION['itemNo'] = $ItemNumber;
$_SESSION['itemQTY'] = $ItemQty;
if($PayPalMode=='sandbox')
{
$paypalmode = '.sandbox';
}
else
{
$paypalmode = '';
}
//Redirect user to PayPal store with Token received.
$paypalurl ='https://www'.$paypalmode.'.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token='.$httpParsedResponseAr["TOKEN"].'';
header('Location: '.$paypalurl);
}else{
//Show error message
echo '<div style="color:red"><b>Error : </b>'.urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]).'</div>';
echo '<pre>';
print_r($httpParsedResponseAr);
echo '</pre>';
}
}
//Paypal redirects back to this page using ReturnURL, We should receive TOKEN and Payer ID
if(isset($_GET["token"]) && isset($_GET["PayerID"]))
{
//we will be using these two variables to execute the "DoExpressCheckoutPayment"
//Note: we haven't received any payment yet.
$token = $_GET["token"];
$playerid = $_GET["PayerID"];
//get session variables
$ItemPrice = $_SESSION['itemprice'];
$ItemTotalPrice = $_SESSION['totalamount'];
$ItemName = $_SESSION['itemName'];
$ItemNumber = $_SESSION['itemNo'];
$ItemQTY =$_SESSION['itemQTY'];
$padata = '&TOKEN='.urlencode($token).
'&PAYERID='.urlencode($playerid).
'&PAYMENTACTION='.urlencode("SALE").
'&AMT='.urlencode($ItemTotalPrice).
'&CURRENCYCODE='.urlencode($PayPalCurrencyCode).
'&NOTIFYURL='.urlencode('http://mywebiste.com/listner');
//We need to execute the "DoExpressCheckoutPayment" at this point to Receive payment from user.
$paypal= new MyPayPal();
$httpParsedResponseAr = $paypal->PPHttpPost('DoExpressCheckoutPayment', $padata, $PayPalApiUsername, $PayPalApiPassword, $PayPalApiSignature, $PayPalMode);
//Check if everything went ok..
if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"]))
{
echo '<h2>Success</h2>';
echo 'Your Transaction ID :'.urldecode($httpParsedResponseAr["TRANSACTIONID"]);
/*
//Sometimes Payment are kept pending even when transaction is complete.
//May be because of Currency change, or user choose to review each payment etc.
//hence we need to notify user about it and ask him manually approve the transiction
*/
if('Completed' == $httpParsedResponseAr["PAYMENTSTATUS"])
{
echo '<div style="color:green">Payment Received! Your product will be sent to you very soon!</div>';
}
elseif('Pending' == $httpParsedResponseAr["PAYMENTSTATUS"])
{
echo '<div style="color:red">Transaction Complete, but payment is still pending! You need to manually authorize this payment in your <a target="_new" href="http://www.paypal.com">Paypal Account</a></div>';
}
echo '<br /><b>Stuff to store in database :</b><br /><pre>';
$transactionID = urlencode($httpParsedResponseAr["TRANSACTIONID"]);
$nvpStr = "&TRANSACTIONID=".$transactionID;
$paypal= new MyPayPal();
$httpParsedResponseAr = $paypal->PPHttpPost('GetTransactionDetails', $nvpStr, $PayPalApiUsername, $PayPalApiPassword, $PayPalApiSignature, $PayPalMode);
if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
$nvpstr="&TOKEN=".$_GET['token'];
$nvpstr.="&BILLINGPERIOD=Month";
$nvpstr.="&BILLINGFREQUENCY=1";
$nvpstr.="&AMT=1";
$nvpstr.="&CURRENCYCODE=USD";
$nvpstr.="&COUNTRYCODE=US";
$nvpstr.="&PAYERID=".$httpParsedResponseAr['PAYERID'];
$nvpstr.="&PROFILESTARTDATE=".date('Y-m-d');
$recurr = $paypal->PPHttpPost('CreateRecurringPaymentsProfile',$nvpStr,$PayPalApiUsername, $PayPalApiPassword, $PayPalApiSignature, $PayPalMode);
echo '<pre>';
print_r($httpParsedResponseAr);
echo '</pre>';
print_r($recurr);
} else {
echo '<div style="color:red"><b>GetTransactionDetails failed:</b>'.urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]).'</div>';
echo '<pre>';
print_r($httpParsedResponseAr);
echo '</pre>';
}
}else{
echo '<div style="color:red"><b>Error : </b>'.urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]).'</div>';
echo '<pre>';
print_r($httpParsedResponseAr);
echo '</pre>';
}
}
}
i am getting token and payer id etc . its all working fine. but when i try to create recurring profile iam getting this response
Array
(
[TIMESTAMP] => 2013%2d03%2d18T05%3a32%3a06Z
[CORRELATIONID] => 912b6004f40bb
[ACK] => Failure
[VERSION] => 76%2e0
[BUILD] => 5294323
[L_ERRORCODE0] => 11585
[L_ERRORCODE1] => 11518
[L_ERRORCODE2] => 11516
[L_ERRORCODE3] => 11519
[L_ERRORCODE4] => 11549
[L_SHORTMESSAGE0] => Missing%20Token%20or%20payment%20source
[L_SHORTMESSAGE1] => Invalid%20billing%20period%2e
[L_SHORTMESSAGE2] => Invalid%20billing%20frequency
[L_SHORTMESSAGE3] => Invalid%20amount
[L_SHORTMESSAGE4] => Start%20Date%20is%20required
[L_LONGMESSAGE0] => Missing%20Token%20or%20buyer%20credit%20card
[L_LONGMESSAGE1] => Billing%20period%20must%20be%20one%20of%20Day%2c%20Week%2c%20SemiMonth%2c%20or%20Year
[L_LONGMESSAGE2] => Billing%20frequency%20must%20be%20%3e%200%20and%20be%20less%20than%20or%20equal%20to%20one%20year
[L_LONGMESSAGE3] => Bill%20amount%20must%20be%20greater%20than%200
[L_LONGMESSAGE4] => Subscription%20start%20date%20is%20required
[L_SEVERITYCODE0] => Error
[L_SEVERITYCODE1] => Error
[L_SEVERITYCODE2] => Error
[L_SEVERITYCODE3] => Error
[L_SEVERITYCODE4] => Error
)
i dont know where i did wrong in this.
thank you.
Your request is missing a bunch of parameters which are required to create a recurring payment profile. Please refer to https://www.x.com/developers/paypal/documentation-tools/express-checkout/integration-guide/ECRecurringPayments.
I think the procedure is wrong: the second call should be a GetExpressCheckoutDetails to retrive the PAYERID in order to be able to do a CreateRecurringPaymentsProfile.
Just follow this tutorial step by step:
https://www.x.com/developers/paypal/documentation-tools/express-checkout/how-to/ht_ec-recurringPaymentProfile-curl-etc
I am trying to create a new shipping method. This method allows users to COLLECT items from a paticular warehouse. So not much involved really.
I have followed a couple of tuts online, and have my module built and installed. It is working on the backend, i can enAble it, and set various values.
When i use the frontend checkout....or even use the following code:
Mage::getSingleton('shipping/config')->getAllCarriers();
I do not get the new shipping method name output.
The message i get on the frontend checkout is:
Sorry, no quotes are available for this order at this time.
Even though i have other shipping methods enabled.
I have another extension in use (regarding stock located in several warehouses). As part of this extension, it lists available shipping options...so that i can assign specific options to a specific warehouse. My new shipping method is not listed that shipping options list.
I seem to have everything required. My other extension is not picking up the method...so must be missing something.
Also, given i am getting no shipping options on frontend...confusing.
I was creating a complex shipping method...rather than a copy of the free shipping method. Turns out i actually needed a copy of the free shipping method, so made my life easier...
This was easier than i thought it would be.
Dont want to post all my code (you will also need a config.xml and system.xml file) but heres my carrier model logic file:
class Myco_Clickcollectshipping_Model_Carrier_Mymethod extends Mage_Shipping_Model_Carrier_Abstract {
protected $_code = 'mymethod ';
public function collectRates(Mage_Shipping_Model_Rate_Request $request)
{
if (!$this->getConfigFlag('active')) {
return false;
}
$freeBoxes = 0;
if ($request->getAllItems()) {
foreach ($request->getAllItems() as $item) {
if ($item->getFreeShipping() && !$item->getProduct()->isVirtual()) {
$freeBoxes+=$item->getQty();
}
}
}
$this->setFreeBoxes($freeBoxes);
$result = Mage::getModel('shipping/rate_result');
if ($this->getConfigData('type') == 'O') { // per order
$shippingPrice = $this->getConfigData('price');
} elseif ($this->getConfigData('type') == 'I') { // per item
$shippingPrice = ($request->getPackageQty() * $this->getConfigData('price')) - ($this->getFreeBoxes() * $this->getConfigData('price'));
} else {
$shippingPrice = false;
}
$shippingPrice = $this->getFinalPriceWithHandlingFee($shippingPrice);
if ($shippingPrice !== false) {
$method = Mage::getModel('shipping/rate_result_method');
$method->setCarrier('mymethod ');
$method->setCarrierTitle($this->getConfigData('title'));
$method->setMethod('mymethod ');
$method->setMethodTitle($this->getConfigData('name'));
if ($request->getFreeShipping() === true || $request->getPackageQty() == $this->getFreeBoxes()) {
$shippingPrice = '0.00';
}
$method->setPrice($shippingPrice);
$method->setCost($shippingPrice);
$result->append($method);
}
return $result;
}
public function getAllowedMethods()
{
return array('mymethod ' => $this->getConfigData('name'));
}
}
I am trying to find a way to keep connected with the Twitter API once authorised using OAuth but am having problems.
I get "Invalid / expired Token" when trying to connect to Twitter API using a saved Oauth token in a session or database.
Is there a way to do this? I dont want the users of my App to have to login via Twitter every time. Surely once they have authorised my App once, that should be enough?
$consumer_key = 'consumerkey';
$consumer_secret = 'consumersecret';
$twitterObj = new EpiTwitter($consumer_key, $consumer_secret);
if (isset($_GET['oauth_token'])){
$oauth_token = $_GET['oauth_token'];
} else if ($_SESSION['oauth_token']){
$oauth_token = $_SESSION['oauth_token'];
echo $_SESSION['oauth_token'];
} else {
//see if authorisation already set up in DB
$query = mysql_query("SELECT oauth_token FROM PingSocialMediaUsers WHERE oauth_provider = 'twitter' AND clientID = '$clientID'");
$result = mysql_fetch_row($query);
$oauth_token = $result[0];
}
if($oauth_token == ''){
$url = $twitterObj->getAuthorizationUrl();
$twitter_login = $url;
} else {
$twitterObj->setToken($oauth_token);
$token = $twitterObj->getAccessToken();
$twitterObj->setToken($token->oauth_token, $token->oauth_token_secret);
$_SESSION['oauth_token'] = $token->oauth_token;
$_SESSION['oauth_secret'] = $token->oauth_token_secret;
$twitterInfo= $twitterObj->get_accountVerify_credentials();
$twitterInfo->response;
echo $twitterInfo->response['error'];
//echo '<pre>';
//print_r($twitterInfo);
$id = $twitterInfo->id;
$username = $twitterInfo->screen_name;
//add to details database
//find the user by ID
if ($id != ''){
$query = mysql_query("SELECT * FROM PingSocialMediaUsers WHERE oauth_provider = 'twitter' AND oauth_uid = '$id'");
$result = mysql_fetch_array($query);
// If does not exist add to database
if(empty($result)){
$query = mysql_query("INSERT INTO PingSocialMediaUsers (oauth_provider, oauth_uid, username, oauth_token, oauth_secret) VALUES ('twitter', {$id}, '{$username}', '{$_SESSION['oauth_token']}', '{$_SESSION['oauth_secret']}')");
$query = mysql_query("SELECT * FROM PingSocialMediaUsers WHERE id = " . mysql_insert_id());
$result = mysql_fetch_array($query);
} else {
//update the tokens
$query = mysql_query("UPDATE PingSocialMediaUsers SET oauth_token = '{$_SESSION['oauth_token']}', oauth_secret = '{$_SESSION['oauth_secret']}' WHERE oauth_provider = 'twitter' AND oauth_uid = {$id}");
}
$_SESSION['id'] = $result['id'];
$_SESSION['username'] = $result['username'];
$_SESSION['oauth_uid'] = $result['oauth_uid'];
$_SESSION['oauth_provider'] = $result['oauth_provider'];
$_SESSION['oauth_token'] = $result['oauth_token'];
$_SESSION['oauth_secret'] = $result['oauth_secret'];
}
$twitterAuth = TRUE;
}
I believe you are talking about access_token which you will get from the twitter as last part of OAuth handshaking after which you can go to access there services on user behalf.
Here is what they are saying in there official developer page
We do not currently expire access tokens.
Your access token will be invalid if a user explicitly
rejects your application from their settings or if a Twitter admin suspends
your application. If your application is suspended there will be
a note on your application page saying that it has been suspended.
So you can very well store that token in your database and can always use at later stage.
here is the reference to there API page
Twitter OAuth FAQ
So i suggest you to make sure that you are not changing any application setting and you are getting a valid access_token from session/database