Catching specific error on Stripe PHP to display custom message - php

I have a Stripe payment gateway with the credit card details to input.
It is working fine but there is one error message that I don't like but I am not advanced enough in PHP to fix this.
function stripeResponseHandler(status, response) {
if (response.error) {
// Enable the submit button
$('#payBtn').removeAttr("disabled");
// Display the errors on the form
$(".payment-status").html('<p>'+response.error.message+'</p>');
} else {
var form$ = $("#paymentFrm");
// Get token id
var token = response.id;
// Insert the token into the form
form$.append("<input type='hidden' name='stripeToken' value='" + token + "' />");
// Submit form to the server
form$.get(0).submit();
}
}
This is catching the errors and displaying response.error.message
These errors are great with the exception of if you write a bunch of numbers into the expiry instead of mm/yy.
the error returned is:
The 'exp_year' parameter should be an integer (instead, is
20undefined).
I don't know enough about this language but I want to catch this specific error and just say something like "The expiry date is incorrect, please enter as MM/YY"
I tried doing an if statement to read response.error.message but I didn't know how to format well. I tried also finding an error.code instead of message to use however the code invalid_number comes up but if I use this in an IF statement it refers to all invalid numbers of all fields (including card number) so my expiry statement is obviously incorrect in this situation!

That's actually JavaScript, not PHP. You probably have this code in a PHP file somewhere which you are rendering on the server, but this is JavaScript code which will run on the client.
It sounds like you are using Stripe.js v2 for your integration. This is discouraged as Stripe.js v2 is deprecated. Instead you should use Stripe Elements, which will handle all the validation you are after here for you.
The above link shows you how to create payments with PaymentIntents, the newest and most feature rich API from Stripe. If you however want to continue using the Charge API, you can see how to use it with Elements here: https://stripe.com/docs/payments/accept-a-payment-charges

Related

Symfony 5 - How to register a card with mangopay php sdk

I'm trying to register a credit card with MangoPay.
On my service file, I've created a public function to register the card, using the package mangopay/php-sdk-v2.
// ApiUser.php
public function Registration($UserId)
{
$CardRegistration = new \MangoPay\CardRegistration();
$CardRegistration->UserId = $UserId;
$CardRegistration->Currency = "EUR";
$CardRegistration->CardType = "CB_VISA_MASTERCARD";
$Result = $this->mangoPayApi->CardRegistrations->Create($CardRegistration);
$this->registration = $Result;
return $Result;
}
Its result will be an object, within three main keys: AccessKey, PreRegistrationData and CardRegistrationURL.
{
[...]
"AccessKey": "1X0m87dmM2LiwFgxPLBJ",
"PreregistrationData": "YkgVxL1yNY4ZOfKtqEew_ZzBSGg0ie3ghohlFhb-37oidM_c0HMmR9H0WvKWb8pa2ddFLVXdicolcUIkv_kKEA",
"CardRegistrationURL": "https://homologation-webpayment.payline.com/webpayment/getToken",
[...]
}
While trying with PostMan, I just have to take the URL in the CardRegistrationURL and, in its body, add: data with the PreRegistrationData, accessKeyRef with AccessKey and cardNumber, cardExpirationDate and cardCvx (the Content-Type is x-www-urlencoded)
Once clicked on the Send button, its response will be a long string that start by data=.
With that string, I can finally update the CardRegistration object and give the user on MangoPay the credit card.
The problem is that while coding, I can't find a way to get the response of the CardRegistrationURL.
I've tried to do a POST while using the http-client package, but the response given is an object. I've checked if it was present within the object, but it was not.
I've also tried to check this: https://github.com/Mangopay/mangopay2-php-sdk/blob/master/demos/paymentDirect/payment.php and tried to emulate it, but without success.
Warning: You don't have to collect card details on your server side, you have to create an HTML form like this
<form action="CardRegistrationURL here">
// inputs for cardNumber, expiration date ...
// You can add an input to redirect your user after card registration, ex:
// <input name="returnUrl" value="https://youwebsite.com">
</form>
You user will be redirected to MangoPay server then come back to your website. When the user comes back to your website use the request data to update card registration and do related things.
The documentation is not very clear, don't hesitate to ask MangoPay support.

Firebase: How can I use the same custom token for authentication from different environments (JS and iOS)?

I am trying to use the same token(server-side generated - PHP) to auth the user in web(JS) and iOS app(SDK). These are the steps I do to auth a user:
generate a JWT token:
I am using using the recommended lib https://github.com/firebase/firebase-token-generator-php:
$generator = new TokenGenerator($firebaseSecret);
$token = $generator->setOption('expires', strtotime('+1 day'))
->setData(array('uid' => $user->id))
->create();
use the token to auth the user via Javascript:
ref.authWithCustomToken(token, registerHandler);
registerHandler: function(error, authData)
{
if (error) {
console.log("Login Failed!", error);
} else {
console.log("Login Success!");
}
All works correctly, the FIRST time, the user is logged in and ready to roll.(Firebase session set to 1 year)
However:
if I logout and use the same method to login again, with the same token, I get the following error: "INVALID_TOKEN: Failed to validate MAC.". If I use another fresh token all works again.
If I send the token(unused) to the iOS app I am also working with, I get the above error all the time.
Can somebody share some light into this situation ? Any help will be greatly appreciated.
I found the problem myself, in the end. I'll post this here so that future devs avoid the issue I ran into.
Be always careful about where you store your data. My tokens were stored into the DB, in a varchar type column, but they were bigger then 256 chars, so they were not saved properly. After changing the column type everything worked flawlessly.

NetSuite - Accept webhook POST data to create record using ASP.NET or PHP

We have a lead generation form at Unbounce.com that is capturing lead data. They have a webhook that can transmit the data via POST to any URL that can accept it and process it. We would like to build a page that accepts this data and processes it in NetSuite (probably via the SuiteScript API's, but not sure). http://www.netsuite.com/portal/developers/resources/APIs/Dynamic%20HTML/SuiteScriptAPI/MS_SuiteScriptAPI_WebWorks.1.1.html
Variables To Get From POST
The following variables will be passed from the form in this order to the NetSuite processing page:
prog
first_name
last_name
email
parents_email
i_am_a_
phone_number
parents_phone_number
comment
Additional Page Variables To Attempt To Grab
Reading the example code below it looks like we can grab and store a few additional items. If so it would be good to store them in the CRM in the visitors profile for future reference:
page_id
page_url
variant
REQUEST FOR SAMPLE CODE
Since our preferred development enviornment is ASP.NET, can you provide sample code that can accept POST data from a webhook and create a new CRM record within our NetSuite account?
SAMPLE PHP CODE TO GET DATA FROM POST
Example code can be found at http://support.unbounce.com/entries/307685-how-does-the-form-webhook-work
If this were a PHP page you would grab the variables in the following fashion:
// This is a sample PHP script that demonstrates accepting a POST from the
// Unbounce form submission webhook, and then sending an email notification.
function stripslashes_deep($value) {
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
// First, grab the form data. Some things to note:
// 1. PHP replaces the '.' in 'data.json' with an underscore.
// 2. Your fields names will appear in the JSON data in all lower-case,
// with underscores for spaces.
// 3. We need to handle the case where PHP's 'magic_quotes_gpc' option
// is enabled and automatically escapes quotation marks.
if (get_magic_quotes_gpc()) {
$unescaped_post_data = stripslashes_deep($_POST);
} else {
$unescaped_post_data = $_POST;
}
$form_data = json_decode($unescaped_post_data['data_json']);
// If your form data has an 'Email Address' field, here's how you extract it:
$email_address = $form_data->email_address[0];
// Grab the remaining page data...
$page_id = $_POST['page_id'];
$page_url = $_POST['page_url'];
$variant = $_POST['variant'];
However I don't know the code to use to get it into NetSuite. After reviewing the SuiteScript API from NetSuite it looks like we should be using nlobjRequest or nlapiRequestURL, but I have zero knowledge on how to integrate this with the sample PHP page above.
Thanks for all your help for a NetSuite noob.
You would need to create a RESTlet in NetSuite. You can find the documentation on NetSuite's Help Guide. RESTlets are part of NetSuite's SuiteScript API. They are written as JavaScript (of course, using the APIs provided by NetSuite).
When you create a RESTlet, you will be given a URL. Which you should use for your Unbounce web hook. Your RESTlet should parse the JSON data being passed by Unbounce.com.

Why is this jquery script not working?

So I have a website that allows a user to enter a link and it then extracts information and places it into a list for them.
Now everything was working fine until yesterday when my web hosting partner done some upgrades. I know that mysql & php have been upgrading but am not sure what else.
First I had issues that I could not log into the DB (had to drop and recreate users).
Then an issue with PHP serialise for JSON (needed a code change).
Then a 412 invalid precondition error (needed a special rule set up by the hosting partner).
And now last of all a jquery script has stopped working. But I have no idea as to why. It worked before, but maybe that was luck (I am not so experienced in this).
Anyway, what happens is
User enters a link.
jquery calls a link which returns JSON.
The JSON is parsed and the web page updated with the results.
The user clicks on save and the data is entered into the DB.
using firebug and placing alerts in my javascript then I can see that Step 1, step 2 work fine. The JSON returned is valid (I have verfied it with JSONlint) but step 3 does not work. My script is below;
function getURLData(form)
{
var listid = $('input#listid').val();
var memberid = $('input#memberid').val();
var link = $('input#link').val();
var sendstr = "http://www.wishindex.com/ajax.php?link=\"" + link + "\"&listid=" + listid + "&memberid=" + memberid;
alert(sendstr);
$.getJSON(sendstr,function(result)
{
alert('inside');
if(result['Itemname'] != "")
{
alert('inside2');
$('#itemname').val(result['Itemname']);
$('#itemname').attr('readonly', 'true');
$('#desc').val(result['Description']);
$('#category').val(result['Category']);
$('#category').attr('readonly', 'true');
$('#price').val(result['Price']);
$('#price').attr('readonly', 'true');
$('#choosepicture').attr('onclick', 'window.open(\'http://www.wishindex.com/picture.php?link=' + result['Link'] + '\')');
if (result['PictureLink'] != "")
{
$('#picturelink').val(result['PictureLink']);
$('#picturelink').attr('readonly', 'true');
}
else
$('#choosepicture').removeAttr('disabled');
$('#automatic').attr('value', 'true');
$('#currency').val(result['Currency']);
$('#currency').attr('readonly', 'true');
}
else
{
$('#automatic').attr('value', 'false');
$('#manual').html('Please enter details manually');
$('#choosepicture').removeAttr('disabled');
$('#choosepicture').attr('onclick', 'window.open(\'http://www.wishindex.com/picture.php?link=' + result['Link'] + '\')');
}
});
}
If I enable the alerts then I see the link called is correct, the JSON is valid (via firebug and calling the link manually) and that the alert('inside') & alert('inside2') are executed so it is reaching this segment of the code, but my html elements are not updated!
As I said, before the upgrade it was fine, but maybe I have done something wrong, so any help would be appreciated as I have spent hours on this and can't find the issue.
My JSON response;
[{"ID":"","MemberID":"24","Listid":"41","Itemname":"LEGO Star Wars 9489: Endor Rebel Trooper and Imperial Trooper","Description":null,"NumberDesired":null,"NumberPurchased":null,"Category":{"0":"TOYS_AND_GAMES"},"Link":"\"http:\/\/www.amazon.co.uk\/LEGO-Star-Wars-9489-Imperial\/dp\/B005KISGAI\/ref=pd_rhf_gw_shvl1\"","PictureLink":{"0":"http:\/\/ecx.images-amazon.com\/images\/I\/51fQnt%2BlppL._SL160_.jpg"},"Price":"9.89","Currency":"\u00a3","Priority":null,"SuggestedPurchaser":null,"ActualPurchaser":null,"PurchaseStatus":null,"Productid":"B005KISGAI","Site":"amazon.co.uk","DateAdded":null,"DatePurchased":null,"Domain":null,"Temp":["LEGO-Star-Wars-9489-Imperial","dp","B005KISGAI","ref=pd_rhf_gw_shvl1\""],"Error":"","Warning":null}]
You can call this to get a JSON result example
http://www.wishindex.com/ajax.php?link=%22http://www.amazon.co.uk/LEGO-Star-Wars-9489-Imperial/dp/B005KISGAI/ref=pd_rhf_gw_shvl1%22&listid=41&memberid=24
A working demo (as requested) can be found here;
http://www.wishindex.com/test_newitem.php?listid=41
To test;
Enter a product link from amazon.co.uk such as
http://www.amazon.co.uk/LEGO-Star-Wars-9489-Imperial/dp/B005KISGAI/ref=pd_rhf_gw_shvl1
into the link field
Click on get details and the rest of the fields should be populated
automatically, but t hey are not.
Your json is an object inside an array. so you should only be able to access the data like that: result[0]['Itemname'] or do result = result[0] before you access it.
So it reaches 'inside2' because result['Itemname'] is undefined which is != ""

how to : define and get a custom report from google analytics using gapi

I have a custom report called my-newsletters in Google analytics. I want to fetch this report with a php call to $ga->requestReportData(...) and then parse the response and format it up.
First I made an account to collect all my newsletter open and click hits - each time someone opens a newsletter or clicks on a link in the newsletter I capture that with a call to the __utm.gif on Google. That part is working and I include in the call ( in the Landing Page aka utmp parameter) some data such as the word 'open' and 'click' to distinguish the events and also some other data i hope to parse out later, plus i use the campaign field and maybe I should do something with the source field too - now I just dup the utmp field. So far that part seems to work.
Now I need help to define a report that will return that utmp and campaign field info and the number of hits each has taken, sorted by date of hit I guess. then i need to call that report from my php and then later parse it - the parsing part I'm not worried about yet.
PS: here is the code I use to generate the utm url
function getGoogleUtmUrl($source='Emails', $referer='opens', $estid='0',$mailid='0', $campaign){
$stat_id='MO-xxx31982-1';
$var_utmcs=urlencode( 'UTF-8');
$var_utmac = $stat_id;
$var_utmhn = 'mysite.com'; //enter your domain
$var_utmn = rand(1000000000,9999999999); //random request number
$var_cookie = rand(10000000,99999999); //random cookie number
$var_random = rand(1000000000,2147483647); //number under 2147483647
$var_today = time(); //today
$var_referer = $referer; //referer url
$utm_source = 'my_newsletter';
$utm_medium = 'Emails';
$utm_campaign = $campaign;//$_GET['url'];
$var_uservar = $estid.'_'.$mailid; //enter your own user defined variable
$var_utmp = 'mysite.com/newsletters/'.$referer.'/'.$estid.'/'.$mailid;//.$estid;//$_GET['url']; //this example adds a fake file request to the (fake) tracker directory (the image/pdf filename).
$urchinUrl1 = 'http://www.google-analytics.com/__utm.gif?utmwv=4.3&utmn='.$var_utmn.'&utmsr='.$referer.'&utmcs='.$var_utmcs.
'&utmul=en&utmje=0&utmfl=-&utmdt='.$utm_campaign.'&utmhn='.$var_utmhn.
'&utm_source='.$var_utmp.'&utm_medium='.$utm_medium.'&utm_campaign='.$utm_campaign.'&utmr='.$var_referer.
'&utmp='.$var_utmp.'&utmac='.$var_utmac.
'&utmcc=__utma%3D'.$var_cookie.'.'.$var_random.'.'.
$var_today.'.'.$var_today.'.'.$var_today.
'.2%3B%2B__utmb%3D'.$var_cookie.'%3B%2B__utmc%3D'.
$var_cookie.'%3B%2B__utmz%3D'.$var_cookie.'.'.$var_today.
'.2.2.utmccn%3D(direct)%7Cutmcsr%3D(direct)%7Cutmcmd%3D(none)%3B%2B__utmv%3D'.
$var_cookie.'.'.'%3B';
// Now fire off the HTTP request
echo "urchinURL1 == ".$urchinUrl1.' '.__FILE__.' '.__LINE__.'<br/>';
return $urchinUrl1;
seems like over kill to me but it works, I tried the code at https://developers.google.com/analytics/devguides/collection/other/mobileWebsites and it doesn't work - the opens and clicks do not register in analytics - at least not on the real time page.
Please help.
I suggest that you build your report query first, I recommend that you use Google Analytics Query Explorer for that.
And next use the reporting API from PHP to transpose the resulting query and extract the data from within your app.

Categories