Integrate DFINERY (Adbrix) - Hybrid App
FollowGetting Started
This article provides an example of calling the Native DFINERY SDK's API by calling native code from Android and iOS webviews using a JavaScript interface .Therefore, please refer to the integration methods of Android and iOS SDK .
Android
Assuming that the web page is loaded through a web view as follows.
WebView myWebView = (WebView) findViewById(R.id.webview); WebSettings webSettings = myWebView.getSettings(); webSettings.setJavaScriptEnabled(true); webView.addJavascriptInterface(new AdbrixJavascriptInterface(this), "AdbrixBridge");
Create a class for a JavaScript interface.
public class AdbrixJavascriptInterface { Context context; AdbrixJavascriptInterface(Context context) { this.context = context; } // This guide assumes the use of the following two APIs. // Please refer to the Android SDK integration guide to add the necessary APIs. @JavascriptInterface public void invoke(String json) { try { AbxLog.i("received json: "+json, false); JSONObject jsonObject = new JSONObject(json); String methodName = jsonObject.optString("method_name"); if(CommonUtils.isNullOrEmpty(methodName)){ AbxLog.e("method name is null or empty", false); return; } switch (methodName){ case "login":{ login(json); break; } case "purchase":{ purchase(json); break; } } } catch (JSONException e) { e.printStackTrace(); } } private void login(String json) { try { jsonObject = new JSONObject(json); String userId = jsonObject.optString("user_id"); AdBrixRm.login(userId); } catch (JSONException e) { e.printStackTrace(); } } private void purchase(String json) { JSONObject jsonObject = new JSONObject(json); String orderId = jsonObject.optString("order_id"); double orderSales = jsonObject.getDouble("order_sales"); double discount = jsonObject.getDouble("discount"); double deliveryCharge = jsonObject.getDouble("delivery_charge"); int paymentMethod = jsonObject.getInt("payment_method"); String productModelList = jsonObject.optString("items"); List commerceProductModelList = getProductListByJsonString(productModelList); AdBrixRm.CommercePaymentMethod method = AdBrixRm.CommercePaymentMethod.getMethodByMethodCode(paymentMethod); AdBrixRm.Common.purchase(orderId, commerceProductModelList, orderSales, discount, deliveryCharge, method); } // Example of parsing the items within the purchase() parameters. private List getProductListByJsonString(String json){ ArrayList result = new ArrayList(); try { JSONArray root = new JSONArray(json); for(int i=0; i<root.length(); i++){ JSONObject productJson = root.getJSONObject(i); AdBrixRm.CommerceProductModel productModel = getProductByJsonObject(productJson); result.add(productModel); } } catch (JSONException e) { e.printStackTrace(); } return result; } private AdBrixRm.CommerceProductModel getProductByJsonObject(JSONObject jsonObject){ AdBrixRm.CommerceProductModel result = new AdBrixRm.CommerceProductModel(); String productId = jsonObject.optString("product_id"); String productName = jsonObject.optString("product_name"); double price = jsonObject.optDouble("price"); int quantity = jsonObject.optInt("quantity"); double discount = jsonObject.optDouble("discount"); double sales = jsonObject.optDouble("sales"); int currencyCode = jsonObject.optInt("currency"); String categories = jsonObject.optString("categories"); result.setProductID(productId); result.setProductName(productName); result.setPrice(price); result.setQuantity(quantity); result.setDiscount(discount); result.sales = sales; result.setCurrency(AdBrixRm.Currency.getCurrencyByCurrencyCode(currencyCode)); result.setCategory(AdBrixRm.CommerceCategiresModel.fromJSONString(categories)); return result; } }
iOS
Assume that the webpage is loaded through a webview as follows.
class ViewController: UIViewController { var webView: WKWebView! override func viewDidLoad() { ... ... ... } override func loadView() { let webConfiguration = WKWebViewConfiguration() let contentController = WKUserContentController() contentController.add(self, name: "AdbrixBridge") webConfiguration.userContentController = contentController webView = WKWebView(frame: .zero, configuration: webConfiguration) view = webView } }
Handles messages received from JavaScript through WKScriptMessageHandler.
extension ViewController: WKScriptMessageHandler { func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { if message.name == "AdbrixBridge" { guard let body = message.body as? [String: Any], let eventName = body["method_name"] as? String else {return} switch eventName { case "login": login(body) case "purchase": purchase(body) default: return } } } private func login(_ json: [String: Any]) { guard let userId = json["user_id"] as? String else {return} AdBrixRm.sharedInstance.login(userId: userId) } private func purchase(_ json: [String: Any]) { guard let orderId = json["order_id"] as? String, let orderSales = json["order_sales"] as? Double, let discount = json["discount"] as? Double, let deliveryCharge = json["delivery_charge"] as? Double, let paymentMethodValue = json["payment_method"] as? Int, let items = json["items"] as? NSArray else {return} let productInfo = items.compactMap { value -> AdBrixRmCommerceProductModel? in let productModel = AdBrixRmCommerceProductModel() guard let map = value as? [String: Any] else {return nil} guard let productId = map["product_id"] as? String, let productName = map["product_name"] as? String, let price = map["price"] as? Double, let quantity = map["quantity"] as? Int, let discount = map["discount"] as? Double, let currencyNum = map["currency"] as? Int?, let categoryString = map["categories"] as? [String:String]? else {return nil} let currencyString = currencyNum.map{ AdBrixRm.sharedInstance.getCurrencyString($0) } let category = categoryString.map{ AdBrixRmCommerceProductCategoryModel().setModel(categoryArr: $0.compactMap {$1}) } return productModel.setModel(productId: productId, productName: productName, price: price, quantity: quantity, discount: discount, currencyString: currencyString, categories: category, productAttrsMap: nil) } AdBrixRm.sharedInstance.commonPurchase(orderId: orderId, productInfo: productInfo, orderSales: orderSales, discount: discount, deliveryCharge: deliveryCharge, paymentMethod: adbrix.convertPayment(paymentMethodValue)) } }
Web
Call the native code as follows.
<script type="text/javascript"> function login() { var userId = 'jimmy'; const param = { method_name: 'login', user_id: userId }; // Check the platform. if (typeof AdbrixBridge !== 'undefined') { // Call Android code AdbrixBridge.invoke(param); } else if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.AdbrixBridge) { // Call iOS code window.webkit.messageHandlers.AdbrixBridge.postMessage(param); } else { // Unsupported platform console.log('Platform not supported'); } } function purchase() { var orderId = "order_id"; var orderSales = 10.0; var productId = "product_id"; var productName = "product_name"; var price = 10.0; var quantity = 1; var discount = 1200.00; var deliveryCharge = 0; // This is a sample Enum written as an example. Please check the type of parameters used natively. var payment = PaymentEnum.BankTransfer; var categories = { category1: "category1", category2: "category2", category3: "category3", category4: "category4" }; const products = []; products.push({ product_id: productId, product_name: productName, price: price, quantity: quantity, discount: discount, // This is a sample Enum written as an example. Please check the type of parameters used natively. currency: CurrencyEnum.CNY, categories: categories }); products.push({ product_id: productId, product_name: productName, price: price, quantity: quantity, discount: discount, // This is a sample Enum written as an example. Please check the type of parameters used natively. currency: CurrencyEnum.CNY, categories: categories }); const param = { method_name: "purchase", order_id: "orderID", order_sales: orderSales, discount: discount, delivery_charge: deliveryCharge, // This is a sample Enum written as an example. Please check the type of parameters used natively. payment_method: PaymentEnum.BankTransfer, quantity: 1, items: products, }; if (typeof AdbrixBridge !== 'undefined') { // Call Android code AdbrixBridge.invoke(param); } else if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.AdbrixBridge) { // Call iOS code window.webkit.messageHandlers.AdbrixBridge.postMessage(param); } else { // Unsupported platform console.log('Platform not supported'); } } </script>
[[인용:보통:위험]] The examples so far have been written to understand how to use native SDKs in hybrid apps through communication between web and native code.The implementation method does not necessarily have to be the same as the example code, and you can just call the native SDKs API in a way that suits your project.