if (!window.console === undefined || console.log === undefined) { console = { log: function (str) { } } } // Checks if an input has some characters in it and displays associated error if not function valNotEmpty(containerSelector) { var v = $(containerSelector).find('input').val(); var valid = v.trim().length > 0; $(containerSelector).find('.error').toggle(!valid); return valid; } function isPayingByCreditCard() { return $('input[name=billing_method][value=credit_card]')[0].checked; } function checkShippingAddress() { var firstNameValid = valNotEmpty('.first_name_container'); var lastNameValid = valNotEmpty('.last_name_container'); var address1Valid = valNotEmpty('.address1_container'); var address2Valid = true; // Not all addresses require apt / suite var cityValid = valNotEmpty('.city_container'); var stateValid = true; // Not all countries require state var zipValid = valNotEmpty('.zip_container'); // var whereHeardValid = valNotEmpty('.where_heard_container'); var whereHeardValid = true; return firstNameValid && lastNameValid && address1Valid && address2Valid && cityValid && stateValid && zipValid && whereHeardValid; } var emailContainerSelector = '.email_container'; // Only require email to be correct if the field is present. If it is not present, // it is because this is part of an A/B test that has already asked it in a previous step. function emailRequired() { return $(emailContainerSelector).length === 1; } function checkEmail() { if (emailRequired()) { var valid = $(emailContainerSelector).find('input').val().indexOf('@') != -1; $(emailContainerSelector).find('.error').toggle(!valid); return valid; } else { return true; } } function checkForm() { if (!isPayingByCreditCard()) { return true; } var shippingAddressValid = checkShippingAddress(); var emailValid = checkEmail(); var valid = shippingAddressValid && emailValid; return valid; // var paymentDetailsValid = checkPaymentDetails(); // return shippingAddressValid && paymentDetailsValid; } function showFieldsRelevantForBillingMethod() { $('#credit_card_details').toggle(isPayingByCreditCard()); $('.hide_for_paypal').toggle(isPayingByCreditCard()); } function redirectToPaypal(custom) { $('input[name=custom]').val(custom); $('form[id=pp]').submit(); } /* Gather fields from the form into an object that will be easy to serialize */ function subscriptionFieldsToObject(includeReplay) { var o = {}; var sel = '.order_form_container input, .order_form_container select'; $(sel).each(function (index, element) { if (element.id !== "") { o[element.id] = $(element).val(); } }); if (includeReplay) { o['LN3SODZF21N48LQRLWK351D9TUZG2A50VOYFCPDC1T1R7Z9T6L5B82N1D5ZE4C09PSVV794969Y4MI5VE4H1USZ2KUSQMHXLAD7B'] = JSON.stringify(replay); } o['AZKLMW0OI5BI2ZD51INMG2G3YR3HH7TTOFHI9ZC5Y9EAOGS3S1DPSYYCX0VCBR5582I8SMV7D3QHYXR4BI28AVX5NA8C4LM66KJF'] = isPayingByCreditCard() ? "credit card" : "paypal"; // User might have applied a coupon which affects the price o['coupon_code'] = $('.coupon_code').val(); return o; } function scrollToError() { var scrollTo = Math.max( $('.error:visible').offset().top - $(window).height()/2, 0 ); var diff = $('html').scrollTop() - $('.error:visible').offset().top; var delay = Math.abs(diff) * 0.5; $('html').animate({ scrollTop: scrollTo }, delay); } var submissionAttempted = false; function processCreditCardOrder() { var subscriptionFields = subscriptionFieldsToObject(true); var fields = { // Required attributes number: subscriptionFields[''], month: subscriptionFields[''], year: subscriptionFields[''], first_name: subscriptionFields['KNQYEY3HFISGL4ADOGKRUDNF1ZC92MYSRGS2J6CRMITGY7B07JK1REWM6SS1RBKHIE1HVWWTIJSWXJQ0QRHJCJTSWF6NWUP7X3EV'], last_name: subscriptionFields['2F80JZ59N0DV4CNJI7BK4XRI8ZKJKES409L5H5D32U9Q43BH5JVX18IF63SNZ3HV9WGYS0DUQ7OVAO7NJVFK8I4S4PG04LW46P7Q'], cvv: subscriptionFields[''], // where_heard: subscriptionFields['3NSKB2C1V6DPTM3HYSH8GBHNNPQ7BZT77JAOZ477FX2MHTHXOTEJOOZOSTAU4TXZN3N2RS3OXDDEWBN7P5RHWQUUSM2UVOQOMCK8'], // Optional attributes address1: subscriptionFields['TKPNK8SE4UY92BK4YQ42QLCBJC80XOPVWJM8SVFI1F9P8B3IPPBLEYISFKAWOHDPH603GY4CHS7HF95YBDDU693B6OSG00FVDMBB'], address2: subscriptionFields['2MF0SOJ54VL1CZGI4SV4YII5YCAJTXJXDVRWUFAZT1449NTU48XNOSL0TQZMIOXK4JE7E0P719VQH5925ZOKN0UXOROBCHRN5C1E'], city: subscriptionFields['FZSRJBIRWXI9GX9T42CROQ3WQNYW9QRD3VOZQMZ7YXODSWBFNMV7X7TCZTMIBPPE7CH6KP2WGS6FIATBKS3V4UCJ1MM3TQ4Q9XVA'], state: subscriptionFields['IYFQDHWHT4YO5NJN45HSX4UZDJ25HWV8A2YXOVF5M0021R8NO60Q1EJDXE5UJVV11MU0TQ1YTZEX05OK1J5MP730KNQ2TU0HN5IF'], postal_code: subscriptionFields[''], country: subscriptionFields[''] } // It still has the raw CC number in there, that's not good. Tokenize it. var tokenData = { name: $('#34NE4SHX731FG5USQXHLU62XBE1D3CKT362GCBNORU2ALWW21Q26KKJV9OHP3YL8UYFYPIZID05XHWS8CULGH5KE7KX869SDC4KQ').val() + ' ' + $('#849PMYIN1K6FCBCA00U6NXO312DT6AQ54NFHHVB5JB1MYAIU49PE4P8XS83MXBWZ0CXS9NMRAECPS81WC8AFKIS8U2FPUCYYW3VF').val(), address_country: $('BPQALHFO7WLIZM3M1OOJWOYX7Y1BUIWIEN4WWZGXXYD6QUW3AWOE1S3E87DF4G537IKWMVP3POS5YM5R6B71IFM0M3WZS7P3HUVV').val() }; // console.log(tokenData); stripe.createToken(card, tokenData).then(function(result) { if (result.error) { $('button').show(); $('.activity').hide(); alert(result.error.message); } else { subscriptionFields['K4SBKBM7Z69VWJTVB8F3GOCFHX6L4WHQWINWXRS43LWOQLEMWEGPURFU8QAJC0EJARZI2ZGLIMDV9L80ZCID88LRVZ4ISOE9F0OJ'] = result.token.id; // Send the token to your server // console.log(result.token); // stripeTokenHandler(result.token); $.post( '/subscribe_submit', {'fields_json' : JSON.stringify(subscriptionFields)}, function (response) { window.location.href = '/thanks'; }, dataType = "json" ); } }); } function processPayPalOrder() { var fields = subscriptionFieldsToObject(true); // Make sure if the user first selected credit card, filled in their number and // then switched back to PayPal that the CC data is not submitted. delete fields['']; delete fields['']; delete fields['']; delete fields['']; delete fields['']; delete fields['']; // Associate the form submission with the payment, so when returned from PayPal // we'll know what the payment is for. $.post( '/subscribe_submit', {'fields_json' : JSON.stringify(fields)}, function (response) { // redirectToPaypal(response.custom); redirectToPaypal($('input[id=form_key]').val()); }, dataType = "json" ); } // Helper for replacing actual credit card number and CVV with Xs function strToRepeatedX(str) { var xRepeated = ""; for (var i = 0; i < str.length; i++) { xRepeated += "X"; } return xRepeated; } // So I can see how the forms got filled later, keypress by keypress. var replay = []; var firstReplayStep = null; function recordReplayStep() { if (firstReplayStep === null) { firstReplayStep = Date.now(); } var fields = subscriptionFieldsToObject(false); delete fields.form_key; delete fields.coupon_code; delete fields.tier; // fields[''] = strToRepeatedX(fields['']); // fields[''] = strToRepeatedX(fields['']); replay.push({ elapsed: Date.now() - firstReplayStep, fields: fields }); } function applyCoupon() { $('.have_coupon_code').show(); $('.coupon_code_entry').hide(); var couponCode = $('.coupon_code').val(); // If you are reading the source, please use the "SOURCE" coupon to get as much off as any of the others here. var validCoupons = ['YEAR2018', 'TWOFORKS', 'INJECT', 'SOURCE', 'ALEK', '3OFF', 'TUBE', 'HACKERNEWS', 'ENTREPRENEUR', 'URBAN', 'BOND', 'ANSHIE', 'ARISU', 'ZOEY', 'CHIIKA', 'PHARAOH', 'SZU', 'IZABELA', 'WORLD', 'SARAH', 'BLACKNEO', 'MYCHAN', 'FUN', 'AANDK', 'MARACONT', 'WENDYLAND', 'LOWEN', 'JADE', 'FUINUR', 'HOLLY', 'CLARITA', 'AMBER', 'CORDEWA', 'MILLI', 'CRAFTY', 'MAI', 'GWENDY', 'SADIQ', 'FABIO', 'MIYU', 'REI', 'ZONA', 'NOMNOM', 'YUE', 'KYU', 'KAIGUYS']; var isValid = false; for (var i = 0; i < validCoupons.length; i++) { if (couponCode.toUpperCase().indexOf(validCoupons[i]) !== -1) { isValid = true; } } if (isValid) { $('.usdprice').text('$26'); $('input[name=a3]').val('26.00'); // Set PayPal price $('#coupon_code').val(couponCode); $('.coupon_applied').show(); $('.have_coupon_code').hide(); $('.coupon_line_item').show(); } else { alert("Sorry, that wasn't a valid coupon."); $('.coupon_code').val(''); } return false; } function initCouponFields() { $('.coupon_code_entry button').click(applyCoupon); $('.coupon_code_entry form').on('submit', applyCoupon); $('.have_coupon_code').click(function() { $('.have_coupon_code').hide(); $('.coupon_code_entry').show(); $('.coupon_code').focus(); }); }; function copyNameFromShippingToCard() { // If credit card name is empty but there is a name in shipping, use that by default var fieldsToCopy = ['.first_name_container', '.last_name_container']; fieldsToCopy.forEach(function (field) { var shipVal = $('#shipping_address ' + field + ' input').val(); var ccValSelector = '#credit_card_details ' + field + ' input'; if (shipVal && !$(ccValSelector).val()) { $(ccValSelector).val(shipVal); } }); } function initStripe() { stripe = Stripe('pk_live_Lh9RxfYBEjLco30J7VLUeGEP'); var elements = stripe.elements(); var style = { base: { iconColor: '#666ee8', color: '#31325f', fontWeight: 400, fontFamily: 'sans-serif', fontSmoothing: 'antialiased', lineHeight: '30px', fontSize: '18px', '::placeholder': { color: '#aab7c4', }, ':-webkit-autofill': { color: '#666ee8', }, }, }; card = elements.create('card', {style: style}); card.mount('#card_mount'); } $(function () { // Don't show CC form if PayPal selected $('input[name=billing_method]').change(showFieldsRelevantForBillingMethod); showFieldsRelevantForBillingMethod(); // Subscription attempt $('.subscribeSubmit2').click(function (event) { event.preventDefault(); submissionAttempted = true; // See if there are any errors var valid = checkForm(); if (!valid) { scrollToError(); return; } $('button').hide(); $('.activity').show(); if (isPayingByCreditCard()) { processCreditCardOrder(); } else { processPayPalOrder(); } }); // Show relevant errors if fields become invalid, but not on initial fill $('input,select').change(function () { copyNameFromShippingToCard(); if (submissionAttempted) { checkForm(); } }); $('input,select').on('input', recordReplayStep); // Order summary is in two places, let the left one be the defacto content $('.order_summary_container_bottom section').replaceWith($('.order_summary_container_left section').clone()); initCouponFields(); initStripe(); });