美文网首页
android支付宝,微信支付集成工具类

android支付宝,微信支付集成工具类

作者: 木小伍 | 来源:发表于2018-12-14 15:04 被阅读0次

    详细的介绍、解释移步微信、支付宝的开发平台。下载官方demo了解更多。需要注意的是,微信的官方demo还是eclipse版的。

    实现步骤

    1.添加相关的引用(微信,支付宝)

    主要是在libs目录下,添加支付宝sdkjar包,同时在gradle文件中添加依赖。如下图所示


    image.png
    2.配置微信回调的activity(支付宝的在第一步已经完成了)

    微信支付需要创建一个包名为wxapi,并且必须放置在applicationId下面,随便放到一个包下的话,会导致支付之后,拿不到回调,如下图


    image.png

    WXPayEntryActivity,主要是对onResp()的方法重写,参见官方的demo,自己的全部代码为:

    package com.example.user.paydemo.wxapi;
    
    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.os.Handler;
    import android.support.annotation.Nullable;
    import android.support.v7.app.AppCompatActivity;
    import android.widget.RelativeLayout;
    
    import com.example.user.paydemo.AppManager;
    import com.example.user.paydemo.MainActivity;
    import com.example.user.paydemo.PayUtils;
    import com.tencent.mm.opensdk.modelbase.BaseReq;
    import com.tencent.mm.opensdk.modelbase.BaseResp;
    import com.tencent.mm.opensdk.modelpay.PayResp;
    import com.tencent.mm.opensdk.openapi.IWXAPI;
    import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
    import com.tencent.mm.opensdk.openapi.WXAPIFactory;
    
    /**
     * 微信回调页面
     */
    public class WXPayEntryActivity extends AppCompatActivity implements IWXAPIEventHandler {
        private IWXAPI api;
    
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(new RelativeLayout(this));
            api = WXAPIFactory.createWXAPI(this, PayUtils.WECHAT_APP_ID);
            api.handleIntent(getIntent(), this);
    
        }
        
        @Override
        protected void onNewIntent(Intent intent) {
            super.onNewIntent(intent);
            setIntent(intent);
            api.handleIntent(intent, this);
        }
        
        @Override
        public void onReq(BaseReq baseReq) {
        }
        @Override
        public void onResp(BaseResp baseResp) {
            int code = baseResp.errCode;
            //    LogUtils.LOG_D(PayUtils.class, "返回的code=" + code);
            PayResp payResp = (PayResp) baseResp;
            switch (code) {
                case 0://支付成功后的界面
                    paySucess(payResp);
                    finish();
                    break;
                case -1:
                    //   showToast("签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、您的微信账号异常等。");
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            finish();
                        }
                    }, 1500);
                    break;
                case -2://用户取消支付后的界面
                    //   mPresenter.payCancle();取消支付处理方法类似paySucess()
                    finish();
                    break;
            }
        }
    
        private void paySucess(PayResp payResp) {
            //从activity栈中取出需要支付页面
            Activity activity = AppManager.getBaseActivity(MainActivity.class);
            if (activity != null && !activity.isFinishing()) {
                MainActivity payActivity = (MainActivity) activity;
                payActivity.wxPaySuccess(payResp);
            }
        }
    }
    

    至此,支付宝和微信的配置就完成了。
    接下来是配置支付工具类了。目录结构如下:


    image.png

    AlipayEntity全部代码:

    package com.example.user.paydemo.bean;
    import com.google.gson.annotations.Expose;
    /**
     * 调起支付宝支付的实体类
     */
    public class AlipayEntity {
        @Expose
        private String orderstring;
        @Expose
        private String orderid;
        public String getOrderstring() {
            return orderstring;
        }
        public AlipayEntity setOrderstring(String orderstring) {
            this.orderstring = orderstring;
            return this;
        }
        public String getOrderid() {
            return orderid;
        }
        public AlipayEntity setOrderid(String orderid) {
            this.orderid = orderid;
            return this;
        }
    }
    

    WxPayEntity 全部代码:

    package com.example.user.paydemo.bean;
    
    import com.google.gson.annotations.Expose;
    import com.google.gson.annotations.SerializedName;
    
    import java.io.Serializable;
    
    /***
     * 调起微信支付的实体类
     *
     */
    public class WxPayEntity implements Serializable{
        @Expose
        private String prepay_id;
        @Expose
        private String orderid;
        @Expose
        private String noncestr;
        @Expose
        private String timestamp;
        @Expose
        private String sign;
        @SerializedName("package")
        private String packageName = "Sign=WXPay"; //固定写死
    
        public String getPrepay_id() {
            return prepay_id;
        }
    
        public WxPayEntity setPrepay_id(String prepay_id) {
            this.prepay_id = prepay_id;
            return this;
        }
    
        public String getOrderid() {
            return orderid;
        }
    
        public WxPayEntity setOrderid(String orderid) {
            this.orderid = orderid;
            return this;
        }
    
        public String getNoncestr() {
            return noncestr;
        }
    
        public WxPayEntity setNoncestr(String noncestr) {
            this.noncestr = noncestr;
            return this;
        }
    
        public String getTimestamp() {
            return timestamp;
        }
    
        public WxPayEntity setTimestamp(String timestamp) {
            this.timestamp = timestamp;
            return this;
        }
    
        public String getSign() {
            return sign;
        }
    
        public WxPayEntity setSign(String sign) {
            this.sign = sign;
            return this;
        }
    
        public String getPackageName() {
            return packageName;
        }
    
        public WxPayEntity setPackageName(String packageName) {
            this.packageName = packageName;
            return this;
        }
    }
    

    PayZfbResultEntity代码:

    package com.example.user.paydemo.bean;
    
    /**
     * Created by xiaodi on 2017/5/27.
     */
    public class PayZfbResultEntity {
        public PayResult payResult;
        public String orderid;
    }
    

    PayResult代码:

    package com.example.user.paydemo.bean;
    
    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()) {
                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;
        }
    }
    

    PayUtils代码:

    package com.example.user.paydemo;
    
    import android.app.Activity;
    import android.os.AsyncTask;
    import android.os.Handler;
    import android.os.Message;
    import android.text.TextUtils;
    import android.widget.Toast;
    
    import com.alipay.sdk.app.PayTask;
    import com.example.user.paydemo.bean.AlipayEntity;
    import com.example.user.paydemo.bean.PayResult;
    import com.example.user.paydemo.bean.PayZfbResultEntity;
    import com.example.user.paydemo.bean.WxPayEntity;
    import com.tencent.mm.opensdk.constants.Build;
    import com.tencent.mm.opensdk.modelpay.PayReq;
    import com.tencent.mm.opensdk.openapi.IWXAPI;
    
    import org.json.JSONException;
    import org.json.JSONObject;
    
    import java.util.Map;
    
    /**
     * Created by user on 2018/10/16.
     * 支付工具类
     */
    
    public class PayUtils {
        //开发者的appid,拿到正式的appid,就要替换
        public static final String WECHAT_APP_ID = "*************";
        //商户id
        public static final String PARENT_ID = "*************";
    
        private static final int SDK_PAY_FLAG = 1;
        private IWXAPI api;
        private Activity activity;
    
        public PayUtils(IWXAPI api, Activity activity) {
            this.activity = activity;
            this.api = api;
        }
    
    
        Handler mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case SDK_PAY_FLAG:// 支付宝
                        PayZfbResultEntity payZfbResultEntity = (PayZfbResultEntity) msg.obj;
                        /**
                         对于支付结果,请商户依赖服务端的异步通知结果。同步通知结果,仅作为支付结束的通知。
                         */
                        PayResult payResult = payZfbResultEntity.payResult;
                        String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                        String resultStatus = payResult.getResultStatus();
                        // 判断resultStatus 为9000则代表支付成功
                        if (TextUtils.equals(resultStatus, "9000")) {
                            // 该笔订单是否真实支付成功,需要依赖服务端的异步通知。
                            if (null != resultListener) {
                                resultListener.aliPayCallBack();
                            }
                        } else if (TextUtils.equals(resultStatus, "6001")) {
                            if (null != resultListener) {
                                resultListener.aliPayCancle();
                            }
                        } else {
                            // 该笔订单真实的支付结果,需要依赖服务端的异步通知。
                            Toast.makeText(activity, "支付失败或未安装支付宝", Toast.LENGTH_SHORT).show();
                        }
                        break;
                }
            }
        };
    
        /**
         * 支付宝支付
         *
         * @param alipayEntity 服务器传回来的支付数据
         */
        public void payByAliPay(final AlipayEntity alipayEntity) {
            //需要处理后台服务器返回的数据信息
            // 后台返回的zfb 信息
            if (TextUtils.isEmpty(alipayEntity.getOrderid())) return;
    
            Runnable payRunnable = new Runnable() {
                @Override
                public void run() {
                    PayTask alipay = new PayTask(activity);
                    Map<String, String> result = alipay.payV2(alipayEntity.getOrderstring(), true);
    
                    PayZfbResultEntity payZfbResultEntity = new PayZfbResultEntity();
                    payZfbResultEntity.payResult = new PayResult(result);
                    payZfbResultEntity.orderid = alipayEntity.getOrderid();
                    try {
                        JSONObject jsonObject = new JSONObject(payZfbResultEntity.payResult.getResult());
                        //   LogUtils.LOG_D(PayUtils.class, "支付宝返回结果" + jsonObject.toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
    
                    Message msg = new Message();
                    msg.what = SDK_PAY_FLAG;
                    msg.obj = payZfbResultEntity;
                    mHandler.sendMessage(msg);
                }
            };
            // 必须异步调用
            Thread payThread = new Thread(payRunnable);
            payThread.start();
        }
    
        /**
         * 微信支付
         */
        public void payByWechat(final WxPayEntity wxPayEntity) {
            if (api.isWXAppInstalled() && api.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT) {
            } else {
                // mView.showToast("未安装微信或微信版本过低!", R.mipmap.icon_fail);
                return;
            }
            if (null == wxPayEntity)
                return;
            new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... voids) {
                    //  LogUtils.LOG_D(getClass(), "正在生成订单,请稍等.");
                    PayReq request = new PayReq();
                    //
                    request.appId = WECHAT_APP_ID;
                    request.partnerId = PARENT_ID;
                    // 后台返回
                    request.prepayId = wxPayEntity.getPrepay_id();
                    request.packageValue = wxPayEntity.getPackageName();
                    request.nonceStr = wxPayEntity.getNoncestr();
                    request.timeStamp = wxPayEntity.getTimestamp();
                    request.sign = wxPayEntity.getSign();
                    //  LogUtils.LOG_D(getClass(), "正常调起支付.");
                    boolean sendReq = api.sendReq(request);
                    // LogUtils.LOG_D(getClass(), "支付请求发送-----" + sendReq);
    
                    return null;
                }
            }.execute();
    
        }
    
        public interface PayResultListener {
            /**
             * 阿里支付完成回掉
             */
            void aliPayCallBack();
    
            /**
             * 取消支付
             */
            void aliPayCancle();
        }
    
        private PayResultListener resultListener;
    
        public void setResultListener(PayResultListener resultListener) {
            this.resultListener = resultListener;
        }
    
        public void release() {
            mHandler.removeCallbacksAndMessages(null);
        }
    }
    

    payutils的用法,MainActivity的代码:
    在调用支付之前一定要将app注册到微信中,即执行:api.registerApp();这个方法

    调用支付宝支付的方法
    payUtils.payByAliPay(alipayEntity);
    

    需要注意的是传入的参数是服务器返回的支付宝数据的数据实体类,服务器返回的支付宝数据格式应该如下:(即message字段的数据内容通过json转换bean对象)


    支付宝支付返回的数据.png
    调用微信支付的方法
    payUtils.payByWechat(wxPayEntity);
    

    需要注意的是传入的参数,需要为服务器返回的微信支付数据的实体对象。服务器返回的格式应如下:(同样是将message字段部分转换成为bean对象)


    微信支付返回数据格式.png
    package com.example.user.paydemo;
    
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    
    import com.example.user.paydemo.bean.AlipayEntity;
    import com.example.user.paydemo.bean.WxPayEntity;
    import com.tencent.mm.opensdk.modelpay.PayResp;
    import com.tencent.mm.opensdk.openapi.IWXAPI;
    import com.tencent.mm.opensdk.openapi.WXAPIFactory;
    
    public class MainActivity extends AppCompatActivity implements PayUtils.PayResultListener {
        private PayUtils payUtils;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
    
            IWXAPI api = WXAPIFactory.createWXAPI(this, PayUtils.WECHAT_APP_ID);
            api.registerApp(PayUtils.WECHAT_APP_ID);// 将该app注册到微信
    
            payUtils = new PayUtils(api, this);
            String jsonData = "这个是后台返回给我们的支付数据";
    
            //支付方式为支付宝
            payByAliPay(jsonData);
    
            //微信支付
            payByWeChat(jsonData);
    
        }
    
        /**
         * 微信支付
         *
         * @param jsonData 后台返回的支付数据
         */
        private void payByWeChat(String jsonData) {
            WxPayEntity wxPayEntity = JsonUtils.json2Object(jsonData, WxPayEntity.class);
            payUtils.payByWechat(wxPayEntity);
        }
    
        /**
         * 支付宝支付
         *
         * @param jsonData 后台返回的支付数据
         */
        private void payByAliPay(String jsonData) {
            //将支付数据转换成为实体对象
            AlipayEntity alipayEntity = JsonUtils.json2Object(jsonData, AlipayEntity.class);
            payUtils.payByAliPay(alipayEntity);
        }
    
        @Override
        public void aliPayCallBack() {
            //付款成功的回调
        }
    
        @Override
        public void aliPayCancle() {
            //取消支付的回调
        }
    
        @Override
        protected void onDestroy() {
            super.onDestroy();
            payUtils.release();
        }
    
        /**
         * 微信支付成功
         *
         * @param payResp
         */
        public void wxPaySuccess(PayResp payResp) {
    
        }
    
        /**
         * 微信支付取消
         */
        public void wxPayCancle() {
            aliPayCancle();
        }
    }
    

    AppManager工具类:

    package com.example.user.paydemo;
    
    import android.app.Activity;
    import android.app.ActivityManager;
    import android.app.Application;
    import android.content.ComponentName;
    import android.content.Context;
    
    import java.util.Stack;
    
    /**
     * App管理Activity类
     */
    public class AppManager {
        private static Stack<Activity> activityStack = new Stack<>();
    
        /**
         * 添加Activity到堆栈
         */
        public static void addActivity(Activity activity) {
            activityStack.push(activity);
        }
    
        /**
         * 获取当前Activity(堆栈中最后一个压入的)
         */
        public static Activity currentActivity() {
            ActivityManager am = (ActivityManager) activityStack.firstElement().getSystemService(Context.ACTIVITY_SERVICE);
            ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
            Activity activity = null;
            for (Activity activityItem : activityStack) {
                if (cn.getClassName().contains(activityItem.getLocalClassName())) {
                    activity = activityItem;
                    break;
                }
            }
            return activity == null ? activityStack.lastElement() : activity;
        }
    
        /**
         * 结束当前Activity(堆栈中最后一个压入的)
         */
        public static void finishCurrentActivity() {
            Activity activity = activityStack.pop();
            activity.finish();
        }
    
        /**
         * 结束指定的Activity
         */
        public static void finishActivity(Activity activity) {
            if (activity != null) {
                if (!activity.isFinishing()) {
                    activity.finish();
                }
            }
        }
    
        /**
         * 结束指定类名的Activity
         */
        public static void finishActivity(Class<?> cls) {
            Activity factivity = null;
            for (Activity activity : activityStack) {
                if (activity.getClass().equals(cls)) {
                    factivity = activity;
                }
            }
            finishActivity(factivity);
        }
    
        /**
         * 结束所有Activity
         */
        public static void finishAllActivity() {
            for (Activity activity : activityStack) {
                if (activity != null) {
                    activity.finish();
                    activity = null;
                }
            }
            activityStack.clear();
        }
    
        /**
         * 根据class获取activity
         */
        public static Activity getBaseActivity(Class cls) {
            Activity baseActivity = null;
            for (Activity activity : activityStack) {
                if (activity.getClass().equals(cls)) {
                    baseActivity = activity;
                }
            }
            return baseActivity;
        }
    
        /**
         * 退出应用程序
         */
        public static void AppExit(Context context) {
            try {
                finishAllActivity();
                ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
                manager.killBackgroundProcesses(context.getPackageName());
                //System.exit(0);
                android.os.Process.killProcess(android.os.Process.myPid());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        public static void removeActivity(Activity activity) {
            activityStack.remove(activity);
            if (!activity.isFinishing()) {
                activity.finish();
            }
        }
    
        public static Application getApplication() {
            return currentActivity().getApplication();
        }
    }
    

    demo链接地址(无法运行,无法运行,无法运行,只是记录了主要的步骤)

    存在这么一种情况,当用户通过杀死进程的方法关闭支付的页面回到app端的时候,我们无法获取到手机的支付状态,这个时候我们就需要后台提供一个接口,来告诉app是否支付成功。

    相关文章

      网友评论

          本文标题:android支付宝,微信支付集成工具类

          本文链接:https://www.haomeiwen.com/subject/hlcbhqtx.html