Android 支付宝,微信支付

Android 支付宝,微信支付

https://docs.open.alipay.com/204

https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=8_1

1、配置

android {
    compileSdkVersion 27
    defaultConfig {
        resValue("string", "wx_appid", "wxa----------------")       //此处填入自己appid,必须
    }
}
dependencies {
    implementation  'com.tencent.mm.opensdk:wechat-sdk-android-without-mta:5.1.4'   //微信支付
    implementation files('libs/alipaySdk-xxxx.jar') //支付宝
}

2、复制资源

1、支付宝jar包下载地址:https://docs.open.alipay.com/54/104509
(此资源较敏感,防止第三方修改,本文不提供,仅提供官网下载地址,下载后放入[project]/[model]/libs目录中,1中引用需要修改为jar包名称)。

2、在主包下面新建包wxapi,新建类WXPayEntryActivity.java

package com.xxx.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.xxx.utils.PayUtils;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

/**
 * Created by 林少 on 2016/6/22.
 */
public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {
    public IWXAPI api;
    public static PayUtils.WxPayNotify notify;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        api = WXAPIFactory.createWXAPI(this, getString(getResources().getIdentifier("wx_appid", "string", getPackageName())));
        api.handleIntent(getIntent(), this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq req) {
    }

    @Override
    public void onResp(BaseResp resp) {
        if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
            if (resp.errCode == 0) {
                notify.success();
            } else {
                notify.failure();
            }
            finish();
        }
    }
}

AndroidManifest.xml添加

    
    
    

3、将下面工具类放入项目中,代码为kotlin编写,如需要转换为java,请留言

package com.xxx.utils

import android.app.Activity
import android.content.Context
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import com.alipay.sdk.app.PayTask
import com.xxx.wxapi.WXPayEntryActivity
import com.tencent.mm.opensdk.constants.Build
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.WXAPIFactory

/**
 * 支付utils
 * Created by 林少 on 2016/12/2.
 */

class PayUtils {

    interface AlipayNotify {
        fun success()

        fun loadinging()

        fun failure()
    }

    private class AlipayPayResult(rawResult: Map?) {
        /**
         * @return the resultStatus
         */
        var resultStatus: String? = null
            private set
        /**
         * @return the result
         */
        var result: String? = null
            private set
        /**
         * @return the memo
         */
        var memo: String? = null
            private set

        init {
            if (null != rawResult) {
                for (key in rawResult.keys) {
                    if (TextUtils.equals(key, "resultStatus")) {
                        resultStatus = rawResult[key]
                    } else if (TextUtils.equals(key, "result")) {
                        result = rawResult[key]
                    } else if (TextUtils.equals(key, "memo")) {
                        memo = rawResult[key]
                    }
                }
            }
        }

        override fun toString(): String {
            return ("resultStatus={" + resultStatus + "};memo={" + memo
                    + "};result={" + result + "}")
        }
    }

    data class WxInfoBean(
            var timestamp: String? = null,
            var sign: String? = null,
            var partnerid: String? = null,
            var noncestr: String? = null,
            var prepayid: String? = null,
            var packageValue: String? = null,
            var appid: String? = null
    )

    interface WxPayNotify {
        fun success()

        fun failure()
    }

    companion object {
        private val SDK_PAY_FLAG = 1
        private var alipayNotify: AlipayNotify? = null
        private val mHandler = Handler(Handler.Callback { message ->
            if (message.what == SDK_PAY_FLAG) {
                val payResult = AlipayPayResult(message.obj as Map)
                val resultStatus = payResult.resultStatus
                // 判断resultStatus 为“9000”则代表支付成功,具体状态码代表含义可参考接口文档
                if (TextUtils.equals(resultStatus, "9000")) {
                    alipayNotify!!.success()
                } else {
                    // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认,最终交易是否成功以服务端异步通知为准(小概率状态)
                    if (TextUtils.equals(resultStatus, "8000")) {
                        alipayNotify!!.loadinging()
                    } else {
                        // 其他值就可以判断为支付失败,包括用户主动取消支付,或者系统返回的错误
                        alipayNotify!!.failure()
                    }
                }
            }
            false
        })

        fun alipayPay(aty: Activity, orderInfo: String, notify: AlipayNotify) {
            alipayNotify = notify
            val payRunnable = Runnable {
                val alipay = PayTask(aty)
                val result = alipay.payV2(orderInfo, true)
                val msg = Message()
                msg.what = SDK_PAY_FLAG
                msg.obj = result
                mHandler.sendMessage(msg)
            }
            val payThread = Thread(payRunnable)
            payThread.start()
        }

        /**
         * 
         */

        fun wxPayMethod(context: Context, wxResultBean: WxInfoBean, wxPayNotify: WxPayNotify) {
            val api = WXAPIFactory.createWXAPI(context, null)
            api.registerApp(context.getString(context.resources.getIdentifier("wx_appid", "string", context.packageName)))
            WXPayEntryActivity.notify = wxPayNotify
            val isPaySupported = api.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT
            if (isPaySupported) {
                val req = PayReq()
                req.appId = wxResultBean.appid
                req.partnerId = wxResultBean.partnerid
                req.prepayId = wxResultBean.prepayid
                req.nonceStr = wxResultBean.noncestr
                req.timeStamp = wxResultBean.timestamp
                req.packageValue = wxResultBean.packageValue
                req.sign = wxResultBean.sign
                api.sendReq(req)
            } else {
                ToastUtil.showShort(context, "您未安装微信或者安装的版本过低,不支持微信支付")
            }
        }
    }
    /**
     * 
     */
}

public class PayUtils {
    interface AlipayNotify {
        void success();

        void loadinging();

        void failure();
    }

    interface WxPayNotify {
        void success();

        void failure();
    }

    private static class AlipayPayResult {
        public AlipayPayResult(Map rawResult) {
            if (null != rawResult) {
                for (String key : rawResult.keySet()) {
                    if (TextUtils.equals(key, "resultStatus")) {
                        resultStatus = rawResult.get(key);
                    } else if (TextUtils.equals(key, "result")) {
                        result = rawResult.get(key);
                    }
                    if (TextUtils.equals(key, "memo")) {
                        memo = rawResult.get(key);
                    }
                }
            }
        }

        String resultStatus;
        String result;
        String memo;

        public String getResultStatus() {
            return resultStatus;
        }

        public void setResultStatus(String resultStatus) {
            this.resultStatus = resultStatus;
        }

        public String getResult() {
            return result;
        }

        public void setResult(String result) {
            this.result = result;
        }

        public String getMemo() {
            return memo;
        }

        public void setMemo(String memo) {
            this.memo = memo;
        }

        @Override
        public String toString() {
            return "AlipayPayResult{" +
                    "resultStatus='" + resultStatus + '\'' +
                    ", result='" + result + '\'' +
                    ", memo='" + memo + '\'' +
                    '}';
        }
    }

    private class WxInfoBean {
        String timestamp;
        String sign;
        String partnerid;
        String noncestr;
        String prepayid;
        String packageValue;
        String appid;
    }

    private static final int SDK_PAY_FLAG = 1;
    private static AlipayNotify alipayNotify;
    private static Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == SDK_PAY_FLAG) {
                AlipayPayResult payResult = new AlipayPayResult((Map) msg.obj);
                String resultStatus = payResult.getResultStatus();
                if (TextUtils.equals(resultStatus, "9000")) {
                    alipayNotify.success();
                } else if (TextUtils.equals(resultStatus, "8000")) {
                    alipayNotify.loadinging();
                } else {
                    alipayNotify.failure();
                }
            }
            return false;
        }
    });

    public static void alipayPay(final Activity aty, final String orderInfo, AlipayNotify notify) {
        alipayNotify = notify;
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(aty);
                Map result = alipay.payV2(orderInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    public static void wxPayMethod(Context context, WxInfoBean wxResultBean, WxPayNotify wxPayNotify) {
        IWXAPI api = WXAPIFactory.createWXAPI(context, null);
        api.registerApp(context.getString(context.getResources().getIdentifier("wx_appid", "string", context.getPackageName())));
        WXPayEntryActivity.notify = wxPayNotify;
        boolean isPaySupported = api.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
        if (isPaySupported) {
            PayReq req = new PayReq();
            req.appId = wxResultBean.appid;
            req.partnerId = wxResultBean.partnerid;
            req.prepayId = wxResultBean.prepayid;
            req.nonceStr = wxResultBean.noncestr;
            req.timeStamp = wxResultBean.timestamp;
            req.packageValue = wxResultBean.packageValue;
            req.sign = wxResultBean.sign;
            api.sendReq(req);
        } else {
            Toast.makeText(context, "您未安装微信或者安装的版本过低,不支持微信支付", Toast.LENGTH_SHORT).show();
        }
    }
}

4、支付调用

支付宝
//back.data为后台返回
PayUtils.alipayPay(this@PayVipActivity, back.data, object : PayUtils.AlipayNotify {
                                override fun success() {
                                    T("支付成功")
                                    finish()
                                }

                                override fun loadinging() {
                                    T("支付结果确认中,请勿返回")
                                }

                                override fun failure() {
                                    T("支付失败,请重试")
                                }
                            })
微信
//back.data为后台返回签名过的对象
PayUtils.wxPayMethod(this@PayVipActivity, back.data, object : PayUtils.WxPayNotify {
                                override fun success() {
                                    T("支付成功")
                                    finish()
                                }

                                override fun failure() {
                                    T("支付失败,请重试")
                                }
                            })

出现错误请检查配置先,微信支付错误如果返回失败,自己debug看log,如果是-1,先检查开放平台包名和签名,如果正确说明后台签名错误,请把次链接给他,zzzz,https://www.jianshu.com/p/332e2e968c2b

你可能感兴趣的:(Android 支付宝,微信支付)