The second encapsulation of Wechat and Alipay

Secondary encapsulation of wechat and Alipay payment based on factory mode.

1, first wrap an abstract class BasePay, wrap an abstract method pay
Abstract class BasePay {/** * abstract payment method * @param activity activity * @param orderStr calls the argument that needs to be passed when the payment is called * @param callback payment callback */ abstract fun pay(activity: Activity, orderStr: String, callback: OnPayCallback? = null) }Copy the code
2. Define an OnPayCallback interface that can be extended to call back and forth payment success and payment failure
interface OnPayCallback {

    fun onPaySuccess()

    fun onPayFailed()

}
Copy the code
3. Encapsulate AliPay payment, define a class AliPay, inherit BasePay to rewrite the Pay method, and call AliPay payment in the pay method
class AliPay : BasePay() {... override fun pay(activity: Activity, orderStr: String, callback: OnPayCallback?) {doAsync {
            val aliPay = PayTask(activity)
            val result = aliPay.payV2(orderStr, true) uiThread {val payResult = payResult (result) val resultStatus = payResult. ResultStatus // If resultStatus is 9000, the payment is successfulif (TextUtils.equals(resultStatus, "9000")) { callback? .onPaySuccess() // Paysuccess callback}else{ callback? .onPayFailed() // Payment failure callback}}}}}Copy the code
4. Encapsulate wechat pay, define a class WxPay, inherit BasePay to rewrite the pay method, and call wechat pay in the pay method
class WxPay : BasePay() {
···
    private var mWxApi: IWXAPI? = null
    private val gson = Gson()

    override fun pay(activity: Activity, orderStr: String, callback: OnPayCallback?) {
        mWxApi = WXAPIFactory.createWXAPI(mActivity, Constants.WX_APP_KEY)
        val payInfo = gson.fromJson<CreatePayBean>(orderStr, CreatePayBean::class.java)
        val req = PayReq()
        req.appId = payInfo?.appid
        req.partnerId = payInfo?.partnerid
        req.prepayId = payInfo?.prepayid
        req.nonceStr = payInfo?.noncestr
        req.packageValue = payInfo?.packageValue
        req.timeStamp = payInfo?.timestamp
        req.sign = payInfo?.sign
        mWxApi?.sendReq(req)
    }
}
Copy the code

Since wechat Payment requires the support of class WXPayEntryActivity, whether the payment is successful or not should be processed in class WXPayEntryActivity. Here, the result of EventBus processing is used

public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {
    private static final String TAG = "MicroMsg.SDKSample.WXPayEntryActivity";
    private IWXAPI api;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        api = WXAPIFactory.createWXAPI(this, Constants.WX_APP_KEY);
        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.d("WxPayEntryActivity"."onPayFinish, errCode = " + resp.errCode);
        if(resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) { WxPayEvent event = new WxPayEvent(resp.errCode); EventBus.getDefault().post(event); finish(); }}}Copy the code

Receive messages sent by EventBus in an Activity or Fragment

@subscribe (threadMode = threadmode.main) {Subscribe(threadMode = threadmode.main) {if (event.errorCode == 0) {
            onPaySuccess()
        } else {
            onPayFailed()
        }
    }
Copy the code
5. Create a payment factory class PayFactory to encapsulate both payment methods
object PayFactory {
    fun createPay(payType: PayType): BasePay? {
        return when (payType) {
            PayType.ALI -> {
                AliPay.getInstance()
            }
            PayType.WX -> {
                WxPay.getInstance()
            }
        }
    }
}
Copy the code

Create an enumeration class for the payment method

enum class PayType {
    ALI, WX
}
Copy the code
6. Use two payment methods
  • Alipay Payment
PayFactory.createPay(PayType.ALI)? .pay(this@MainActivity,"", object : OnPayCallback{
                override fun onPaySuccess() {
                }

                override fun onPayFailed() {}})Copy the code
  • WeChat pay
PayFactory.createPay(PayType.WX)? .pay(this@MainActivity,"")
Copy the code
@subscribe (threadMode = threadmode.main) {Subscribe(threadMode = threadmode.main) {if (event.errorCode == 0) {
        onPaySuccess()
    } else {
        onPayFailed()
    }
}
Copy the code

Finally, attach the source code address:Github.com/iceCola7/Pa…