WordPress: Store stripe info as user_meta - php

I'm using a Stripe webhook to store the dollar amount a customer is charged when they get charged in Stripe.
I've got the webhook working fine and can email out the charge amount but can't seem to store it in WordPress user_meta field.
Here's what my code looks like:
// Retrieve the request's body and parse it as JSON
$input = #file_get_contents("php://input");
$event_json = json_decode($input);
// Check against Stripe to confirm that the ID is valid
$event = \Stripe\Event::retrieve($event_json->id);
// If charge is successful, store in user meta
if (isset($event) && $event->type == "charge.succeeded") {
$amount = $event->data->object->amount / 100;
}
$payment_user_id = 9192321;
update_user_meta($payment_user_id, 'payment_history', $amount);
Is this because the json received from stripe is in a format that needs to be converted to something before I can store it? If I try to convert it to an integer using intval($amount) it just stores it as 0.
Thanks in advance!

Turns out I'm dumb and just needed to put the "update_user_meta" in the "if" statement.

Related

Magento Credit card number mismatch with credit card type exception

I am using stripe credit card payment method for website on my magento store and developing a mobile application. I am developing the api's using native magento api. Problem occurred on create order api, everything till adding payment for stripe credit card works fine but when I hit the create order api it throws the exception.
"Credit card number mismatch with credit card type exception"
Below is api code, Please share your knowledge for this issue. Thanks in advance.
$proxy = new SoapClient($this->_client); //soap handle
$sessionId = $proxy->login($this->_apiuser, $this->_apikey);
$resultCustomerAddresses = $proxy->call($sessionId, "cart_customer.addresses", array($shoppingCartId, $arrAddresses));
if ($resultCustomerAddresses != TRUE)
{
return json_encode(array('status' => 0, 'result' => array(),'message' => 'Error in saving address'));
}
$resultShippingMethods = $proxy->call($sessionId, "cart_shipping.list", array($shoppingCartId));
$randShippingMethodIndex = rand(0, count($resultShippingMethods)-1 );
$shippingMethod = $resultShippingMethods[$randShippingMethodIndex]["code"];
$resultShippingMethod = $proxy->call($sessionId, "cart_shipping.method", array($shoppingCartId, $shipping_method));
//$resultTotalOrder = $proxy->call($sessionId,'cart.totals',array($shoppingCartId));
$paymentMethod = array(
"method" => $payment_method
);
$resultPaymentMethod = $proxy->call($sessionId, "cart_payment.method", array($shoppingCartId, $payment_method));
$licenseForOrderCreation = null;
$resultOrderCreation = $proxy->call($sessionId,"cart.order",array($shoppingCartId, null, $licenseForOrderCreation));
I had the same problem and successfully solved it, see this answer: https://stackoverflow.com/a/41948259/1052675
Basically, you supply the card information before you save the quote. It will validate the card against regex patterns and configured purchase limits and make sure you can use the payment method.
Then it will forget the payment information.
So before you tell it to submit the order, you need to supply the card info again.
My solution was a custom endpoint for simplicity on the front end app and it enabled me to keep the card info in memory to re-save between saving the quote and submitting the order.

Stripe doubles anything

I am using a function I created that I have tried creating customers from, and creating charges from. For whatever reason it seems to be double charging in test mode (Not bringing into live mode under these conditions) and I'm trying to understand why. I had it going through a few functions so I made it all happen in one function to make sure that it had nothing to do with what I had made. I'm lost on why this is happening. I try to make charges from token, doubles in less than a second. I try to create a customer from token, doubles in less than a second. I am using Stripes latest stripe-php library.
public function invoice($invoice = null) {
//Provides billing info for invoice.ctp
$this->loadModel('Invoice');
$billingi = $this->Invoice->get($invoice, [
'contain' => ['Items'],
]);
$dollars = 0;
foreach ($billingi->items as $item) {
$dollars += $item->price;
}
$cents = bcmul($dollars, 100);
$price = floatval($cents);
if ($this->request->is('post')) {
$stripeToken = $this->request->data('stripeToken');
//Sets stripe API
\Stripe\Stripe::setApiKey("sk_test_QVYouMViTf1k3zfVu2VAyZge");
//Retrieves stripe token from stripe API
//$response = \Stripe\Token::retrieve($stripeToken);
\Stripe\Customer::create(array(
"description" => "Test customer",
"source" => $stripeToken // obtained with Stripe.js
));
$this->Flash->success(__('Thank you for your payment!'));
return $this->redirect(['action' => 'approved', $invoice]);
}
/*
if ($response && $this->checkExists($response->card->cvc_check, $response->card->address_zip_check) == true) {
$this->insertCharge($invoice, $response, $price);
} else {
//Throw error because cvc_check or zip came back null (doesn't exist)
}
}
*/
$this->set('billingi', $billingi);
$this->set('_serialize', ['billing']);
}
The reason why there are things commented out is because I wanted to test the function without it, but adding it back later when I understand what the issue is.
In your code, the only API request sent to Stripe is a customer creation request (\Stripe\Customer::create(...)).
This doesn't charge the user -- it merely validates the card from the token in the source parameter, and creates a persistent customer object that you can in turn use to create actual charges. This tutorial explains this flow.
There's nothing in your code that would cause the API request to be sent twice. It's very unlikely the issue is on Stripe's end. More likely, your code is being called twice for some reason that's not related to Stripe. You'd need to add traces to your code to figure out what exactly is being called in what order.

QUickbooks PHP SDK add invoice payment

I am trying to add payments to an invoice using the Quickbooks PHP SDK.
I can create customers, invoices, items, sales lines etc but I am a little stuck when it comes to the correct way to create and link a payment to an invoice.
This is what I have been trying:
$qbLinkedInvoice = new IPPLinkedTxn();
$qbLinkedInvoice->TxnId = 277; // the QB invoice ID
$qbLinkedInvoice->TxnType = 'Invoice';
$qbPayment = new IPPPayment();
$qbPayment->Amount = 10.0;
$qbPayment->CustomerRef = 164; // the QB cusotmer ID
$qbPayment->LinkedTxn = $qbLinkedInvoice;
$createdQbPayment = $this->dataService->Add($qbPayment);
But this just gives:
CheckNullResponseAndThrowException - Response Null or Empty
Which means something isn't formatted correctly. All the refs are correct (Exist in quickbooks, invoice, customer etc).
I have been sending up invoice line items by creating an IPPSalesItemLineDetail Object and then assigning that to the line and then assigning that to the invoice as the 'Line' array property at the point when the invoice is created in quickbooks but I can't seem to figure out how to send a payment and link that to an invoice.
There aren't any samples within the SDK that give me any clues either.
Any help would be greatly appreciated. Thanks.
Found how to do it. I was missing a IPPLine object to tie the Payment and LinkedTxn objects together. This is what worked:
$qbLinkedInvoice = new IPPLinkedTxn();
$qbLinkedInvoice->TxnId = 277;
$qbLinkedInvoice->TxnType = 'Invoice';
$qbLine = new IPPLine();
$qbLine->Amount = 10.0;
$qbLine->LinkedTxn = $qbLinkedInvoice;
$qbPayment = new IPPPayment();
$qbPayment->CustomerRef = 164;
$qbPayment->TotalAmt = 10.0;
$qbPayment->Line = [$qbLine];
$createdQbPayment = $this->dataService->Add($qbPayment);
Refer to the example here is you are using PHP official SDK, you can just pass an array to create Invoice and Payment:
https://github.com/intuit/QuickBooks-V3-PHP-SDK

Recurlyv3 API doesn't find any data associated with valid token id

This is the essential bit of PHP:
// Add subscription
$subscription = new Recurly_Subscription();
$subscription->plan_code = $planCode;
$subscription->currency = 'USD';
$subscription->quantity = 1;
if ($couponCode != "") { $subscription->coupon_code = $couponCode; }
$subscription->account = new Recurly_Account();
$subscription->account->account_code = $customerID;
$subscription->billing_info = new Recurly_BillingInfo();
$subscription->account->billing_info->token_id = $token;
$subscription->create();
When this code runs, $token has the tokenID created by an earlier call to recurly.token (...) with the billing info.
The account already exists on Recurly -- the account ID, first and last names, but no billing info. This is because we allow people to signup for a complimentary service before subscribing. So I want to create the subscription on the extant account. Initially, following the code examples, the create() call was subscription->account->create(). But that failed because the account existed already.
This sounds like an issue with the old PHP library, which did not support tokenization of billing information. An upgrade to the PHP client library should fix this issue.

Google checkout ,Database updation failed

I was download and edit the code for google checkout from google help.Here i specify murchent calculation url in my site.But that function donot work in my site.Here is my code
function UseCase3() {
//Create a new shopping cart object
$merchant_id = "xxxxxxxxxxxxx"; // Your Merchant ID
$merchant_key = "xxxxxxxxxxxxx";
$server_type = "sandbox";
$currency = "USD";
$cart = new GoogleCart($merchant_id, $merchant_key, $server_type, $currency);
// Add items to the cart
$item = new GoogleItem("MegaSound 2GB MP3 Player",
"Portable MP3 player - stores 500 songs", 1, 175.49);
$item->SetMerchantPrivateItemData("<color>blue</color><weight>3.2</weight>");
$cart->AddItem($item);
// Add merchant calculations options
$cart->SetMerchantCalculations(
"https://mysite.com/google2/demo/responsehandlerdemo.php",
"false", // merchant-calculated tax
"true", // accept-merchant-coupons
"true"); // accept-merchant-gift-certificates
// Add merchant-calculated-shipping option
$ship = new GoogleMerchantCalculatedShipping("2nd Day Air", // Shippping method
10.00); // Default, fallback price
$restriction = new GoogleShippingFilters();
$restriction->AddAllowedPostalArea("GB");
$restriction->AddAllowedPostalArea("US");
$restriction->SetAllowUsPoBox(false);
$ship->AddShippingRestrictions($restriction);
$address_filter = new GoogleShippingFilters();
$address_filter->AddAllowedPostalArea("GB");
$address_filter->AddAllowedPostalArea("US");
$address_filter->SetAllowUsPoBox(false);
$ship->AddAddressFilters($address_filter);
$cart->AddShipping($ship);
// Set default tax options
$tax_rule = new GoogleDefaultTaxRule(0.15);
$tax_rule->SetWorldArea(true);
$cart->AddDefaultTaxRules($tax_rule);
$cart->AddRoundingPolicy("UP", "TOTAL");
// Specify <edit-cart-url>
$cart->SetEditCartUrl("https://mysite.com/google/demo/cartdemo.php");
// Specify "Return to xyz" link
$cart->SetContinueShoppingUrl("https://mysite.com");
// Display XML data
// echo "<pre>";
// echo htmlentities($cart->GetXML());
// echo "</pre>";
// Display a disabled, small button
echo $cart->CheckoutButtonCode("SMALL");
}
Clarifications:
Merchant Calculations URL - as the name implies is the URL that Google will use to send a callback request for Shipping and Tax, promotions calculations. That is its purpose as documented in Merchant Calculations API. It is part of the Checkout Phase (sending information to Google for checkout).
API Callback URL - which is set in your account (Integration Settings) and not sent in any request (unlike merchant calculations url) and is the URL Google will send Notifications to as documented in Notification API. This is the API you need to implement in order to obtain data from Google (getting information from Google - e.g. after checkout)
So these urls/APIs serve different purposes.
Based on your comment:
I need to execute a php file after user pay through Google checkout
You need to implement the Notification API (the merchant calcuations url/api is not what you need).

Categories