整合微信支付 SDK 時,必須在指定包名下實作 WXPayEntryActivity 並覆寫 onResp 接收支付結果回調。本文整理關鍵步驟、常見錯誤與安全驗證流程。
你的包名.wxapi (如 com.example.app.wxapi)。WXPayEntryActivity。IWXAPIEventHandler 介面。package com.example.app.wxapi
import android.app.Activity
import android.os.Bundle
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.IWXAPIEventHandler
class WXPayEntryActivity : Activity(), IWXAPIEventHandler {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// 微信 SDK 會自動將回調轉發給 onResp,此處無需 setContentView
// 若需顯示載入中可自行加載佈局
}
override fun onReq(req: BaseReq?) { /* 支付流程不需處理 */ }
override fun onResp(resp: BaseResp?) {
val payResp = resp as? PayResp
val errCode = payResp?.errCode ?: -1
when (errCode) {
BaseResp.ErrCode.ERR_OK -> {
// 支付成功:務必去後端驗證訂單狀態,再展示成功頁
verifyOrderWithServer(payResp.prepayId)
}
BaseResp.ErrCode.ERR_USER_CANCEL -> toast("使用者取消支付")
BaseResp.ErrCode.ERR_COMM, BaseResp.ErrCode.ERR_SENT_FAILED -> toast("支付失敗,請重試")
else -> toast("未知錯誤: $errCode")
}
finish() // 關閉透明 Activity
}
private fun verifyOrderWithServer(prepayId: String?) {
// TODO: 呼叫後端 API 驗證訂單狀態,成功後再導向訂單詳情頁
}
}
<activity
android:name=".wxapi.WXPayEntryActivity"
android:exported="true"
android:launchMode="singleTop"
android:theme="@android:style/Theme.Translucent.NoTitleBar">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="wx<你的AppID>" />
</intent-filter>
</activity>
wxapi.WXPayEntryActivity not found。onResp 運行在主執行緒,**嚴禁**直接做網路請求,必須切換到 IO 執行緒 (Coroutine/RxJava/Thread)。onResp 與 onNewIntent 同時觸發,需去重 (用訂單號 Set 記錄已處理)。onCreate 呼叫 finish() 僅作為回調入口。| errCode | 常數 | 含義 |
|---|---|---|
| 0 | ERR_OK | 成功 |
| -1 | ERR_COMM | 一般錯誤 (網路、簽名錯誤) |
| -2 | ERR_USER_CANCEL | 使用者取消 |
| -3 | ERR_SENT_FAILED | 發送失敗 |
| -4 | ERR_AUTH_DENIED | 授權失敗 |
| -5 | ERR_UNSUPPORT | 不支援的 API |
嚴格遵循微信規範實作回調入口,並配合後端驗證,才能確保支付流程安全可靠。