unity3d+android:支付宝

2023-08-24 14:39:10 浏览数 (2)

android studio:

MyAliPay代码

代码语言:javascript复制
package com.luoyikun.myalipay;

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.unity3d.player.UnityPlayer;

import java.util.Map;

public class MyAliPay extends Fragment {

    String m_gameObjectName;
    String m_funcName;

    private Context unityContext;
    private Activity unityActivity;

    private static final String TAG = "MyAliPay";


    private static final int SDK_PAY_FLAG = 1;

    private static final String RESULT_SUCCESS = "9000";
    private static final String TIP_PAY_SUCCESS = "支付成功";
    private static final String TIP_PAY_FAILED = "支付失败";

    public void UnityFunc(String gameObjectName, String funcName)
    {
        m_gameObjectName = gameObjectName;
        m_funcName = funcName;
    }

    private static MyAliPay Instance = null;

    public static MyAliPay GetInstanceByAndroid(Activity activity,Context context)
    {
        if (Instance == null)
        {
            Instance = new MyAliPay();
            Instance.unityActivity = activity;
            Instance.unityContext = context;

            activity.getFragmentManager().beginTransaction().add(Instance, TAG).commit();
        }
        return Instance;
    }

    public static MyAliPay GetInstance()
    {
        if(Instance == null)
        {
            Instance = new MyAliPay();
            //Instance.gameObjectName = gameObject;
            Instance.unityActivity = UnityPlayer.currentActivity;
            Instance.unityContext = Instance.unityActivity.getBaseContext();
            UnityPlayer.currentActivity.getFragmentManager().beginTransaction().add(Instance, TAG).commit();
        }
        return Instance;
    }

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);  // 这一句很重要,保存对该Fragment的引用,防止在旋转屏幕等操作时时丢失引用(Fragment隶属于Activity)
    }

    // 调用 Unity
    // gameObjectName 为接受消息的Unity 中 GameObject 的名字
    // functionName   为接受消息的GameObject 挂载 C# 脚本中的函数名
    // _content       为发送给Unity 的内容
    public void CallUnity( String _content)
    {
        UnityPlayer.UnitySendMessage(m_gameObjectName, m_funcName, _content);
    }

    //支付回调:同步通知
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            @SuppressWarnings("unchecked")
            PayResult payResult = new PayResult((Map<String, String>) msg.obj);
            //根据支付结果返回的参数进行判断,resultStatus:结果状态
            //如果resultStatus为9000则是支付成功,否则则判定为支付失败
            String resultStatus = payResult.getResultStatus();
            if(TextUtils.equals(resultStatus,RESULT_SUCCESS)){
                //支付成功
                Toast.makeText(unityActivity, TIP_PAY_SUCCESS, Toast.LENGTH_SHORT).show();
            }
            else {
                //支付失败
                Toast.makeText(unityActivity, TIP_PAY_FAILED, Toast.LENGTH_SHORT).show();
            }

            //Toast.makeText(MainActivity.this, payResult.getResult(),
            // Toast.LENGTH_LONG).show();

        }
    };

    //支付方法,提供给Unity调用,info参数是服务器加签后传递给客户端的最终请求参数.再由客户端调用该方法的时候传递.
    //方法体是官方提供调用支付宝SDK支付的代码.
    public  void PayING(final String info){

        final String orderInfo = info;   // 订单信息

        //支付代码
        Runnable payRunnable = new Runnable() {


            @Override
            public void run() {
                PayTask alipay = new PayTask(unityActivity);
                Map<String, String> result = alipay.payV2(orderInfo,true);//ture表示unity到支付宝这个跳转的过程,是否会有一个过渡的动画

                //支付结果回调:就是执行了以上的mHandler
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();

    }
}

PayResult代码:

代码语言:javascript复制
package com.luoyikun.myalipay;

import android.text.TextUtils;

import java.util.Map;

public class PayResult {
    private String resultStatus;
    private String result;
    private String memo;

    public PayResult(Map<String, String> rawResult) {
        if (rawResult == null) {
            return;
        }

        for (String key : rawResult.keySet()) {
            //keySet 获取到map的所有key集合 equals 判断key的名称是否等于xxx
            if (TextUtils.equals(key, "resultStatus")) {
                resultStatus = rawResult.get(key);
            } else if (TextUtils.equals(key, "result")) {
                result = rawResult.get(key);
            } else if (TextUtils.equals(key, "memo")) {
                memo = rawResult.get(key);
            }
        }
    }

    @Override
    public String toString() {
        return "resultStatus={"   resultStatus   "};memo={"   memo
                  "};result={"   result   "}";
    }

    /**
     * @return the resultStatus
     */
    public String getResultStatus() {
        return resultStatus;
    }

    /**
     * @return the memo
     */
    public String getMemo() {
        return memo;
    }

    /**
     * @return the result
     */
    public String getResult() {
        return result;
    }
}

修改Grade

代码语言:javascript复制
apply plugin: 'com.android.library'

android {
    compileSdkVersion 28



    defaultConfig {
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'com.android.support:appcompat-v7:28.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    compile files('libs/alipaySdk-20170725.jar')
    implementation files('libs/classes.jar')
}

修改AndroidManifest

增加权限,与两个h5活动

代码语言:javascript复制
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.luoyikun.myalipay" >

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application android:allowBackup="true">
    <activity
        android:name="com.alipay.sdk.app.H5PayActivity"
        android:configChanges="orientation|keyboardHidden|navigation|screenSize"
        android:exported="false"
        android:screenOrientation="behind"
        android:windowSoftInputMode="adjustResize|stateHidden" >
    </activity>
    <activity
        android:name="com.alipay.sdk.app.H5AuthActivity"
        android:configChanges="orientation|keyboardHidden|navigation"
        android:exported="false"
        android:screenOrientation="behind"
        android:windowSoftInputMode="adjustResize|stateHidden" >
    </activity>

</application>
</manifest>

增加混淆proguard-rules

代码语言:javascript复制
-keep class com.alipay.android.app.IAlixPay{*;}
-keep class com.alipay.android.app.IAlixPay$Stub{*;}
-keep class com.alipay.android.app.IRemoteServiceCallback{*;}
-keep class com.alipay.android.app.IRemoteServiceCallback$Stub{*;}
-keep class com.alipay.sdk.app.PayTask{ public *;}
-keep class com.alipay.sdk.app.AuthTask{ public *;}
-keep class com.alipay.sdk.app.H5PayCallback {
    <fields>;
    <methods>;
}
-keep class com.alipay.android.phone.mrpc.core.** { *; }
-keep class com.alipay.apmobilesecuritysdk.** { *; }
-keep class com.alipay.mobile.framework.service.annotation.** { *; }
-keep class com.alipay.mobilesecuritysdk.face.** { *; }
-keep class com.alipay.tscenter.biz.rpc.** { *; }
-keep class org.json.alipay.** { *; }
-keep class com.alipay.tscenter.** { *; }
-keep class com.ta.utdid2.** { *;}
-keep class com.ut.device.** { *;}

unity3d端调用:

给服务器发商品id与数量,服务器向支付宝后台请求下单信息,服务器再发给客户端调用android端

代码语言:javascript复制
    public static void AliPay(string info)
    {
        AndroidJavaObject pluginObject = new AndroidJavaClass("com.luoyikun.myalipay.MyAliPay").CallStatic<AndroidJavaObject>("GetInstance");
        pluginObject.Call("PayING", info);
    }

0 人点赞