Last active
May 6, 2023 10:33
-
-
Save scriptpapi/a4f9745a04be6e23a94ad459d7dd6b63 to your computer and use it in GitHub Desktop.
Plugin for Hosted Checkout on IOS SwiftUI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// HostedCheckout.swift | |
// | |
// Created by Nawaf Abdullah on 02/05/2023. | |
// | |
/* | |
Example Usage: | |
VStack { | |
HostedCheckout( | |
hostUrl: "https://test-gateway.mastercard.com", | |
sessionId: "SESSION0002578579722L05088797N1", | |
paymentFinished: self.$paymentFinished) | |
} | |
.frame(height: 500) | |
.padding() | |
*/ | |
import SwiftUI | |
import WebKit | |
struct HostedCheckout: UIViewRepresentable { | |
var hostUrl: String | |
var sessionId: String | |
@Binding var paymentFinished: Bool | |
func makeUIView(context: Context) -> WKWebView { | |
let wKWebView = WKWebView() | |
wKWebView.navigationDelegate = context.coordinator | |
return wKWebView | |
} | |
func updateUIView(_ webView: WKWebView, context: Context) { | |
let html = "<html> <header> <meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0'> </header> <head> <script src='" + self.hostUrl + "/static/checkout/checkout.min.js'></script> <script type='text/javascript'> Checkout.configure({ session: { id: '" + self.sessionId + "' } }).then(() => { Checkout.showEmbeddedPage('#embed-target'); }) </script> </head> <body> <div id='embed-target'> </div> </body> </html>" | |
webView.scrollView.isScrollEnabled = false | |
webView.loadHTMLString(html, baseURL: Bundle.main.bundleURL) | |
} | |
func makeCoordinator() -> WebViewCoordinator { | |
WebViewCoordinator(self) | |
} | |
class WebViewCoordinator: NSObject, WKNavigationDelegate { | |
var parent: HostedCheckout | |
init(_ parent: HostedCheckout) { | |
self.parent = parent | |
} | |
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { | |
if navigationAction.request.url!.description.contains("resultIndicator") { | |
self.parent.paymentFinished = true | |
} | |
else { | |
self.parent.paymentFinished = false | |
} | |
decisionHandler(.allow) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment