支付宝支付接入+微信支付

去年写的支付宝支付,今年项目里需要又接入了一遍,发现开发文档更新有点慢啊。自己写个demo吧,省的下次又忘记了怎么抄。

下载sdk导入

支付宝:

支付宝支付接入+微信支付_第1张图片

微信:

//微信支付
compile 'com.tencent.mm.opensdk:wechat-sdk-android-with-mta:+'

AndroidManifest

<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" />

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


        
        <activity
            android:name=".wxapi.WXPayEntryActivity"
            android:configChanges="keyboardHidden|orientation|screenSize"
            android:exported="true"
            android:launchMode="singleTop"
            android:screenOrientation="portrait"/>
        

OrderPayActivity

public class OrderPayActivity extends BaseActivity {
    @Bind(R.id.headLeftImg)
    ImageView headLeftImg;
    @Bind(R.id.headTitleView)
    TextView headTitleView;
    @Bind(R.id.tv_name)
    TextView tvName;
    @Bind(R.id.tv_price)
    TextView tvPrice;
    @Bind(R.id.iv_weixin)
    ImageView ivWeixin;
    @Bind(R.id.rl_weixin)
    RelativeLayout rlWeixin;
    @Bind(R.id.iv_alipay)
    ImageView ivAlipay;
    @Bind(R.id.rl_alipay)
    RelativeLayout rlAlipay;

    private static final int SDK_PAY_FLAG = 1;
    private String paytype;//alipay:支付宝    tenpay:微信
    private String name;
    private String totalprice;
    private String orderno;
    private String orderid;

    MyOderBean.DataBean orderBean;

    @Override
    public int getLayoutId() {
        return R.layout.activity_orderpay;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        headLeftImg.setVisibility(View.VISIBLE);
        headTitleView.setText("订单支付");
    }

    @Override
    public void initData() {
        //        clientId= SpUtil.getSpString(Constant.SpConstants.USER_INFO,Constant.SpConstants.ClientId,"");

        orderBean = (MyOderBean.DataBean) getIntent().getSerializableExtra("orderBean");
        if (orderBean != null) {
            name = orderBean.getItemName();
            totalprice = orderBean.getTotalPrice() + "";
            orderid = orderBean.getOrderId() + "";
            orderno = orderBean.getOrderNum();
        } else {
            name = getIntent().getStringExtra("name");
            totalprice = getIntent().getStringExtra("totalprice");
            orderno = getIntent().getStringExtra("orderno");
            orderid = getIntent().getStringExtra("orderid");
        }
    }

    @Override
    public void ctlDV() {
        tvName.setText(name);
        tvPrice.setText("¥" + totalprice);
    }

    @Override
    public boolean haveEventBus() {
        return false;
    }

    boolean isweixinChose = false;
    boolean isalipayChose = false;

    @OnClick({R.id.headLeftImg, R.id.rl_weixin, R.id.rl_alipay, R.id.gopay})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.headLeftImg:
                finish();
                break;
            case R.id.rl_weixin:
                if (!isweixinChose) {
                    ivWeixin.setImageResource(R.mipmap.chose);
                    isweixinChose = true;
                    isalipayChose = false;
                    ivAlipay.setImageResource(R.mipmap.nochose);
                } else {
                    ivWeixin.setImageResource(R.mipmap.nochose);
                    isweixinChose = false;
                }
                break;
            case R.id.rl_alipay:
                if (!isalipayChose) {
                    ivAlipay.setImageResource(R.mipmap.chose);
                    isalipayChose = true;
                    isweixinChose = false;
                    ivWeixin.setImageResource(R.mipmap.nochose);
                } else {
                    ivAlipay.setImageResource(R.mipmap.nochose);
                    isalipayChose = false;
                }
                break;
            case R.id.gopay:
                //去支付
                if (isalipayChose) {
                    alipay();
                } else if (isweixinChose) {
                    tenpay();
                }
                break;
        }
    }

    private void alipay() {
        showProgressDialog();
        ApiWrapper apiWrapper = new ApiWrapper();
        apiWrapper.pay("alipay", orderno, "0.01", orderid).enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                dismissProgressDialog();
                msg_d_s_Bean msgDSBean = response.body();
                if (msgDSBean.isSuccess()) {
                    payAli(msgDSBean.getData());

                } else {
                    ToastUtils.showToast(mContext, msgDSBean.getMessage());
                }
            }

            @Override
            public void onFailure(Call call, Throwable t) {
                dismissProgressDialog();
            }
        });
    }

    private void tenpay() {
        showProgressDialog();
        ApiWrapper apiWrapper = new ApiWrapper();
        apiWrapper.tenpay("tenpay", orderno, "0.01", orderid).enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                dismissProgressDialog();
                WxpayBean wxpayBean = response.body();
                if (wxpayBean.isSuccess() && wxpayBean.getData() != null) {
                    WxpayBean.DataBean dataBean = wxpayBean.getData();
                    wxPay(dataBean);
                } else {
                    ToastUtils.showToast(mContext, wxpayBean.getMessage());
                }
            }
            @Override
            public void onFailure(Call call, Throwable t) {
                dismissProgressDialog();
            }
        });
    }

    //支付宝支付
    private void payAli(final String orderInfo) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(OrderPayActivity.this);
                Map map = alipay.payV2(orderInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = map;
                payhandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /**
     * 支付宝支付结果
     */
    @SuppressLint("HandlerLeak")
    private Handler payhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            PayResult payResult = new PayResult((Map) msg.obj);
            /**
             对于支付结果,请商户依赖服务端的异步通知结果。同步通知结果,仅作为支付结束的通知。
             */
            String resultInfo = payResult.getResult();// 同步返回需要验证的信息
            String resultStatus = payResult.getResultStatus();
            Log.i("TAG", "=====handleMessage: " + resultInfo + "====" + resultStatus);
            //   判断resultStatus 为9000则代表支付成功
            if (TextUtils.equals(resultStatus, "9000")) {
                // 该笔订单是否真实支付成功,需要依赖服务端的异步通知。
                Toast.makeText(mContext, "支付成功", Toast.LENGTH_SHORT).show();
                Intent intent1 = new Intent(mContext, MyOderActivity.class);
                startActivity(intent1);
                finish();
            } else {
                // 该笔订单真实的支付结果,需要依赖服务端的异步通知。
                //Toast.makeText(mContext, "支付失败..", Toast.LENGTH_SHORT).show();
            }
        }
    };

    //微信支付
    private IWXAPI api;

    private void wxPay(final WxpayBean.DataBean orderInfo) {
        //        spUtil.putStringValue("app_id", orderInfo.getAppid());
        SpUtil.saveSpString(Constant.SpConstants.USER_INFO, "app_id", orderInfo.getAppid());
        api = WXAPIFactory.createWXAPI(this, null);
        api.registerApp(orderInfo.getAppid());
        new Thread(new Runnable() {
            @Override
            public void run() {
                PayReq req = new PayReq();
                req.partnerId = orderInfo.getPartnerid();
                req.sign = orderInfo.getSign();
                req.prepayId = orderInfo.getPrepayid();
                req.appId = orderInfo.getAppid();
                req.timeStamp = orderInfo.getTimestamp();
                req.packageValue = orderInfo.getPackageX();
                req.nonceStr = orderInfo.getNoncestr();
                api.sendReq(req);
            }
        }).start();

    }

}

PayResult


import android.text.TextUtils;

import java.util.Map;

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

    public PayResult(Map 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;
    }
}

微信支付回调

package com.espar.www.esparclientios.wxapi;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import com.espar.www.esparclientios.activity.mine.MyOderActivity;
import com.espar.www.esparclientios.constants.Constant;
import com.espar.www.esparclientios.utils.SpUtil;
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;


public class WXPayEntryActivity extends AppCompatActivity implements IWXAPIEventHandler {
    private Context mContext = this;
    private IWXAPI api;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i("TAG", "onCreate:==== 回调");
        String app_id = SpUtil.getSpString(Constant.SpConstants.USER_INFO,"app_id","");
        api = WXAPIFactory.createWXAPI(this, app_id, false);
        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) {
        Log.i("TAG", "onResp:============ " + resp.errCode);
        if (resp.errCode == 0) {//成功
            Intent intent1 = new Intent(mContext, MyOderActivity.class);
            startActivity(intent1);
            finish();
        } else {
            boolean b = resp.checkArgs();
            String errStr = resp.errStr;
            String openId = resp.openId;
            Log.i("TAG", "onResp: " + errStr + "+" + openId + "+" + resp.toString());
            finish();
        }
    }

    /**
     * 显示一个Toast信息
     *
     * @param content
     */
    private Toast mToast = null;

    public void showToast(String content) {
        if (mToast == null) {
            mToast = Toast.makeText(this, content, Toast.LENGTH_SHORT);
        } else {

            mToast.setText(content);
        }
        mToast.show();
    }
}

你可能感兴趣的:(第三方)