要致富,先接支付!
最近公司需求的原因,APP需要接入支付收费功能,所以趁此机会,记录一下(绝对不是因为官网的文档有点烂,特别微信的)
一、接入支付宝支付
支付宝支付官网
支付宝的接入前准备工作:
①下载aar库,并放在libs中
// 支付宝 SDK AAR 包所需的配置
compile (name: 'alipaysdk-15.8.03.210428205839', ext: 'aar')
这样支付宝的准备工作已经做好了,接下来就是怎么写支付逻辑了。为了以后方便修改、增加支付方式等迭代,代码上需要一点设计:
首先定义一个支付接口,作用是统一支付的入口。
/***
* 支付统一接口
*/
interface IAppPay {
fun pay(orderInfo:String)
fun result()
}
然后编写支付宝的支付逻辑:
class AliPay(val activity: Activity) : IAppPay {
private val handler: Handler
companion object {
const val SDK_PAY_FLAG = 1
}
init {
this.handler = PayHandler(activity)
}
override fun pay(orderInfo: String) {
val runnable = Runnable {
val payTask = PayTask(activity)
val result: MutableMap = payTask.payV2(orderInfo, true)
Log.d("msp", result.toString())
val msg = Message()
msg.what = SDK_PAY_FLAG
msg.obj = result
handler.sendMessage(msg)
}
val payThread = Thread(runnable)
payThread.start()
}
override fun result() {
TODO("Not yet implemented")
}
private class PayHandler(activity: Activity) : Handler() {
private val activityWeakReference: WeakReference?
init {
activityWeakReference = WeakReference(activity)
}
override fun handleMessage(msg: Message) {
super.handleMessage(msg)
if (null != activityWeakReference) {
val activity = activityWeakReference.get()
when (msg.what) {
SDK_PAY_FLAG -> {
val payResult = PayResult(msg.obj as Map)
//对于支付结果,请商户依赖服务端的异步通知结果。同步通知结果,仅作为支付结束的通知。
val resultInfo: String = payResult.result// 同步返回需要验证的信息
// 判断resultStatus 为9000则代表支付成功
when(payResult.resultStatus) {
"9000" -> {
AppContext.showToast("支付成功!")
}
"6001"->{
AppContext.showToast("已取消支付!")
}
else -> {
AppContext.showToast(payResult.toString())
}
}
}
}
}
}
}
}
PayResult
class PayResult {
var resultStatus: String = ""
var result: String = ""
private var memo: String = ""
constructor(rawResult: Map?){
if (rawResult == null) {
memo = ""
return
}
for (key in rawResult.keys) {
when {
TextUtils.equals(key, "resultStatus") -> {
resultStatus = rawResult[key]?:""
}
TextUtils.equals(key, "result") -> {
result = rawResult[key]?:""
}
TextUtils.equals(key, "memo") -> {
memo = rawResult[key]?:""
}
}
}
}
override fun toString(): String {
return ("resultStatus={" + resultStatus + "};memo={" + memo
+ "};result={" + result + "}")
}
}
最后增加一个统一管理器
/***
* 支付中心,统一管理各种支付方式
*/
class PayControlCenter {
companion object{
const val PAY_TYPE_ALI = 0X1001
const val PAY_TYPE_WECHAT = 0X1002
fun pay(activity: Activity,orderInfo:String,type:Int){
when(type){
PAY_TYPE_ALI ->{
val pay: IAppPay = AliPay(activity)
pay.pay(orderInfo)
}
PAY_TYPE_WECHAT ->{
val pay:IAppPay = WeChatPay(activity)
pay.pay(orderInfo)
}
}
}
}
}
使用方法:
PayControlCenter.pay(
this@VipOpenActivity,
payInfo, PayControlCenter.PAY_TYPE_ALI )
二、接入微信支付
微信支付官网
准备工作:
①在build.gradle中,引入微信支付库。
implementation 'com.tencent.mm.opensdk:wechat-sdk-android-with-mta:5.3.1'
②在项目的根包名下,新建一个包,包名为wxapi,包里新建一个类WXPayEntryActivity
class WXPayEntryActivity : Activity(), IWXAPIEventHandler {
private var api: IWXAPI? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
api = WXAPIFactory.createWXAPI(this, APPConfig.WECHAT_APP_ID, false)
try {
api?.handleIntent(intent, this)
} catch (e: Exception) {
}
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
setIntent(intent)
api?.handleIntent(intent, this)
}
override fun onReq(req: BaseReq?) {
}
override fun onResp(resp: BaseResp?) {
val response: PayResp = resp as PayResp
val extData = response.extData
if (resp.type == ConstantsAPI.COMMAND_PAY_BY_WX) {
when (resp.errCode) {
0 -> {//支付成功
ToastUtil.showToast("支付成功")
}
-1 -> {//支付失败
ToastUtil.showToast("支付失败")
}
-2 -> {//取消支付
ToastUtil.showToast("取消支付")
}
}
}
finish()
}
}
③新建AppRegister类,位置随意
public class AppRegister extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
final IWXAPI api = WXAPIFactory.createWXAPI(context, null,false);
// 将该app注册到微信
api.registerApp(APPConfig.WECHAT_APP_ID);
}
}
④在AndroidManifest中注册
最后就是微信支付的具体逻辑了。
class WeChatPay(val activity: Activity) : IAppPay {
private val api: IWXAPI = WXAPIFactory.createWXAPI(activity, APPConfig.WECHAT_APP_ID, false)
override fun pay(orderInfo: String) {
//检查是否已经安装了微信
if (checkWeChatInstall()) {
val runnable = Runnable {
val jsonObject: JSONObject = JSONObject(orderInfo)
if (jsonObject != null) {
val req: PayReq = PayReq()
req.appId = jsonObject.optString("appId")
req.partnerId = jsonObject.optString("partnerId")
req.prepayId = jsonObject.optString("prepayId")
req.packageValue = jsonObject.optString("packageValue")
req.nonceStr = jsonObject.optString("nonceStr")
req.timeStamp = jsonObject.optString("timeStamp")
req.sign = jsonObject.optString("sign")
api.sendReq(req)
} else {
ToastUtil.showToast("订单有误!")
}
}
val payThread = Thread(runnable)
payThread.start()
} else {
ToastUtil.showToast("尚未安装微信,请安装微信支付!")
}
}
override fun result() {
}
private fun checkWeChatInstall(): Boolean {
return api.isWXAppInstalled
}
}
调用方法,和支付宝的是一致的,只是参数换成微信的就行。
整体结构是这样:
记录完毕!