Unity 对接 Android SDK (支付宝)
环境版本使用Loopback4作为后端框架Unity版本:2020.3.13Android Studio:4.2.2
流程
后端组装支付宝OrderInfo传给 Unity 调用Android SDK,Android SDK 拉起支付宝
后端服务实现代码
按照支付宝官方教程生成RSA2
支付宝1.png
创建 private-key.pem文件,将生成的私钥要存在此文件中。
-----BEGIN RSA PRIVATE KEY-----私钥-----END RSA PRIVATE KEY-----
导入支付宝依赖包
const AlipaySdk = require('alipay-sdk').default;const aliUtil = require('alipay-sdk/lib/util');const urllib = require("urllib");
实现代码
@get("/test/create_order") public async testPaymentFun(): Promise<string> { const alipaySdk = new AlipaySdk({ appId: '应用id', signType: 'RSA2', privateKey: fs.readFileSync('./public/private-key.pem', 'ascii'), gateway: `https://openapi.alipaydev.com/gateway.do` }); const params = { notifyUrl: '回调地址', bizContent: { out_trade_no: `${uuidv4().replace(/-/g, '')}`, subject: encodeURIComponent('超超超级vip'), total_amount: 1.00, body: encodeURIComponent('超超超级vip'), product_code: 'QUICK_MSECURITY_PAY', } } const config = alipaySdk.config const signData = aliUtil.sign('alipay.trade.app.pay', params, config) const payInfo = new URLSearchParams(signData).toString() return payInfo; }支付宝android原生SDK分装
下载支付宝aar包:alipaysdk-15.8.03.210428205839.aar使用 Android Studio 新建项目(名称随意)新建Module
<!--- 创建流程 --->File--> new ---> new module ---> Android Library<!--- 注意:需要记住包名:com.xx.xx 后续需要在unity里面调用 --->
将aar放入刚刚创建 Library 下的 libs 中找到 build.gradle 文件添加
repositories { flatDir { dirs 'libs' } }dependencies { ... // 加载支付宝arr包 implementation(name:"alipaysdk-15.8.03.210428205839",ext:"aar") ... }
新建 AliSDKActivity.java文件
public class AliSDKActivity { privateString callAliObjName; privateString cllAliFunName;//回调方法 private static Activity _unityActivity;// unity启动时上下文 // 获取Unity上下文 public static Activity getActivity(){ if(null == _unityActivity) { try { Class<?> classtype = Class.forName("com.unity3d.player.UnityPlayer"); Activity activity = (Activity) classtype.getDeclaredField("currentActivity").get(classtype); _unityActivity = activity; } catch (ClassNotFoundException e) { } catch (IllegalAccessException e) { } catch (NoSuchFieldException e) { } } return _unityActivity; } // 调用unity内部方法 public static boolean callUnity(String gameObjName,String funName,String args){ try { // 获取unity的UnityPlayer Class<?> classType=Class.forName("com.unity3d.player.UnityPlayer"); Method method=classType.getMethod("UnitySendMessage",String.class,String.class,String.class); method.invoke(classType,gameObjName,funName,args); return true; }catch (Exception e){ } // 调用失败 returnfalse; } // ************************************** // 支付宝 // ************************************** // 调用支付宝支付 public void AliPay(final String info,String callObj,String callFun){ Toast.makeText(getActivity(),"转跳至支付宝",Toast.LENGTH_SHORT).show(); // 订单信息 final String orderInfo=info; // 方法回调名 callAliObjName=callObj; cllAliFunName=callFun; // 支付代码 Runnable payRunnable = new Runnable() { public void run() { // 设置为沙盒模式 (需要下载支付宝沙盒app) EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX); PayTask alipay = new PayTask(getActivity()); // true 表示unity到支付报是否有个过度动画 Map<String, String> result = alipay.payV2(orderInfo, true); Log.i("msp", result.toString()); Message msg = new Message(); msg.obj = result; mHandler.sendMessage(msg); } }; // 必须异步调用 Thread payThread = new Thread(payRunnable); payThread.start(); }; // 请求结果回调 private Handler mHandler = new Handler() { @SuppressWarnings("unused") public void handleMessage(Message msg) { PayResult payResult=new PayResult((Map<String,String>) msg.obj); String resultStatus=payResult.getResultStatus(); // 表示支付成功 if(TextUtils.equals(resultStatus, "9000")) { callUnity(callAliObjName,cllAliFunName,"请求成功"); }else { callUnity(callAliObjName,cllAliFunName,"请求失败"); } }; };}
将Android Module 打包成 aar
build ---> Rebuild Project新建untiy项目
将打包的aar放入到Assets/Plugins/Android目录下(没有此目录就手动创建)。新建xxx.cs
public class MyTestButton : MonoBehaviour{ // Unity dataBaes public GameObject textGameObj; private Text text; // android原生代码对象 AndroidJavaObject _ajc; private string orderInfo; // Start is called before the first frame update void Start() { text = textGameObj.transform.GetComponent<Text>(); //通过该API来实例化导入的arr中对应的类 _ajc = new AndroidJavaObject("com.xxx.xxx.AliSDKActivity"); } // Update is called once per frame void Update() { } // 创建订单 public void MyCreatOrder() { // 请求后台服务器 StartCoroutine(CreatOrder()); } // 支付 public void MyPaymentOnClick() { object[] bjcts = new object[] { orderInfo, "Canvas", "UpdateText" }; // 调用 Android 里面的方法 _ajc.Call("AliPay", bjcts); } // 修改Unity Text private void UpdateText(string str) { text.text = str; } // unity Get 请求获取订单数据 IEnumerator CreatOrder() { string url = "http://192.168.3.180:3000/test/create_order"; using (UnityWebRequest webRequest = UnityWebRequest.Get(url)) { yield return webRequest.SendWebRequest(); if (webRequest.isHttpError || webRequest.isNetworkError) { Debug.LogError(webRequest.error + "\n" + webRequest.downloadHandler.text); } else { Debug.Log(webRequest.downloadHandler.text); orderInfo = webRequest.downloadHandler.text; } } }}注意:此代码支付未作校验,具体支付校验需按支付宝官方对接文档实现。
页:
[1]