def PhoneScraper(self, pPhone): tPhoneUrl = 'http://www.searchpeopledirectory.com/international-reverse-phone/' tPhoneUrl = tPhoneUrl + pPhone request_cookies = mechanize.CookieJar() request_opener = mechanize.build_opener(mechanize.HTTPCookieProcessor(request_cookies)) request_opener.addheaders = [('Content-Type', 'application/x-www-form-urlencoded')] mechanize.install_opener(request_opener) tResponse = mechanize.urlopen(url = tPhoneUrl, timeout = 25.0) tContent = str(urllib.unquote(tResponse.read())) try: tCountryRegex = re.compile(">Country: <span id=\"extra\">(?P<country>.*?)</span") tCountryMatch = tCountryRegex.search(tContent) tCountry = tCountryMatch.groupdict()['country'] if(tCountry == "USA"): tCountry = "United States" except: tCountry = "Unknown" try: tStateRegex = re.compile(">State: <span id=\"extra\">(?P<state>.*?)</span") tStateMatch = tStateRegex.search(tContent) tState = tStateMatch.groupdict()['state'] except: tState = "Unknown" tResult = {} tResult['country'] = tCountry tResult['state'] = tState return tResult
def post(self): tUrl = "https://api-3t.paypal.com/nvp" tPaypalPayload = {} tPaypal = PaypalRefund() tAgent = Agent() tOrder = Order() tUser = users.get_current_user() tTransId = str(self.request.get('orderid')) tAgentEmail = str(tUser.email()) tAgent = Agent().GetAgentByEmail(tAgentEmail) tRefundAgent = tAgentEmail tOrderQuery = Order.all() tOrderQuery.filter("orderTransactionId", tTransId) #logging.debug("Transaction id: " + tTransId) tOrder = tOrderQuery.get() if (tOrder.orderDeliver != 'True'): tPaypalPayload['METHOD'] = "RefundTransaction" tPaypalPayload['TRANSACTIONID'] = tTransId tPayloadEncoded = tPaypal.GeneratePayload(tPaypalPayload) request_cookies = mechanize.CookieJar() request_opener = mechanize.build_opener( mechanize.HTTPCookieProcessor(request_cookies)) request_opener.addheaders = [('Content-Type', 'application/x-www-form-urlencoded')] mechanize.install_opener(request_opener) tResponse = mechanize.urlopen(url=tUrl, timeout=25.0, data=tPayloadEncoded) #logging.debug("Mechanize Package") #logging.debug("Url: " + tUrl) #logging.debug("Data: " + str(tPaypalPayload)) tResult = tResponse.read() #logging.debug(tResult) tOrder.orderIsRefunded = "True" tOrder.orderRefundAgent = tRefundAgent tOrder.orderLocked = "True" tOrder.orderRefundId = "" tOrder.put() self.response.out.write("Order Locked and Refunded")
def ProcessOrder(self, pArgumentDic): tOrderHandler = OrderHandler() tCustomerHandler = CustomerHandler() tCustomer = Customer() tPaypalOrder = PaypalOrder() tArgumentDic = pArgumentDic #Assign Values from POST from Paypal IPN tTransactionId = tArgumentDic['txn_id'] tAlphaMatch = re.compile('[^A-Za-z0-9]+') tAlphaSpaceMatch = re.compile('[^A-Za-z0-9 ]+') #Short circuits the order process for special PA page if ('payer_email' in tArgumentDic.keys()): if (tArgumentDic['payer_email'] == '*****@*****.**'): tPaypalOrder.ProcessPlayerAuctions(tArgumentDic) return try: tGoldAmount = tArgumentDic['option_name7'] except: tGoldAmount = "" try: tCustomerFirstName = tAlphaSpaceMatch.sub( '', tArgumentDic['first_name']) except: tCustomerFirstName = "" try: tCustomerLastName = tAlphaSpaceMatch.sub('', tArgumentDic['last_name']) except: tCustomerLastName = "" try: tCustomerName = tAlphaSpaceMatch.sub('', tArgumentDic['option_name1']) except: tCustomerName = "" try: tEmail = tArgumentDic['option_name2'] except: tEmail = "" tPaypalEmail = str(tArgumentDic['payer_email']).lower() try: tMobilePhone = tArgumentDic['option_name3'] tMobilePhone = re.sub(r'\D', '', tMobilePhone) except: tMobilePhone = "" try: tRsName = tArgumentDic['option_name4'].strip().lower() tRsName = tRsName.replace(' ', '_') tRsName = tRsName.replace('-', '_') except: tRsName = "" try: tCombatLevel = "" except: tCombatLevel = "" #try: #tReferCode = str(tArgumentDic['option_name5']).strip() #except: tReferCode = "" try: tPromotionCode = str(tArgumentDic['option_name5']).strip() except: tPromotionCode = "" tOrderIp = tArgumentDic['custom'] tMembers = "" try: tOrderQuery = Order.all().filter('orderTransactionId', tTransactionId) tOrder = tOrderQuery.fetch(1)[0] except: tOrder = Order() if ('fake' in tArgumentDic.keys()): #logging.debug('Fake key hit') #logging.debug(str(tArgumentDic['fake'])) if (tArgumentDic['fake'] == 'True'): tOrder.orderIsGenerated = True tOrder.orderFormName = tCustomerName tOrder.orderCombatLevel = tCombatLevel if (len(tGoldAmount) == 0): tUrl = "https://api-3t.paypal.com/nvp" #tOperation = "AddressVerify" tOperation = "GetTransactionDetails" #Get Paypal Information #tPaypal = PaypalTrigger() tResultDictionary = {} tPaypalPayload = {} tPayload = {} tPaypalPayload['METHOD'] = tOperation tPaypalPayload['TRANSACTIONID'] = tTransactionId tPayloadEncoded = tOrderHandler.GeneratePayload(tPaypalPayload) request_cookies = mechanize.CookieJar() request_opener = mechanize.build_opener( mechanize.HTTPCookieProcessor(request_cookies)) request_opener.addheaders = [('Content-Type', 'application/x-www-form-urlencoded')] mechanize.install_opener(request_opener) tResponse = mechanize.urlopen(url=tUrl, timeout=25.0, data=tPayloadEncoded) tResult = str(urllib.unquote(tResponse.read())) tResultSplit = tResult.split('&') for tPair in tResultSplit: tSplitPair = tPair.split("=") if (len(tSplitPair) == 1): tSplitPair.append("") tResultDictionary[tSplitPair[0]] = tSplitPair[1] logging.debug(tSplitPair[0] + " " + tSplitPair[1]) tGoldAmountString = tResultDictionary['L_NAME0'] logging.debug("Gold amount string %s".format(tGoldAmountString)) try: tGoldRegex = re.compile("([0-9]*?[m|M]).T") tGoldMatch = tGoldRegex.findall(tGoldAmountString) #logging.debug("Backup gold amount parser hit, string " + tGoldAmountString + " Match: " + tGoldMatch[0]) tGoldAmount = tGoldMatch[0] except: tGoldRegex = re.compile("([0-9]*?[m|M]).T") tGoldMatch = tGoldRegex.findall(tGoldAmountString) try: #logging.debug("Backup gold amount parser hit, string " + tGoldAmountString + " Match: " + tGoldMatch[0]) tGoldAmount = tGoldMatch[0] except: #logging.debug("No gold match") tGoldAmount = "" tOrder.orderQuantity = NumberToGp.ConvertBetToInt(tGoldAmount) tOrder.orderSimpleGoldAmount = tGoldAmount tOrder.orderFormEmail = tEmail tOrder.orderAccountName = tRsName tOrder.orderMobileNumber = tMobilePhone tOrder.orderPromotionalCode = tPromotionCode.lower() tOrder.orderIp = tOrderIp if (tMembers == "yes"): tOrder.orderCustomerIsMember = True else: tOrder.orderCustomerIsMember = False #Paypal Info tOrder.orderTransactionId = tTransactionId tOrder.orderPaypalFirstName = tCustomerFirstName tOrder.orderPaypalLastName = tCustomerLastName tOrder.orderCost = float(tArgumentDic['payment_gross']) tOrder.orderCustomerPaypalId = tArgumentDic['payer_id'] tOrder.orderPaypalEmail = str(tPaypalEmail).lower() tAssignedAgentNick = tPaypalOrder.GetAssignedAgent(tOrder) tOrder.orderAssignedAgent = tAssignedAgentNick #logging.debug("Order assigned to agent: " + str(tAssignedAgentNick)) tOrder.orderReferralCode = tReferCode tOrder.orderDeliver = 'False' if (tOrder.orderVerificationCode == None or tOrder.orderVerificationCode == ''): tOrder.orderVerificationCode = re.sub(r'\W', '', str(uuid.uuid4())).lower() tCurrentEocPrices = PriceContainer.GetCurrentPriceDic() tCurrent07Prices = PriceContainer.GetCurrentPriceDic07() tSkip07 = False if tOrder.orderSimpleGoldAmount in tCurrentEocPrices.keys(): if str(tOrder.orderCost) == str( tCurrentEocPrices[tOrder.orderSimpleGoldAmount]): tOrder.orderGoldType = 'eoc' tSkip07 = True if not tSkip07: if tOrder.orderSimpleGoldAmount in tCurrent07Prices.keys(): if str(tOrder.orderCost) == str( tCurrent07Prices[tOrder.orderSimpleGoldAmount]): tOrder.orderGoldType = '07' tOrderKey = str(tOrder.put()) #logging.debug("Order Saved: " + str(tOrderKey)) taskqueue.add(url="/iplookup", countdown=1, params={ "ip": tOrderIp, "transid": tTransactionId }) tUsedBonus = [] tCustomerList = tCustomerHandler.GetCustomerByPpid( tOrder.orderCustomerPaypalId) if (len(tCustomerList) == 1): tCustomer = tCustomerList[0] tIpList = tCustomer.customerIpAddresses tIpList.append(tOrderIp) tCustomer.customerIpAddresses = tIpList tOrderList = tCustomer.customerOrders tOrderList.append(tOrderKey) tCustomer.customerOrders = tOrderList tCustomer.customerOrderCount = int( tCustomer.customerOrderCount) + 1 #tUsedBonus = tCustomer.customerUsedBonus tUsedBonus = Order.GetCustomerPromoCodes( tCustomer.customerPaypalId) #tOrder.orderCustomer = str(tCustomer.key()) elif (len(tCustomerList) == 0): tCustomer.customerEmail = str(tOrder.orderPaypalEmail).lower() tCustomer.customerName = tCustomerName tCustomer.customerFirstName = tOrder.orderPaypalFirstName tCustomer.customerLastName = tOrder.orderPaypalLastName tCustomer.customerIpAddresses = [tOrderIp] tCustomer.customerOrders = [tOrderKey] tCustomer.customerOrderCount = 1 tCustomer.customerPhone = tMobilePhone tCustomer.customerEmailVerified = False tCustomer.customerPhoneVerified = False tCustomer.customerIdVerified = False tCustomer.customerPaypalId = tOrder.orderCustomerPaypalId tCustomer.customerIsGlobalBlacklisted = False tCustomer.customerIsPaBlacklisted = False tPromoCode = "" tPromoCode = tOrder.orderPromotionalCode #logging.debug("Order Promo Code: " + str(tOrder.orderPromotionalCode)) tPromo = Promo() tPromoCode = tPromoCode.lower() try: logging.debug("Promo Code: " + str(tPromoCode)) tPromo = Promo.GetPromoByCode(tPromoCode) logging.debug("Promo: " + str(tPromo)) tGoldAmount = tOrder.orderQuantity logging.debug("Gold Amount: " + str(tGoldAmount)) logging.debug("Promo is active: " + str(tPromo.promoIsActive)) if ((tPromo.promoIsActive) and (tPromo.promoUses <= tPromo.promoLimit)): if (tPromo.promoLimit != 0): tPromo.promoUses = tPromo.promoUses + 1 if ((tPromoCode in tUsedBonus) == True): tPercentBonus = 0.0 else: tPercentBonus = tGoldAmount * tPromo.promoPercentage #tUsedBonus.append(tPromoCode) tGoldAmount = tGoldAmount + tPercentBonus tGoldAmount = tGoldAmount + tPromo.promoGoldAmount tTotalBonusFloat = tPercentBonus + tPromo.promoGoldAmount logging.debug("Bonus float: " + str(tTotalBonusFloat)) tOrder.orderBonusQuantity = int(tTotalBonusFloat) logging.debug("Total Bonus Float " + str(tTotalBonusFloat)) logging.debug("Promo Gold Amount " + str(tPromo.promoGoldAmount)) logging.debug("Promo Percentage " + str(tPercentBonus)) except: tOrder.orderBonusQuantity = 0 #tCustomer.customerUsedBonus = tUsedBonus tCustomerKey = str(tCustomer.put()) tOrder.orderCustomer = tCustomerKey tOrderKey = str(tOrder.put()) if (tCustomerName == ""): tCustomerName = tCustomerFirstName + " " + tCustomerLastName if (tGoldAmount == None or len(str(tGoldAmount)) == 0): tGoldAmount = tGoldAmountString response = taskqueue.add(url="/emailnotify", countdown=1, params={ "email": tPaypalEmail, "gold": tGoldAmount, "name": tCustomerName, 'key': tOrderKey }) logging.debug(str(response))
def PostContext(self): tOrder = {} tContext = {} tPriceDictionary = PriceContainer.GetCurrentPriceDic() tType = str(self.request.get('type')) #logging.debug("Type: " + tType) tRandomAmount = "" tRandomPrice = "" tRandomAmount = random.choice(tPriceDictionary.keys()) tRandomPrice = tPriceDictionary[tRandomAmount] tRandomNumberList = [str(random.randrange(0, 9)) for i in range(0, 9)] #valid for all types of orders tOrder['mc_currency'] = 'USD' tOrder['receiver_email'] = '*****@*****.**' tOrder['receiver_id'] = 'NSKCXUXQEMPBG' tOrder['residence_country'] = 'US' tOrder['address_city'] = 'Beverly Hills' tOrder['address_country'] = 'United States' tOrder['address_country_code'] = 'US' tOrder['address_name'] = 'Test Address' tOrder['address_state'] = 'California' tOrder['address_street'] = '9876 Wilshire Boulevard' tOrder['address_zip'] = '90210' tOrder['notify_version'] = '3.4' #logging.debug(str(tOrder)) tAvailableEligibility = [ "Ineligible", "Partially Eligible - INR Only", "Eligible" ] tOrder['protection_eligibility'] = random.choice(tAvailableEligibility) tAvailableStatus = ["verified", "unverified"] tOrder['payer_status'] = random.choice(tAvailableStatus) if (tType == "random" or tType == "me"): tOrder['mc_gross'] = tRandomPrice tOrder['payment_gross'] = tRandomPrice tOrder['txn_type'] = 'web_accept' tOrder['discount'] = '0.0' tOrder['handling_amount'] = '0.0' tOrder['insurance_amount'] = '0.0' tOrder['item_number'] = '1' tOrder['mc_fee'] = '0.0' tOrder['COUNTRYCODE'] = 'US' tOrder['address_country'] = 'United States' tOrder['payment_fee'] = '0.0' tOrder['quantity'] = "1" tOrder['shipping'] = "0.0" tOrder['shipping_discount'] = "0.0" tOrder['shipping_method'] = "Default" tOrder['tax'] = "0.0" tOrder['item_name'] = tRandomAmount.upper() + "Transfer Code" tReferralCodes = ["", "69a8e184"] tRandomReferral = random.choice(tReferralCodes) tPromoCodes = ["SMELITE10"] tRandomPromoCode = random.choice(tPromoCodes) tOrder['option_name1'] = 'Test Order Name' #name tOrder['option_name4'] = 'RS Test Name' #rs name tOrder['option_name5'] = tRandomReferral #referral tOrder[ 'option_name5'] = tRandomPromoCode #promocode formerly option 6 tOrder['option_name7'] = tRandomAmount #gold amount #logging.debug(str(tOrder)) if (tType == "random" or tType == "viprandom"): tRandomEmail = 'sm-test-email-' + "".join( tRandomNumberList) + "@smokinmils.com" tOrder['payer_email'] = tRandomEmail tOrder['payer_id'] = "".join(tRandomNumberList) + "-testid" tOrder['txn_id'] = "".join(tRandomNumberList) tOrder['custom'] = '65.91.31.0' tOrder['option_name2'] = tRandomEmail #email tOrder['option_name3'] = '310-274-7777' #number tOrder['transaction_subject'] = '65.91.31.0' #logging.debug(str(tOrder)) if (tType == "me" or tType == "vipme"): tOrder['custom'] = '75.138.80.254' tOrder['payer_email'] = '*****@*****.**' tOrder['payer_id'] = 'FE6TJMYCTZ9CA' tOrder['txn_id'] = "".join(tRandomNumberList) tOrder['option_name2'] = '*****@*****.**' tOrder['option_name3'] = '678-499-6457' tOrder['transaction_subject'] = '75.138.80.254' #logging.debug(str(tOrder)) if (tType == "viprandom" or tType == "vipme"): tOrder['payment_gross'] = "8.99" tOrder['transaction_subject'] = "VIP Membership" tOrder['item_name'] = "VIP Membership" tOrder['item_number'] = "VIP" tOrder['mc_gross'] = "8.99" tOrder['txn_type'] = "subscr_payment" tOrder['subscr_id'] = "".join(tRandomNumberList) #logging.debug(str(tOrder)) tOrder['payment_status'] = 'Completed' tOrder['payment_type'] = 'Instant' tOrder['last_name'] = "Pleco" tOrder['first_name'] = "Kort" tOrder['fake'] = 'True' #logging.debug("Last call: " + str(tOrder)) tPayloadEncoded = urllib.urlencode(tOrder) #logging.debug("Encoded: " + str(tPayloadEncoded)) tUrl = "http://smokin-goldshop.appspot.com/paypalipn" #logging.debug("Url: " + str(tUrl)) request_cookies = mechanize.CookieJar() request_opener = mechanize.build_opener( mechanize.HTTPCookieProcessor(request_cookies)) request_opener.addheaders = [('Content-Type', 'application/x-www-form-urlencoded')] mechanize.install_opener(request_opener) tResponse = mechanize.urlopen(url=tUrl, timeout=25.0, data=tPayloadEncoded) tOrderQuery = Order().all() tOrderQuery.filter("orderIsGenerated", True) tOrderQuery.order("-orderCreated") tOrderList = tOrderQuery.fetch(limit=30) tContext['orders'] = tOrderList #logging.debug("Response: " + str(tResponse)) return tContext
def IpInfoScraper(self, pIp): tIpUrl = 'http://whatismyipaddress.com/ip/' tIpUrl = tIpUrl + pIp #logging.debug("Ip Url: " + tIpUrl) request_cookies = mechanize.CookieJar() request_opener = mechanize.build_opener( mechanize.HTTPCookieProcessor(request_cookies)) request_opener.addheaders = [('Content-Type', 'application/x-www-form-urlencoded')] mechanize.install_opener(request_opener) tResponse = mechanize.urlopen(url=tIpUrl, timeout=25.0) tContent = str(urllib.unquote(tResponse.read())) #logging.debug(str(tContent)) tCity = "" tCountry = "" tProxy = "" tHost = "" tIsp = "" tState = "" tType = "" try: tCountryRegex = re.compile( "<th>Country:</th><td>(?P<country>.*) <img") tCountryMatch = tCountryRegex.search(tContent) tCountry = tCountryMatch.groupdict()['country'] except: logging.debug("Country Storing Failed") try: tHostRegex = re.compile( "<th>Hostname:</th><td>(?P<host>.*)</td></tr><tr><th>I") tHostMatch = tHostRegex.search(tContent) tHost = tHostMatch.groupdict()['host'] except: logging.debug("Host Storing Failed") try: tStateRegex = re.compile( "<th>State/Region:</th><td>(?P<state>.*)</td></tr>") tStateMatch = tStateRegex.search(tContent) tState = tStateMatch.groupdict()['state'] except: logging.debug("State Storing Failed") try: tCityRegex = re.compile("<th>City:</th><td>(?P<city>.*)</td></tr>") tCityMatch = tCityRegex.search(tContent) tCity = tCityMatch.groupdict()['city'] except: logging.debug("City Storing Failed") try: tIspRegex = re.compile( "<th>ISP:</th><td>(?P<isp>.*)</td></tr><tr><th>Or") tIspMatch = tIspRegex.search(tContent) tIsp = tIspMatch.groupdict()['isp'] except: logging.debug("ISP Storing Failed") try: tProxyRegex = re.compile( "<th>Services:</th><td>(?P<proxy>.*)</td></tr><tr><th>T") tProxyMatch = tProxyRegex.search(tContent) tProxy = tProxyMatch.groupdict()['proxy'] if (tProxy[0] == "<"): tProxyRegex = re.compile( '<a href="/ip-services">(?P<proxy>.*)</a>') tProxyMatch = tProxyRegex.search(tProxy) tProxy = tProxyMatch.groupdict()['proxy'] except: logging.debug("Proxy Storing Failed") try: tTypeRegex = re.compile( "<th>Type:</th><td><a.+href=[\'|\"](.+)[\'|\"].*?>(?P<type>.*)</a></td></tr><tr><th>A" ) tTypeMatch = tTypeRegex.search(tContent) tType = tTypeMatch.groupdict()['type'] except: logging.debug("Type Storing Failed") tResult = {} tResult['country'] = tCountry tResult['host'] = tHost tResult['state'] = tState tResult['isp'] = tIsp tResult['proxy'] = tProxy tResult['type'] = tType return tResult
def post(self): tUrl = "https://api-3t.paypal.com/nvp" tOperation = "TransactionSearch" tOrderList = [] tPaypalPayload = {} tPayload = {} tPaypal = PaypalTrigger() tPostDate = self.request.get('date') if (tPostDate == None): tPostDate = datetime.datetime(2011, 2, 1, 1, 01, 01) tStartDate = tPaypal.StringToDatetime(tPostDate) try: tIncrement = datetime.timedelta(days = 1) tEndDate = tStartDate + tIncrement if(int(tEndDate.day) > 31): tEndDate = datetime.datetime(tStartDate.year, str(int(tStartDate.month) + 1), "01", tStartDate.hour, tStartDate.minute, tStartDate.second) #logging.debug("Fetching Items for Date: " + str(tPaypal.DatetimeToString(tStartDate))) tPaypalPayload['TRANSACTIONCLASS'] = "Received" tPaypalPayload['STATUS'] = "Success" tPaypalPayload['METHOD'] = tOperation tPaypalPayload['STARTDATE'] = tStartDate tPaypalPayload['ENDDATE'] = tEndDate tPayloadEncoded = tPaypal.GeneratePayload(tPaypalPayload) request_cookies = mechanize.CookieJar() request_opener = mechanize.build_opener(mechanize.HTTPCookieProcessor(request_cookies)) request_opener.addheaders = [('Content-Type', 'application/x-www-form-urlencoded')] mechanize.install_opener(request_opener) tResponse = mechanize.urlopen(url = tUrl, timeout = 25.0, data = tPayloadEncoded) #logging.debug("Mechanize Package") #logging.debug("Url: " + tUrl) #logging.debug("Data: " + str(tPaypalPayload)) tResult = tResponse.read() #logging.debug(tResult) except: logging.error("Paypal Timed Out: " + str(tPaypal.DatetimeToString(tStartDate))) tEndDate = tStartDate tResult = "" tPayload['date'] = tPaypal.DatetimeToString(tEndDate) tTimestampRegex = re.compile("L_TIMESTAMP(?P<objectnumber>\d*)=(?P<timestamp>.*?)Z&") tTimestampMatches = tTimestampRegex.findall(tResult) for tTimestamp in tTimestampMatches: tTempOrder = Order() tTimestampDecoded = urllib.unquote(tTimestamp[1]) tTimestampSplit = str(tTimestampDecoded).split('T') tTimestampDate = tTimestampSplit[0] tTimestampTime = tTimestampSplit[1] tTimestampDateSplit = tTimestampDate.split('-') tTimestampTimeSplit = tTimestampTime.split(':') tOrderTime = datetime.datetime(int(tTimestampDateSplit[0]), int(tTimestampDateSplit[1]), int(tTimestampDateSplit[2]), int(tTimestampTimeSplit[0]), int(tTimestampTimeSplit[1]), int(tTimestampTimeSplit[2])) tTempOrder.orderCreated = tOrderTime tOrderList.append(tTempOrder) tTypeRegex = re.compile("L_TYPE(?P<objectnumber>\d*)=(?P<type>.*?)&") tTypeMatches = tTypeRegex.findall(tResult) for tType in tTypeMatches: tTempOrder = tOrderList[int(tType[0])] tTempOrder.orderPaypalType = urllib.unquote(tType[1]) tOrderList[int(tType[0])] = tTempOrder tEmailRegex = re.compile("L_EMAIL(?P<objectnumber>\d*)=(?P<email>.*?)&") tEmailMatches = tEmailRegex.findall(tResult) for tEmail in tEmailMatches: tTempOrder = tOrderList[int(tEmail[0])] tTempOrder.orderCustomerEmail = urllib.unquote(tEmail[1]) tOrderList[int(tEmail[0])] = tTempOrder tNameRegex = re.compile("L_NAME(?P<objectnumber>\d*)=(?P<name>.*?)&") tNameMatches = tNameRegex.findall(tResult) for tName in tNameMatches: tTempOrder = tOrderList[int(tName[0])] tTempOrder.orderCustomerName = urllib.unquote(tName[1]) tOrderList[int(tName[0])] = tTempOrder tTransactionIdRegex = re.compile("L_TRANSACTIONID(?P<objectnumber>\d*)=(?P<transactionid>.*?)&") tTransactionIdMatches = tTransactionIdRegex.findall(tResult) for tTransactionId in tTransactionIdMatches: tTempOrder = tOrderList[int(tTransactionId[0])] tTempOrder.orderPaypalId = urllib.unquote(tTransactionId[1]) tOrderList[int(tTransactionId[0])] = tTempOrder tStatusRegex = re.compile("L_STATUS(?P<objectnumber>\d*)=(?P<status>.*?)&") tStatusMatches = tStatusRegex.findall(tResult) for tStatus in tStatusMatches: tTempOrder = tOrderList[int(tStatus[0])] tTempOrder.orderPaypalStatus = urllib.unquote(tStatus[1]) tOrderList[int(tStatus[0])] = tTempOrder for tOrder in tOrderList: try: tOrder.put() except: logging.error("============= Order Storing FAILED =============") logging.error("orderPaypalStatus: " + str(tOrder.orderPaypalStatus)) logging.error("orderPaypalId: " + str(tOrder.orderPaypalId)) logging.error("orderCustomerName: " + str(tOrder.orderCustomerName)) logging.error("orderCustomerEmail: " + str(tOrder.orderCustomerEmail)) logging.error("orderCreated: " + str(tPaypal.DatetimeToString(tOrder.orderCreated))) tFormerCount = int(self.request.get('former')) tOrderCount = len(tOrderList) #logging.debug("Former Count: " + str(tFormerCount) + " Order Count: " + str(tOrderCount)) if (tOrderCount == 0): tFormerCount += 1 else: tFormerCount = 0 tPayload['former'] = tFormerCount if (tFormerCount < 100): taskqueue.add(url = '/paypaltrigger', countdown = 10, params = tPayload)
def PostContext(self): tResponse = {} tResponse['tResponseText'] = "" tPaypal = VipCancelPaypalAjax() tResultDictionary = {} tPaypalPayload = {} tPayload = {} pSubscriptionKey = str(self.request.get('key')) tSubscription = VipSubscription() try: tSubscription = VipSubscription.get(pSubscriptionKey) except: tResponse['tResponseText'] = "Not Found" return tResponse #logging.debug("Subscription found with owner: " + tSubscription.subscriptionOwner) if (tSubscription): tPaypalPayload['METHOD'] = "ManageRecurringPaymentsProfileStatus" tPaypalPayload['PROFILEID'] = str(tSubscription.subscriptionId) tPaypalPayload['ACTION'] = 'Cancel' tPayloadEncoded = tPaypal.GeneratePayload(tPaypalPayload) request_cookies = mechanize.CookieJar() request_opener = mechanize.build_opener( mechanize.HTTPCookieProcessor(request_cookies)) request_opener.addheaders = [('Content-Type', 'application/x-www-form-urlencoded')] mechanize.install_opener(request_opener) tResponse = mechanize.urlopen(url=tUrl, timeout=25.0, data=tPayloadEncoded) tResult = str(urllib.unquote(tResponse.read())) #logging.debug("Mechanize Package") #logging.debug("Url: " + tUrl) #logging.debug("Data: " + str(tPaypalPayload)) #logging.debug("Response: " + tResult) tResultSplit = tResult.split('&') for tPair in tResultSplit: tSplitPair = tPair.split("=") tResultDictionary[tSplitPair[0]] = tSplitPair[1] tResponse['tResponseText'] = "Cancelled" tSubscription.subscriptionIsActive = False tSubscription.subscriptionEnd = datetime.datetime.now() tSubscription.subscriptionNeedsUpgrade = False tSubscription.subscriptionNeedsCancel = False tSubscription.put() tSubscriber = VipSubscriber() tSubscriber.subscriberActiveSubscription = "" tSubscriber.subscriberHasActiveSubscription = False tSubscriber.put() return tResponse
def GetContext(self): tUser = self.GetUser() tCustomerOrders = [] tOrderData = {} tContext = {} tOrder = Order() tCustomer = Customer() tIpHandler = IpLookup() tIpInfo = IpInfo() tDeliveryAgent = Agent() tRefundAgent = Agent() tAssignedAgent = Agent() tPriceDic = PriceContainer.GetCurrentPriceDic() tCountryDic = CountryContainer.GetCurrentCountryCodes() tOrderKey = str(urllib.unquote(self.request.get('key'))) if (tOrderKey != None and len(tOrderKey) > 0): tOrder = Order.get(tOrderKey) if (tOrder): tOrderHandler = OrderHandler() tResultDictionary = {} tPaypalPayload = {} tPayload = {} tUrl = "https://api-3t.paypal.com/nvp" tOperation = "GetTransactionDetails" tCustomer = Customer.get(tOrder.orderCustomer) # disabled to try to trace the "empty order" bug #if tOrder.orderVerificationCode is None: #tOrder.orderVerificationCode = str(uuid.uuid4()) #tOrder.put() try: tIpInfo = tIpHandler.GetIp(tOrder.orderIp)[0] except: tIpInfo.ipCountry = "Loading" tIpInfo.ipState = "Loading" tIpInfo.ipHost = "Loading" tIpInfo.ipProxy = "Loading" tIpInfo.ipIsp = "Loading" tIpInfo.ipType = "Loading" if (tIpInfo.ipProxy == ""): tIpInfo.ipProxy = 'No Proxy' tContext['tDisplayDeliver'] = 'True' #Get Paypal Information tPaypalPayload['METHOD'] = tOperation tPaypalPayload['TRANSACTIONID'] = tOrder.orderTransactionId #logging.debug("Order Paypal Email: " + tOrder.orderPaypalEmail) try: tPayloadEncoded = tOrderHandler.GeneratePayload(tPaypalPayload) request_cookies = mechanize.CookieJar() request_opener = mechanize.build_opener( mechanize.HTTPCookieProcessor(request_cookies)) request_opener.addheaders = [ ('Content-Type', 'application/x-www-form-urlencoded') ] mechanize.install_opener(request_opener) tResponse = mechanize.urlopen(url=tUrl, timeout=25.0, data=tPayloadEncoded) except: tContext[ 'error'] = 'Unable to Connect to Paypal, Try Refreshing' tContext['showerror'] = 'True' #tmpl = os.path.join(os.path.dirname(__file__), '../views/order.html') #self.response.out.write(render(tmpl, tContext)) return tContext tResult = str(urllib.unquote(tResponse.read())) tResultSplit = tResult.split('&') for tPair in tResultSplit: tSplitPair = tPair.split("=") try: tResultDictionary[tSplitPair[0]] = tSplitPair[1] #logging.debug(tSplitPair[0] + " " + tSplitPair[1]) except: logging.error("Error splitting item: " + str(tPair)) if ('COUNTRYCODE' in tResultDictionary.keys()): tCountryCode = tResultDictionary['COUNTRYCODE'] tPaypalCountry = tCountryDic[tCountryCode] else: tPaypalCountry = 'UNKNOWN' tOrderData['paypalcountry'] = tPaypalCountry if 'PROTECTIONELIGIBILITYTYPE' in tResultDictionary.keys(): tProtectionEligibility = tResultDictionary[ 'PROTECTIONELIGIBILITYTYPE'] if tProtectionEligibility == 'ItemNotReceivedEligible,UnauthorizedPaymentEligible': tProtectionEligibility = 'Eligible' if tProtectionEligibility != 'Eligible': tProtectionEligibility = 'Not Eligible' tContext['PROTECTIONELIGIBILITYTYPE'] = tProtectionEligibility else: tProtectionEligibility = 'UNKNOWN' #Display address fields if 'ADDRESSSTATUS' in tResultDictionary.keys(): tContext['ADDRESSSTATUS'] = tResultDictionary['ADDRESSSTATUS'] else: tContext['ADDRESSSTATUS'] = 'UNKNOWN' if 'SHIPTONAME' in tResultDictionary.keys(): tContext['SHIPTONAME'] = tResultDictionary['SHIPTONAME'] else: tContext['SHIPTONAME'] = 'UNKNOWN' if 'SHIPTOSTREET' in tResultDictionary.keys(): tContext['SHIPTOSTREET'] = tResultDictionary['SHIPTOSTREET'] else: tContext['SHIPTOSTREET'] = 'UNKNOWN' if 'SHIPTOSTREET2' in tResultDictionary.keys(): tContext['SHIPTOSTREET2'] = tResultDictionary['SHIPTOSTREET2'] else: tContext['SHIPTOSTREET2'] = 'UNKNOWN' if 'SHIPTOCITY' in tResultDictionary.keys(): tContext['SHIPTOCITY'] = tResultDictionary['SHIPTOCITY'] else: tContext['SHIPTOCITY'] = 'UNKNOWN' if 'SHIPTOSTATE' in tResultDictionary.keys(): tContext['SHIPTOSTATE'] = tResultDictionary['SHIPTOSTATE'] else: tContext['SHIPTOSTATE'] = 'UNKNOWN' if 'SHIPTOZIP' in tResultDictionary.keys(): tContext['SHIPTOZIP'] = tResultDictionary['SHIPTOZIP'] else: tContext['SHIPTOZIP'] = 'UNKNOWN' if 'SHIPTOCOUNTRYCODE' in tResultDictionary.keys(): tContext['SHIPTOCOUNTRYCODE'] = tResultDictionary[ 'SHIPTOCOUNTRYCODE'] else: tContext['SHIPTOCOUNTRYCODE'] = 'UNKNOWN' if 'SHIPTOPHONENUM' in tResultDictionary.keys(): tContext['SHIPTOPHONENUM'] = tResultDictionary[ 'SHIPTOPHONENUM'] else: tContext['SHIPTOPHONENUM'] = 'UNKNOWN' #Get order amount to add to dated totals tCurrentCost = float(tOrder.orderCost) #Get date 30 days ago tStartDate = tOrder.orderCreated tIncrement = datetime.timedelta(days=-30) tEndDate = tStartDate + tIncrement tCustomerOrderQuery = Order.all() tCustomerOrderQuery.filter("orderCreated >", tEndDate) tCustomerOrderQuery.filter("orderCustomer", tOrder.orderCustomer) tCustomerOrderQuery.filter("orderDeliver", 'True') tCustomerOrders = tCustomerOrderQuery.fetch(1000) #logging.debug("30 day date: " + str(tEndDate)) #logging.debug("30 day orders: " + str(len(tCustomerOrders))) tCustomerOrderTotal = 0.0 for tCustomerOrder in tCustomerOrders: tCustomerOrderTotal += float(tCustomerOrder.orderCost) if (tOrder.orderDeliver == 'False'): tCustomerOrderTotal += tCurrentCost tOrderData['orderTotal'] = str("%.2f" % tCustomerOrderTotal) #Get date 24 hours ago tStartDate = tOrder.orderCreated tIncrement = datetime.timedelta(days=-1) tEndDate = tStartDate + tIncrement tCustomerOrderQuery = Order.all().filter("orderCreated >", tEndDate) tCustomerOrderQuery.filter("orderCustomer", tOrder.orderCustomer) tCustomerOrderQuery.filter("orderDeliver", 'True') tCustomerOrders = tCustomerOrderQuery.fetch(1000) #logging.debug("24 hour date: " + str(tEndDate)) #logging.debug("24 hour orders: " + str(len(tCustomerOrders))) tCustomerOrderTotal24 = 0.0 for tCustomerOrder in tCustomerOrders: tCustomerOrderTotal24 += float(tCustomerOrder.orderCost) if (tOrder.orderDeliver == 'False'): tCustomerOrderTotal24 += tCurrentCost tOrderData['orderTotal24'] = str("%.2f" % tCustomerOrderTotal24) #Get date 15 days ago tStartDate = tOrder.orderCreated tIncrement = datetime.timedelta(days=-15) tEndDate = tStartDate + tIncrement tCustomerOrderQuery = Order.all().filter("orderCreated >", tEndDate) tCustomerOrderQuery.filter("orderCustomer", tOrder.orderCustomer) tCustomerOrderQuery.filter("orderDeliver", 'True') tCustomerOrders = tCustomerOrderQuery.fetch(1000) #logging.debug("15 day date: " + str(tEndDate)) #logging.debug("15 day orders: " + str(len(tCustomerOrders))) tCustomerOrderTotal15 = 0.0 for tCustomerOrder in tCustomerOrders: tCustomerOrderTotal15 += float(tCustomerOrder.orderCost) if (tOrder.orderDeliver == 'False'): tCustomerOrderTotal15 += tCurrentCost tOrderData['orderTotal15'] = str("%.2f" % tCustomerOrderTotal15) #===== Begin Location Matching ===== try: tPhoneHandler = PhoneLookup() tPhoneInfo = tPhoneHandler.GetPhone(tOrder.orderCustomer)[0] except: tPhoneInfo = Phone() tPhoneInfo.phoneState = "Unknown" tPhoneInfo.phoneCountry = "Unknown" #logging.debug("Ip country: " + str(tIpInfo.ipCountry)) #logging.debug("Paypal country: " + str(tPaypalCountry)) if (str(tIpInfo.ipCountry) == str(tPaypalCountry)): tOrderData['locationmatch'] = 'True' else: tOrderData['locationmatch'] = 'False' if (str(tIpInfo.ipCountry) == "United Kingdom" and str(tPaypalCountry) == "Great Britain (UK)"): tOrderData['locationmatch'] = 'True' #Agent Instructions #logging.debug("Order Total 24: " + str(tCustomerOrderTotal24)) #logging.debug("Order Total: " + str(tCustomerOrderTotal)) #logging.debug("Customer email verified: " + str(tCustomer.customerEmailVerified)) #logging.debug("Customer phone verified: " + str(tCustomer.customerPhoneVerified)) #logging.debug("Customer id verified: " + str(tCustomer.customerIdVerified)) #Protection Eligibility Filter tCountryEligibilityCode = tContext['SHIPTOCOUNTRYCODE'] tOrderData[ 'instructions'] = "No verification required" # default value if tCountryEligibilityCode in ('US', 'UK', 'CA', 'GB'): if tOrder.orderCost > 10: if tProtectionEligibility == 'Eligible': if tCustomerOrderTotal24 > 1000.0 or tCustomerOrderTotal > 4000.0: tOrderData[ 'instructions'] = "<span style='color:red'>$$$ Call Corowns $$$</span>" else: # not payment eligible tOrderData[ 'instructions'] = "<span style='color:red'>Refund - No Seller Protection</span>" tContext['tDisplayDeliver'] = 'False' else: # international customer #if( tCustomerOrderTotal24 < 30.0 and tCustomerOrderTotal < 60.0): if tIpInfo.ipType == "Corporate": tOrderData['instructions'] = tOrderData[ 'instructions'] + "<br /><span style='color:red'>Refer to PA - Corporate IP</span>" tOrderData['tDisplayDeliver'] = 'False' if (tIpInfo.ipProxy): if ("Confirmed proxy server" == tIpInfo.ipProxy): tOrderData['instructions'] = tOrderData[ 'instructions'] + "<br /><span style='color:red'>Refer to PA - Proxy</span>" tContext['tDisplaydeliver'] = 'False' if tCustomerOrderTotal24 > 200.0 or tCustomerOrderTotal > 400.0: tOrderData[ 'instructions'] = "<span style='color:red'>Refer to PA - Limit Exceeded</span>" tOrderData['tDisplayDeliver'] = 'False' elif tCustomerOrderTotal24 > 90.0 or tCustomerOrderTotal > 180.0: if tCustomer.customerIdVerified != True: tOrderData[ 'instructions'] = "<span style='color:red'>Verify Photo ID</span>" elif tCustomerOrderTotal24 > 30.0 or tCustomerOrderTotal > 60.0: if tCustomer.customerPhoneVerified != True: tOrderData[ 'instructions'] = "<span style='color:red'>Verify Phone Number</span>" if (tOrderData['locationmatch'] != 'True'): tOrderData['instructions'] = tOrderData[ 'instructions'] + "<br /><span style='color:red'>Verify Country Match</span>" #logging.debug("Order Data Instructions: " + str(tOrderData['instructions'])) #logging.debug("Location Match" + str(tOrderData['locationmatch'])) tCustomerOrderQuery = db.GqlQuery( "SELECT * FROM Order WHERE orderCustomer = '" + tOrder.orderCustomer + "'") tTotalCustomerOrders = [] tTotalCustomerOrders = tCustomerOrderQuery.fetch(50) for tCustomerOrder in tTotalCustomerOrders: if (tCustomerOrder.orderChargeback == True): tChargeBack = True else: tChargeBack = False tOrderData['chargeback'] = tChargeBack if (tChargeBack) else False tOrderData['chargeback'] = str(tOrderData['chargeback']) tIpChargebacks = tIpHandler.GetChargebacks(tOrder.orderIp) tOrderData['ipchargeback'] = len(tIpChargebacks) try: tTotalBonusString = NumberToGp.ConvertIntToBet( int(tOrder.orderBonusQuantity)) #logging.debug("Total Bonus String " + tTotalBonusString) except: tTotalBonusString = "" if (tCustomer.customerIsPaBlacklisted == True): tOrderData['instructions'] = tOrderData[ 'instructions'] + "<br /><span style='color:red'>Refer to PA - Blacklist</span>" tContext['tDisplayDeliver'] = 'False' if (tCustomer.customerIsGlobalBlacklisted == True): tOrderData['instructions'] = tOrderData[ 'instructions'] + "<br /><span style='color:red'>Do Not Deliver - Blacklist</span>" tContext['tDisplayDeliver'] = 'False' #normalize unicode try: tSimpleGold = unicodedata.normalize( "NFC", tOrder.orderSimpleGoldAmount).encode("ascii", "ignore") except: tSimpleGold = tOrder.orderSimpleGoldAmount #logging.debug(str(tPriceDic[tSimpleGold])) #logging.debug(str(tOrder.orderCost)) tCurrentEocPrices = PriceContainer.GetCurrentPriceDic() tCurrent07Prices = PriceContainer.GetCurrentPriceDic07() #logging.debug(str(tCurrent07Prices)) #logging.debug(str(tCurrentEocPrices)) tSkip07 = False tValidOrder = False if tOrder.orderSimpleGoldAmount in tCurrentEocPrices.keys(): if str(tOrder.orderCost) == str( tCurrentEocPrices[tOrder.orderSimpleGoldAmount]): tOrder.orderGoldType = 'eoc' tSkip07 = True tValidOrder = True if not tSkip07: if tOrder.orderSimpleGoldAmount in tCurrent07Prices.keys(): if str(tOrder.orderCost) == str( tCurrent07Prices[tOrder.orderSimpleGoldAmount]): tOrder.orderGoldType = '07' tValidOrder = True #logging.debug("skip07 {}".format(tSkip07)) #logging.debug("valid {}".format(tValidOrder)) #logging.debug("order simple gold amount {}".format(tOrder.orderSimpleGoldAmount)) #logging.debug("order value {}".format(tOrderData['orderTotal'])) #logging.debug("gold type {}".format(tContext['gold_type'])) if not tValidOrder: tOrderData['instructions'] = tOrderData[ 'instructions'] + '<br /><span style="color:red">Do Not Deliver - Bad Payment</span>' #tOrderData['tDisplayDeliver'] = 'False' #tOrder.orderLocked = 'True' #tOrder.put() #logging.debug(str(tOrder.orderIsGenerated)) if (tOrder.orderIsGenerated == True): tOrder.orderLocked = 'False' tOrder.orderIsRefunded = 'False' tOrder.orderDeliver = 'False' tOrderData['tDisplayDeliver'] = 'True' try: tDeliveryAgent = Agent.GetAgentByEmail( tOrder.orderDeliveryAgent) tContext['tDeliveryAgent'] = tDeliveryAgent except: pass try: tAssignedAgent = Agent.GetAgentByEmail( tOrder.orderAssignedAgent) tContext['tAssignedAgent'] = tAssignedAgent except: pass try: tRefundAgent = Agent.GetAgentByEmail(tOrder.orderRefundAgent) tContext['tRefundAgent'] = tRefundAgent except: pass tOrderData['bonus'] = tTotalBonusString tOrderData['phoneverified'] = str(tCustomer.customerPhoneVerified) tOrderData['emailverified'] = str(tCustomer.customerEmailVerified) tOrderData['idverified'] = str(tCustomer.customerIdVerified) tContext['tOrder'] = tOrder tContext['tOrderData'] = tOrderData tContext['tCustomer'] = tCustomer tContext['tIpInfo'] = tIpInfo tContext['tPhoneInfo'] = tPhoneInfo if ((tOrder.orderDeliveryAgent == "" or tOrder.orderDeliveryAgent == None) and tOrder.orderDeliver == 'True'): tAgentKey = tOrder.orderAgent tAgentId = Agent() tAgentId = Agent.get(tAgentKey) tOrder.orderDeliveryAgent = str(tAgentId.agentId) #logging.debug(str(tOrderData)) return tContext