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 handleReturn(self, request):
   logger.debug(str(currentframe().f_lineno) + ":" + inspect.stack()[0][3] + "()")
   assert request is not None
   m_db = mod_database.Mdb()
   payment_id = request.values["pid"]
   payment_rec = m_db.findPaymentTxnById(payment_id)["doc"]
   if payment_rec["status"] != "pending": # prevent double entry
     return None
   payment_rec["status"] = "paid" # update the payment status to "paid"
   m_db.replacePaymentRecord(payment_id, payment_rec)
   payment_method = payment_rec["payment_method"]
   if payment_method == "paypal":
     return self.handlePaypalReturn(payment_id, request, m_db, payment_rec)
   elif payment_method == "braintree_credit_card":
     return self.handleBraintreeCCReturn(payment_id, request, m_db, payment_rec)
   elif payment_method == "stripe":
     return self.handleStripeReturn(payment_id, request, m_db, payment_rec)
   elif payment_method == "bacs":
     return self.handleBacsChequeCodReturn(payment_id, request, m_db, payment_rec)
   elif payment_method == "cheque":
     return self.handleBacsChequeCodReturn(payment_id, request, m_db, payment_rec)
   elif payment_method == "cod":
     return self.handleBacsChequeCodReturn(payment_id, request, m_db, payment_rec)
   else:
     raise Exception("Unknown payment gateway: " + payment_method)
 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 doPaymentStripe(self, payment_id, total, currency, gateway_sts, stripe_token):
   logger.debug(str(currentframe().f_lineno) + ":" + inspect.stack()[0][3] + "()")
   assert isinstance(payment_id, str)
   assert isinstance(total, str)
   assert isinstance(currency, str)
   assert gateway_sts is not None
   assert isinstance(stripe_token, str)
   descriptor = gateway_sts["statement_descriptor"]["value"]
   if gateway_sts["testmode"]["value"] == "yes":
     secret_key = gateway_sts["test_secret_key"]["value"]
     publish_key = gateway_sts["test_publishable_key"]["value"]
   else:
     secret_key = gateway_sts["secret_key"]["value"]
     publish_key = gateway_sts["publishable_key"]["value"]
   stripe.api_key = secret_key
   stripe_txn = stripe.Charge.create(
     amount = int(float(total) * 100),
     currency = currency,
     source = stripe_token,
     description = descriptor
   )
   if stripe_txn["status"] == "succeeded":
     m_db = mod_database.Mdb()
     m_db.setPaymentTxnGatewayResult(payment_id, stripe_txn.to_dict())
     return make_response(jsonify({ "payment_id": payment_id }))
   else:
     message = ""
     for error in result.errors.deep_errors:
       message += error.message + "<br />"
     abort(500, message)
Esempio n. 5
0
 def __init__(self):
     logger.debug(
         str(currentframe().f_lineno) + ":" + inspect.stack()[0][3] + "()")
     self.m_db = mod_database.Mdb()
     self.m_wcbot = mod_wcbot.WcBot()
     self.client_rec = None
     self.c_nls = None
 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 handleCancel(self, request):
   logger.debug(str(currentframe().f_lineno) + ":" + inspect.stack()[0][3] + "()")
   assert request is not None
   m_db = mod_database.Mdb()
   payment_id = request.values["pid"]
   payment_rec = m_db.findPaymentTxnById(payment_id)["doc"]
   payment_rec["status"] = "cancelled" # mark the status to cancelled
   m_db.replacePaymentRecord(payment_id, payment_rec)
   return payment_rec # return payment_rec but it is deleted
def handleAuthenicateCallback(params):
    logger.debug(
        str(currentframe().f_lineno) + ":" + inspect.stack()[0][3] + "()")
    assert isinstance(params["user_id"], str)
    assert isinstance(params["consumer_key"], str)
    assert isinstance(params["consumer_secret"], str)
    fb_page_id = params["user_id"]
    m_db = mod_database.Mdb()
    client_rec = m_db.findClientByFbPageId(fb_page_id)
    client_rec["woocommerce"]["consumer_key"] = params["consumer_key"]
    client_rec["woocommerce"]["consumer_secret"] = params["consumer_secret"]
    client_id = client_rec["client_id"]
    return m_db.replaceClientRecord(client_id, client_rec)
Esempio n. 9
0
 def __init__(self, user_id, fb_page_id, cart_items=None, order_id=None):
     logger.debug(
         str(currentframe().f_lineno) + ":" + inspect.stack()[0][3] + "()")
     assert isinstance(user_id, str)
     assert isinstance(fb_page_id, str)
     self.user_id = user_id
     self.fb_page_id = fb_page_id
     self.doc = None
     self.m_db = mod_database.Mdb()
     if cart_items is not None or order_id is not None:
         self.doc = {}
         if cart_items is not None:
             self.doc["cart_items"] = cart_items
         if order_id is not None:
             self.doc["order_id"] = order_id
def test_db():
    logger.debug(
        str(currentframe().f_lineno) + ":" + inspect.stack()[0][3] + "()")
    mod_global.server_entry(request)
    if request.args.get("q") == "chatbotcms-wcbot":
        try:
            m_mdb = mod_database.Mdb()
            count = m_mdb.getClientsCount()
            resp = make_response("Database connection okay.\n", 200)
            resp.headers["Access-Control-Allow-Origin"] = "*"
            resp.headers["Access-Control-Allow-Headers"] = "X-Requested-With"
            return resp
        except Exception as ex:
            return make_response("Exp: " + str(ex), 200)
    else:
        time.sleep(3)
        return make_response("Invalid request! Missing query string.\n", 500)
 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 doPaymentBraintreeCC(self, payment_id, total, currency, gateway_sts, braintree_nonce):
   logger.debug(str(currentframe().f_lineno) + ":" + inspect.stack()[0][3] + "()")
   assert isinstance(payment_id, str)
   assert isinstance(total, str)
   assert isinstance(currency, str)
   assert gateway_sts is not None
   assert isinstance(braintree_nonce, str)
   # inital braintree individual in this function only use
   if (gateway_sts["environment"]["value"] == "sandbox"):
     mode = braintree.Environment.Sandbox
     merchant_id = gateway_sts["sandbox_merchant_id"]["value"]
     public_key = gateway_sts["sandbox_public_key"]["value"]
     private_key = gateway_sts["sandbox_private_key"]["value"]
   else:
     mode = braintree.Environment.Production
     merchant_id = gateway_sts["merchant_id"]["value"]
     public_key = gateway_sts["public_key"]["value"]
     private_key = gateway_sts["private_key"]["value"]
   assert isinstance(merchant_id, str)
   assert isinstance(public_key, str)
   assert isinstance(private_key, str)
   braintree.Configuration.configure(mode, merchant_id, public_key, private_key)
   result = braintree.Transaction.sale({
     "amount": total,
     "payment_method_nonce": braintree_nonce,
     "options": { "submit_for_settlement": True }
   })
   if result.is_success:
     m_db = mod_database.Mdb()
     m_db.setPaymentTxnGatewayResult(payment_id, {
       "id": result.transaction.id,
       "merchant_account_id": result.transaction.merchant_account_id,
       "payment_instrument_type": result.transaction.payment_instrument_type,
       "processor_authorization_code": result.transaction.processor_authorization_code,
       "processor_response_text": result.transaction.processor_response_text,
       "status": result.transaction.status,
       "type": result.transaction.type
     })
     return make_response(jsonify({ "payment_id": payment_id }))
   else:
     message = ""
     for error in result.errors.deep_errors:
       message += error.message + "<br />"
     abort(500, message)
 def doOrderInfoInput(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")
     m_db = mod_database.Mdb()
     if order_id is None:
         order_id = ""
     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)
     return render_template("orderInfoInput.html",
                            jsOrigin=js_origin,
                            userId=user_id,
                            recipientId=fb_page_id,
                            orderId=order_id,
                            cart=cart_str)
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