def doOrderReview(self, request):
     logger.debug(
         str(currentframe().f_lineno) + ":" + inspect.stack()[0][3] + "()")
     assert isinstance(request.args.get("uid"), str)
     assert isinstance(request.args.get("rid"), str)
     assert isinstance(request.args.get("oid"), str)
     user_id = request.args.get("uid")
     fb_page_id = request.args.get("rid")
     order_id = request.args.get("oid")
     m_db = mod_database.Mdb()
     client_rec = m_db.findClientByFbPageId(fb_page_id)
     wc_rec = client_rec["woocommerce"]
     m_wc = mod_woocommerce.Wc(wc_rec["url"], wc_rec["consumer_key"],
                               wc_rec["consumer_secret"])
     m_cart = mod_shopcart.ShoppingCart(user_id, fb_page_id)
     m_cart.loadFromDatabase()
     cart_rec = m_cart.getRecord()
     cart_str = json.dumps(cart_rec, separators=(",", ":"))
     orderpool_rec = m_db.findOrderPoolById(order_id)["doc"]
     wcorder = m_wc.getOrder(orderpool_rec["order_id"])
     wcorder_str = mod_misc.dictToJsonStr(wcorder)
     return render_template("orderReview.html",
                            jsOrigin=js_origin,
                            userId=user_id,
                            recipientId=fb_page_id,
                            orderId=order_id,
                            shopcart=cart_str,
                            wcorder=wcorder_str)
 def handleBacsChequeCodReturn(self, payment_id, request, m_db, payment_rec):
   """
   BACS/Cheque/COD are all same handling for payment return
   """
   logger.debug(str(currentframe().f_lineno) + ":" + inspect.stack()[0][3] + "()")
   assert isinstance(payment_id, str)
   assert request is not None
   assert m_db is not None
   assert payment_rec is not None
   gateway_sts = payment_rec["gateway_settings"]
   # gateway_txn = payment_rec["gateway_txn"]
   client_rec = m_db.findClientByFbPageId(payment_rec["fb_page_id"])
   m_cart = mod_shopcart.ShoppingCart(payment_rec["user_id"], payment_rec["fb_page_id"])
   m_cart.loadFromDatabase()
   orderpool_id = payment_rec["order_id"]
   orderpool_rec = m_db.findOrderPoolById(orderpool_id)["doc"]
   wcorder_id = str(orderpool_rec["order_id"])
   wc_rec = client_rec["woocommerce"]
   m_wc = mod_woocommerce.Wc(wc_rec["url"], wc_rec["consumer_key"], wc_rec["consumer_secret"])
   wcorder = m_wc.getOrder(wcorder_id)
   self.updateOrderPool(False, m_db, orderpool_id, payment_id, payment_rec)
   self.updateWcOrder(False, wcorder_id, client_rec, payment_rec)
   # NOTES: Don't update stock level for these kinds of payment
   # self.updateWcProductStocks(m_wc, wcorder)
   return {
     "paymenttxn": payment_rec,
     "shopcart": m_cart.getRecord(),
     "wcorder": wcorder
   }
 def doOrderShipping(self, request):
     logger.debug(
         str(currentframe().f_lineno) + ":" + inspect.stack()[0][3] + "()")
     assert isinstance(request.args.get("uid"), str)
     assert isinstance(request.args.get("rid"), str)
     user_id = request.args.get("uid")
     fb_page_id = request.args.get("rid")
     m_db = mod_database.Mdb()
     client_rec = m_db.findClientByFbPageId(fb_page_id)
     wc_rec = client_rec["woocommerce"]
     wc_url = wc_rec["url"]
     wc_con_key = wc_rec["consumer_key"]
     wc_con_sec = wc_rec["consumer_secret"]
     m_wc = mod_woocommerce.Wc(wc_url, wc_con_key, wc_con_sec)
     m_cart = mod_shopcart.ShoppingCart(user_id, fb_page_id)
     m_cart.loadFromDatabase()
     cart_rec = m_cart.getRecord()
     cart_str = mod_misc.dictToJsonStr(cart_rec)
     wcorder = m_cart.createWcOrder(wc_url, wc_con_key, wc_con_sec)
     wcorder = mod_misc.delKeysInDict(wcorder, ["_links"])
     order_pool = m_db.saveOrderToPool(user_id, fb_page_id, wcorder)
     m_cart.saveOrderPool(order_pool)
     # direct pass the wcorder as Json string
     wcorder_str = mod_misc.dictToJsonStr(wcorder)
     wcshippings = m_wc.getShippingSettings()
     self.delWcOrderShipping(wcshippings)
     wcshipping_str = mod_misc.dictToJsonStr(wcshippings)
     return render_template("orderShipping.html",
                            jsOrigin=js_origin,
                            userId=user_id,
                            recipientId=fb_page_id,
                            orderId=order_pool["id"],
                            shopcart=cart_str,
                            wcorder=wcorder_str,
                            wcshipping=wcshipping_str)
 def handleStripeReturn(self, payment_id, request, m_db, payment_rec):
   logger.debug(str(currentframe().f_lineno) + ":" + inspect.stack()[0][3] + "()")
   assert isinstance(payment_id, str)
   assert request is not None
   assert m_db is not None
   assert payment_rec is not None
   gateway_sts = payment_rec["gateway_settings"]
   gateway_txn = payment_rec["gateway_txn"]
   client_rec = m_db.findClientByFbPageId(payment_rec["fb_page_id"])
   m_cart = mod_shopcart.ShoppingCart(payment_rec["user_id"], payment_rec["fb_page_id"])
   m_cart.loadFromDatabase()
   orderpool_id = payment_rec["order_id"]
   orderpool_rec = m_db.findOrderPoolById(orderpool_id)["doc"]
   wcorder_id = str(orderpool_rec["order_id"])
   wc_rec = client_rec["woocommerce"]
   m_wc = mod_woocommerce.Wc(wc_rec["url"], wc_rec["consumer_key"], wc_rec["consumer_secret"])
   wcorder = m_wc.getOrder(wcorder_id)
   self.updateOrderPool(True, m_db, orderpool_id, payment_id, payment_rec)
   self.updateWcOrder(True, wcorder_id, client_rec, payment_rec, gateway_txn)
   self.updateWcProductStocks(m_wc, wcorder)
   return {
     "paymenttxn": payment_rec,
     "shopcart": m_cart.getRecord(),
     "wcorder": wcorder
   }
Ejemplo n.º 5
0
 def createWcOrder(self, url, consumer_key, consumer_secret):
     logger.debug(
         str(currentframe().f_lineno) + ":" + inspect.stack()[0][3] + "()")
     assert isinstance(url, str)
     assert isinstance(consumer_key, str)
     assert isinstance(consumer_secret, str)
     assert self.doc is not None
     assert self.doc["cart_items"] is not None
     assert self.doc["input_info"] is not None
     assert self.doc["input_info"]["billing"] is not None
     assert self.doc["input_info"]["billing"]["first_name"] is not None
     assert self.doc["input_info"]["billing"]["last_name"] is not None
     assert self.doc["input_info"]["billing"]["email"] is not None
     assert self.doc["input_info"]["billing"]["phone"] is not None
     assert self.doc["input_info"]["billing"]["address1"] is not None
     # assert self.doc["input_info"]["billing"]["address2"] is not None
     assert self.doc["input_info"]["billing"]["city"] is not None
     assert self.doc["input_info"]["billing"]["state"] is not None
     # assert self.doc["input_info"]["billing"]["postal"] is not None
     assert self.doc["input_info"]["billing"]["country"] is not None
     assert self.doc["input_info"]["shipping"] is not None
     assert self.doc["input_info"]["shipping"]["first_name"] is not None
     assert self.doc["input_info"]["shipping"]["last_name"] is not None
     assert self.doc["input_info"]["shipping"]["address1"] is not None
     # assert self.doc["input_info"]["shipping"]["address2"] is not None
     assert self.doc["input_info"]["shipping"]["city"] is not None
     assert self.doc["input_info"]["shipping"]["state"] is not None
     # assert self.doc["input_info"]["shipping"]["postal"] is not None
     assert self.doc["input_info"]["shipping"]["country"] is not None
     m_wc = mod_woocommerce.Wc(url, consumer_key, consumer_secret)
     return m_wc.createOrder(self.doc["input_info"], self.doc["cart_items"])
 def doShoppingCart(self, request):
     logger.debug(
         str(currentframe().f_lineno) + ":" + inspect.stack()[0][3] + "()")
     assert isinstance(request.args.get("uid"), str)
     assert isinstance(request.args.get("rid"), str)
     user_id = request.args.get("uid")
     fb_page_id = request.args.get("rid")
     order_id = request.args.get("oid")
     if order_id is None: order_id = ""
     # prefetch server settings
     mDb = mod_database.Mdb()
     client_rec = mDb.findClientByFbPageId(fb_page_id)
     wc_rec = client_rec["woocommerce"]
     m_wc = mod_woocommerce.Wc(wc_rec["url"], wc_rec["consumer_key"],
                               wc_rec["consumer_secret"])
     json_gs = m_wc.getGeneralSetting()
     settingCountry = mod_misc.wcGeneralSettingLookup(
         json_gs, "woocommerce_default_country")
     settingCurrency = mod_misc.wcGeneralSettingLookup(
         json_gs, "woocommerce_currency")
     settingCurPos = mod_misc.wcGeneralSettingLookup(
         json_gs, "woocommerce_currency_pos")
     thouSep = mod_misc.wcGeneralSettingLookup(
         json_gs, "woocommerce_price_thousand_sep")
     decSep = mod_misc.wcGeneralSettingLookup(
         json_gs, "woocommerce_price_decimal_sep")
     numDec = mod_misc.wcGeneralSettingLookup(
         json_gs, "woocommerce_price_num_decimals")
     # Remove some useless properties
     del settingCountry["_links"]
     del settingCountry["description"]
     del settingCountry["tip"]
     del settingCurrency["description"]
     del settingCurrency["type"]
     del settingCurrency["default"]
     del settingCurrency["tip"]
     del settingCurrency["_links"]
     settingCurrency["symbolPos"] = settingCurPos[
         "value"]  # but add currency pos in there. Values maybe left, right, left_space, right_space
     settingCurrency["thousandSep"] = thouSep["value"]
     settingCurrency["decimalSep"] = decSep["value"]
     settingCurrency["numDecimal"] = numDec["value"]
     cart = mod_shopcart.ShoppingCart(user_id,
                                      fb_page_id,
                                      order_id=order_id)
     cart.loadFromDatabase()
     cart.saveServerSettings(
         {  # Append server setting to shopping cart record
             "country": settingCountry,
             "currency": settingCurrency
         })
     cart_str = mod_misc.dictToJsonStr(cart.getRecord())
     return render_template("shoppingCart.html",
                            jsOrigin=js_origin,
                            userId=user_id,
                            recipientId=fb_page_id,
                            orderId=order_id,
                            cart=cart_str)
 def genPaymentScreen(self, user_id, fb_page_id, order_id):
     logger.debug(
         str(currentframe().f_lineno) + ":" + inspect.stack()[0][3] + "()")
     assert request is not None
     assert isinstance(user_id, str)
     assert isinstance(fb_page_id, str)
     assert isinstance(order_id, str)
     m_db = mod_database.Mdb()
     client_rec = m_db.findClientByFbPageId(fb_page_id)
     wc_rec = client_rec["woocommerce"]
     m_wc = mod_woocommerce.Wc(wc_rec["url"], wc_rec["consumer_key"],
                               wc_rec["consumer_secret"])
     m_cart = mod_shopcart.ShoppingCart(user_id, fb_page_id)
     m_cart.loadFromDatabase()
     cart_rec = m_cart.getRecord()
     cart_str = mod_misc.dictToJsonStr(cart_rec)
     orderpool_rec = m_db.findOrderPoolById(order_id)["doc"]
     wcorder = m_wc.getOrder(orderpool_rec["order_id"])
     wcorder_str = mod_misc.dictToJsonStr(wcorder)
     m_pg = mod_payment.Paygate()
     m_pg.initPaymentGateways(m_wc)
     wcpaygates = m_pg.getRawPaymentGateways(
     )  # Get processed of all gateways
     wcpaygates = mod_misc.delKeysInDict(
         wcpaygates,
         ["tip", "_links", "method_description", "method_title", "label"])
     wcpaygates_str = mod_misc.dictToJsonStr(wcpaygates)
     braintree_rst = m_pg.createBraintreeClientToken()
     braintree_mode = ""
     braintree_token = ""
     if braintree_rst is not None:
         braintree_mode = braintree_rst["mode"]
         braintree_token = braintree_rst["clientToken"]
     stripkey = m_pg.getStripePublishKey()
     return render_template("orderPayment.html",
                            jsOrigin=js_origin,
                            userId=user_id,
                            recipientId=fb_page_id,
                            orderId=order_id,
                            stripePublishKey=stripkey,
                            braintreeClientToken=braintree_token,
                            braintreeMode=braintree_mode,
                            shopcart=cart_str,
                            wcorder=wcorder_str,
                            wcpaygates=wcpaygates_str)
 def handlePaypalReturn(self, payment_id, request, m_db, payment_rec):
   logger.debug(str(currentframe().f_lineno) + ":" + inspect.stack()[0][3] + "()")
   assert isinstance(payment_id, str)
   assert request is not None
   assert m_db is not None
   assert payment_rec is not None
   token = request.values["token"]
   payer_id = request.values["PayerID"]
   gateway_sts = payment_rec["gateway_settings"]
   test_mode = gateway_sts["testmode"]["value"]
   if test_mode == "yes":
     api_username = gateway_sts["sandbox_api_username"]["value"]
     api_password = gateway_sts["sandbox_api_password"]["value"]
     api_signature = gateway_sts["sandbox_api_signature"]["value"]
   else:
     api_username = gateway_sts["api_username"]["value"]
     api_password = gateway_sts["api_password"]["value"]
     api_signature = gateway_sts["api_signature"]["value"]
   email = gateway_sts["email"]["value"]
   if test_mode == "yes": mode = "sandbox"
   else: mode = "live"
   # checkout_details = self.callPaypalNVPGetCheckoutDetail(mode, api_username, api_password, api_signature, token)
   # TODO: Maybe add a "Confirm Pay" button here in future
   result_txn = self.callPaypalNVPGetCompleteTxn(mode, api_username, api_password, api_signature, token, payer_id, payment_rec["total"], payment_rec["currency"])
   m_db.setPaymentTxnGatewayResult(payment_id, result_txn)
   client_rec = m_db.findClientByFbPageId(payment_rec["fb_page_id"])
   m_cart = mod_shopcart.ShoppingCart(payment_rec["user_id"], payment_rec["fb_page_id"])
   m_cart.loadFromDatabase()
   orderpool_id = payment_rec["order_id"]
   orderpool_rec = m_db.findOrderPoolById(orderpool_id)["doc"]
   wcorder_id = str(orderpool_rec["order_id"])
   wc_rec = client_rec["woocommerce"]
   m_wc = mod_woocommerce.Wc(wc_rec["url"], wc_rec["consumer_key"], wc_rec["consumer_secret"])
   wcorder = m_wc.getOrder(wcorder_id)
   self.updateOrderPool(True, m_db, orderpool_id, payment_id, payment_rec)
   self.updateWcOrder(True, wcorder_id, client_rec, payment_rec, result_txn)
   self.updateWcProductStocks(m_wc, wcorder)
   return {
     "paymenttxn": payment_rec,
     "shopcart": m_cart.getRecord(),
     "wcorder": wcorder
   }
Ejemplo n.º 9
0
def test_wc():
    logger.debug(
        str(currentframe().f_lineno) + ":" + inspect.stack()[0][3] + "()")
    mod_global.server_entry(request)
    if request.args.get("subscribe_vk") is None:
        time.sleep(3)
        return make_response("Invalid request! Missing query string.\n", 500)
    client_id = request.args.get("subscribe_vk")
    m_mdb = mod_database.Mdb()
    client_rec = m_mdb.findClientByVerifyToken(client_id)
    if client_rec is None:
        return make_response("Invalid request! Invalid id", 500)
    wc_rec = client_rec["woocommerce"]
    wc_url = wc_rec["url"]
    m_wc = mod_woocommerce.Wc(wc_url, wc_rec["consumer_key"],
                              wc_rec["consumer_secret"])
    m_wc.getGeneralSetting()
    m_wc.getProductsList(1, 1)
    resp = make_response(
        "WooCommerce connection with '{0}' okay.\n".format(wc_url), 200)
    resp.headers["Access-Control-Allow-Origin"] = "*"
    resp.headers["Access-Control-Allow-Headers"] = "X-Requested-With"
    return resp
 def updateWcOrder(self, is_paid, wcorder_id, client_rec, payment_rec, txn_obj=None):
   logger.debug(str(currentframe().f_lineno) + ":" + inspect.stack()[0][3] + "()")
   assert isinstance(is_paid, bool)
   assert isinstance(wcorder_id, str)
   assert client_rec is not None
   assert payment_rec is not None
   if is_paid:
     assert txn_obj is not None
   order_id = payment_rec["order_id"]
   method = payment_rec["payment_method"]
   if method == "stripe":
     order_status = "processing"
     txn_id = txn_obj["id"]
   elif method == "braintree_credit_card":
     order_status = "processing"
     txn_id = txn_obj["id"]
   elif method == "paypal":
     order_status = "processing"
     txn_id = txn_obj["PAYMENTINFO_0_TRANSACTIONID"]
   elif method == "bacs": pass
   elif method == "cheque": pass
   elif method == "cod": pass
   else:
     raise Exception("Unhandled payment method: " + method)
   wc_rec = client_rec["woocommerce"]
   m_wc = mod_woocommerce.Wc(wc_rec["url"], wc_rec["consumer_key"], wc_rec["consumer_secret"])
   props = {
     "payment_method": payment_rec["payment_method"],
     "payment_method_title": payment_rec["payment_method_title"],
   }
   if is_paid:
     props["status"] = order_status # change the order status
     props["transaction_id"] = txn_id
     props["date_paid"] = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S")
     props["date_paid_gmt"] = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
   m_wc.updateOrder(wcorder_id, props)