支付宝和微信支付集成

支付宝和微信支付的方法


	Activity activity;//上下文对象
    IWXAPI api;//微信支付的api对象


/**
     * 处理支付宝逻辑的handler
     * SDK_PAY_FLAG:int类型,自定义对象,值为1,判断支付结果
     * SDK_AUTH_FLAG:int类型,自定义对象,值为2,判断是否授权支付宝,这个判断没用到,可不写
     */
@SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler(){
        @SuppressLint("LongLogTag")
        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what){
            	//判断支付结果
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果,请商户依赖服务端的异步通知结果。同步通知结果,仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    Log.d("resultStatus:************:",resultStatus+"**************"+resultInfo);

                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功,需要依赖服务端的异步通知。
                        showAlert(activity, activity.getString("支付成功"));
                    } else {
                        // 该笔订单真实的支付结果,需要依赖服务端的异步通知。
                        showAlert(activity, activity.getString("支付未完成"));
                    }
                    break;
                }
                //判断支付宝授权
                case SDK_AUTH_FLAG: {
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();
                    Log.d("RESULTSTATUS:","返回码为:"+resultStatus);
                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功,具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id,调支付时作为参数extern_token 的value
                        // 传入,则支付账户为该授权账户
                        showAlert(activity, activity.getString("授权成功")) + authResult);
                    } else {
                        // 其他状态值则为授权失败
                        showAlert(activity, activity.getString("授权失败")) + authResult);
                    }
                    break;
                }
                default:
                    break;
            }

            super.handleMessage(msg);
        }
    };


    @SuppressLint("JavascriptInterface")
    @JavascriptInterface
    public void payV2(final String url, String type){

        Log.d("OkHttpSHUJU:","URL路径的数据:"+url);
        Log.d("OkHttpSHUJU:","类型号的数据:"+type);



        /**
         * type:0
         * 调起支付宝支付
         */
        if (type.equals("0")){


            /**
             * 判断是否安装支付宝App
             */
            if (Util.checkAliPayInstalled(activity,"alipays://platformapi/startApp")){


                OkhttpUtil.getmInstance().doGet(url, new OkhttpCallBack() {
                    @Override
                    public void failure(String msg) {
                        Log.d("OKHTTP_PAY","错误信息:"+msg);
                    }

                    @Override
                    public void success(String result) {


                        if (result.equals("404 Not Found")){

                            Toast.makeText(activity,"请求路径错误",Toast.LENGTH_SHORT).show();

                        } else {

                            Log.d("OKHTTP_PAY","请求成功:"+result);
                            //解析bean类
                            payBean = new Gson().fromJson(result,PayBean.class);

                            Log.d("ZFB_CODE:","支付宝响应码:"+payBean.getCode());

                            if (payBean.getCode() == 200 ){
                                final String orderInfo = payBean.getData().getPayCode();
                                Log.d("ORDERINFO:",""+orderInfo);

                                Runnable payRunnable = new Runnable() {
                                    @Override
                                    public void run() {

                                        PayTask alipay = new PayTask(activity);
                                        Map<String,String> 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();

                            } else {
                                Toast.makeText(activity,"服务器繁忙,请稍后重试!",Toast.LENGTH_SHORT).show();
                            }


                        }

                    }
                });


            } else {

                Toast toast=Toast.makeText(activity,"未安装支付宝",Toast.LENGTH_LONG   );
                toast.setGravity(Gravity.CENTER, 0, 0);

                toast.setText("未安装支付宝");
                toast.show();
            }





            /**
             * type:1
             * 调起微信支付,微信支付的东西只有下面这个方法
             * 和一个判断手机是否安装微信的方法和微信的bean类,其他的跟微信没关系,都是支付宝的类
             */
        }else if (type.equals("1")){


            /**
             * 判断是否安装微信App
             */
            if(Util.checkAppInstalled(activity,"com.tencent.mm")) {


                /**
                 * 微信支付
                 */
                OkhttpUtil.getmInstance().doGet(url, new OkhttpCallBack() {
                    @Override
                    public void failure(String msg) {
                        Log.d("OKHTTP_PAY","错误信息:"+msg);
                    }

                    @Override
                    public void success(String result) {
                        Log.d("OKHTTP_PAY","请求成功:"+result);

                        if (result.equals("404 Not Found")){

                            Toast.makeText(activity,"请求路径错误",Toast.LENGTH_SHORT).show();

                        }else {

                            wxPayBean = new Gson().fromJson(result,WxPayBean.class);


                            Log.d("WX_CODE:","微信响应码:"+wxPayBean.getCode());

                            if (wxPayBean.getCode() == 200){

								
                                api = WXAPIFactory.createWXAPI(activity,null);
                                
                                Log.d("WXAPPID:",""+wxPayBean.getData().getAppid());
                                //创建appid到微信
                                api.registerApp(wxPayBean.getData().getAppid());

                                Runnable payRunnable = new Runnable() {
                                    @Override
                                    public void run() {

                                        PayReq request = new PayReq();//调起微信的对象
										
										//下面是一些微信支付需要的参数,微信api文档里有介绍
                                        request.appId = wxPayBean.getData().getAppid();
                                        request.partnerId = wxPayBean.getData().getPartnerid();
                                        request.prepayId = wxPayBean.getData().getPrepayid();
                                        request.packageValue = wxPayBean.getData().getPackageX();
                                        request.nonceStr = wxPayBean.getData().getNoncestr();
                                        request.timeStamp = wxPayBean.getData().getTimestamp();
                                        request.sign = wxPayBean.getData().getSign();

                                        api.sendReq(request);//发送调起微信的请求
                                    }
                                };
                                Thread payThread = new Thread(payRunnable);
                                payThread.start();


                            } else {
                                Toast.makeText(activity,"服务器繁忙,请稍后重试!",Toast.LENGTH_SHORT).show();
                            }

                        }

                    }
                });


            }else{

                Toast toast=Toast.makeText(activity,"未安装微信",Toast.LENGTH_LONG   );
                toast.setGravity(Gravity.CENTER, 0, 0);

                toast.setText("未安装微信");
                toast.show();
            }


        }

    }

//集成微信的东西,应用的包名和签名必须跟微信平台创建应用的包名和签名一致,不然都是白给



//下面这两个方法是支付宝支付成功或失败时候的弹框
 @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    private static void showAlert(Context ctx, String info) {
        showAlert(ctx, info, null);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    private static void showAlert(Context ctx, String info, DialogInterface.OnDismissListener onDismiss) {
        new AlertDialog.Builder(ctx)
                .setMessage(info)
                .setPositiveButton(R.string.confirm, null)
                .setOnDismissListener(onDismiss)
                .show();
    }



下面是支付宝的两个工具类,复制粘贴就可以了

这是第一个

package com.example.pingba.pay;

import android.text.TextUtils;

import java.util.Map;

public class AuthResult {

    private String resultStatus;
    private String result;
    private String memo;
    private String resultCode;
    private String authCode;
    private String alipayOpenId;

    public AuthResult(Map<String,String> rawResult, boolean removeBrackets) {
        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);
            }
        }

        String[] resultValue = result.split("&");
        for (String value : resultValue) {
            if (value.startsWith("alipay_open_id")) {
                alipayOpenId = removeBrackets(getValue("alipay_open_id=", value), removeBrackets);
                continue;
            }
            if (value.startsWith("auth_code")) {
                authCode = removeBrackets(getValue("auth_code=", value), removeBrackets);
                continue;
            }
            if (value.startsWith("result_code")) {
                resultCode = removeBrackets(getValue("result_code=", value), removeBrackets);
                continue;
            }
        }
    }

    private String removeBrackets(String str, boolean remove) {
        if (remove) {
            if (!TextUtils.isEmpty(str)) {
                if (str.startsWith("\"")) {
                    str = str.replaceFirst("\"", "");
                }
                if (str.endsWith("\"")) {
                    str = str.substring(0, str.length() - 1);
                }
            }
        }
        return str;
    }

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

    private String getValue(String header, String data) {
        return data.substring(header.length(), data.length());
    }

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

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

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

    /**
     * @return the resultCode
     */
    public String getResultCode() {
        return resultCode;
    }

    /**
     * @return the authCode
     */
    public String getAuthCode() {
        return authCode;
    }

    /**
     * @return the alipayOpenId
     */
    public String getAlipayOpenId() {
        return alipayOpenId;
    }
}

支付宝第二个工具类

package com.example.pingba.pay;

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;
    }
}

判断是否安装app的方法

//这个是微信的,传入上下文和包名就可以了## 标题
 public static boolean checkAppInstalled(Activity context, String pkgName) {
        if (pkgName== null || pkgName.isEmpty()) {
            return false;
        }
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(pkgName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            packageInfo = null;
            e.printStackTrace();
        }
        if(packageInfo == null) {
            return false;
        } else {
            return true;//true为安装了,false为未安装
        }
    }


    /**
     * 判断是否安装支付宝
     * @param context
     * @param pkgName
     * @return
     */
    public static boolean checkAliPayInstalled(Activity context, String pkgName) {
        if (pkgName== null || pkgName.isEmpty()) {
            return false;
        }
        Uri uri = Uri.parse("alipays://platformapi/startApp");
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);

        ComponentName componentName = intent.resolveActivity(context.getPackageManager());

        return componentName != null;
    }

至于okhttp的什么get请求或post请求就不粘了,bean类也不粘贴了,微信和支付宝的什么aar包和jar包怎么配置啥的,可以去官方文档查看,其他应该没啥了

你可能感兴趣的:(支付宝和微信支付集成)