Alipay.uts 2.6 KB
Newer Older
DCloud-yyl's avatar
DCloud-yyl 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
import { UTSiOSHookProxy } from "DCloudUniappRuntime";
import { UIApplication } from "UIKit"
import { AlipaySDK } from "AlipaySDK"
import { URL, NSUserActivity, NSUserActivityTypeBrowsingWeb } from "Foundation"


const defaultErrorCode : number = 700716;

const errorCodeMap : Map<string, number> = new Map([
	['8000', 700710],
	['4000', 700711],
	['5000', 700712],
	['6001', 700713],
	['6002', 700714],
	['6004', 700715]
]);

export class Alipay implements UTSiOSHookProxy {

	options ?: RequestPaymentOptions

	// 通过 url scheme 方式唤起 app 时的回调函数。
	applicationOpenURLOptions(app : UIApplication | null, url : URL, options : Map<UIApplication.OpenURLOptionsKey, any> | null = null) : boolean {
		if (url.host == 'safepay') {
			AlipaySDK.defaultService().processOrder(withPaymentResult = url, standbyCallback = (resultDic ?: Map<AnyHashable, any>) : void => {
				this.handlePaymentResult(resultDic)
			})
		}
		return true
	}

	// 当应用程序接收到与用户活动相关的数据时调用此方法,例如,当用户使用 Universal Link 唤起应用时。
	applicationContinueUserActivityRestorationHandler(application : UIApplication | null, userActivity : NSUserActivity | null, restorationHandler : ((res : [any] | null) => void) | null = null) : boolean {
		if (userActivity?.activityType == NSUserActivityTypeBrowsingWeb) {
			AlipaySDK.defaultService().handleOpenUniversalLink(userActivity, standbyCallback = (resultDic ?: Map<AnyHashable, any>) : void => {
				this.handlePaymentResult(resultDic)
			})
		}
		return true
	}

	requestPayment(options : RequestPaymentOptions) {
		this.options = options
		AlipaySDK.defaultService().payOrder(options.orderInfo, fromScheme = "uniAlipay", fromUniversalLink = "", callback = (resultDic ?: Map<AnyHashable, any>) : void => {
			this.handlePaymentResult(resultDic)
		})
	}

	handlePaymentResult(resultDic ?: Map<AnyHashable, any>) {
		let resultStatus : string = ''
		if (resultDic == null) {
			resultStatus = defaultErrorCode.toString()
		} else {
			resultStatus = resultDic!.get("resultStatus") as string
			if (resultStatus == null) {
				resultStatus = defaultErrorCode.toString()
			}
		}
		
		if (resultStatus == "9000") {
			let res : RequestPaymentSuccess = {
				data: resultDic
			}
			this.options?.success?.(res)
			this.options?.complete?.(res)
		} else {
			let code = errorCodeMap[resultStatus];
			if (code == null) {
				code = defaultErrorCode
			}
			let err = new RequestPaymentFailImpl(code!);
			this.options?.fail?.(err)
			this.options?.complete?.(err)
		}

	}
}