背景
? ? ? ?最近公司想把游戲包上到各個渠道上,因此需要對接各種渠道,渠道如下,oppo、vivo、華為、小米、應用寶、taptap、榮耀、三星等應用渠道? ? ? ? ? ? ? ?
?????????主要就是對接登錄、支付接口(后續不知道會不會有其他的),由于登錄、支付前置都是一些通用的邏輯處理,所以一開始我就想到了要用設計模式來做,下面我畫了一個圖,大家可以參考看一下 ? ? ? ?
這里值得一提的是目前oppo比常規的渠道多了一個發貨通知的接口,我把幾個接口都說說明下 ? ? ? ?
登錄:用戶通過oppo、vivo等進行登錄并綁定我們內部賬號中 ? ? ? ?
支付回調:用戶使用oppo支付成功后要通知我們用戶下單成功,我們需要進行處理發貨 ? ? ? ?
發貨通知:我們發貨成功后通知oppo發貨成功了 ? ? ? ?
前面兩個接口其實很好理解,主要是發貨通知,官方的文檔如下,看了也許你就明白了,如下
? ? ?如果 OPPO 服務端超過2 個小時仍未收到游戲服務端的發貨結果請求,則代表該筆訂單發貨失敗,將進入可退款狀態,用戶可自助選擇是否退款,如果用戶選擇退款,將進入OPPO 退款流程 ? ? ? ?
對了沒錯,用戶可以退款,我認為就是在對標蘋果吧,目前看小米和vivo都不需要有這個接口
流程圖
代碼邏輯
? ? ? ? 上面的就是設計圖,這里再簡單的說下代碼的結構邏輯是咋樣的,其實做過挺多次類似的處理了,這兩種模式的設計還是挺有意義的,以下只是稍微說下大概的方式
AbstractChannelStrategy
@Slf4j
public abstract class AbstractChannelStrategy{@Resourceprotected ZXCUserParentDao userParentDao;@Resourceprotected ZXCUsermpl userRepo;@Resourceprivate ZXCOrderoDao orderInfoDao;@Resourceprotected ApplicationContext applicationContext;@Resourceprotected ZXCAppRepoImpl gameAppRepo;//獲取用戶注冊類型public abstract UserTypeEnum getUserRegisterTypeEnum();//獲取回調Url地址protected abstract String getCallBackUrlSuffix();//真正的支付成功處理public abstract void doNotifyOrderHandle(ChannelNotifyBaseBo notifyBaseBo, ChannelNotifyOrderResultBO notifyOrderResultBO, OrderInfo orderInfo) throws Exception;//游戲發貨成功后的處理protected abstract DeliveryCallBackResultBo doDeliveryCallback(OrderInfo orderInfo, GameApp gameApp) throws Exception;//允許子類校驗訂單的其他信息protected void checkOrderOtherInfo(OrderInfo orderInfo){}public boolean notifyOrderHandle(ChannelNotifyBaseBo notifyBaseBo) {try {if(notifyBaseBo == null) {return false;}//檢查訂單基礎信息OrderInfo orderInfo = commonOrderCheck(notifyBaseBo.getOrderNumber());checkOrderOtherInfo(orderInfo);ChannelNotifyOrderResultBO notifyOrderResultBO = new ChannelNotifyOrderResultBO();doNotifyOrderHandle(notifyBaseBo, notifyOrderResultBO, orderInfo);boolean success = notifyOrderResultBO.isSuccess();//成功后處理后續if(success) {log.info("notifyOrderHandle-訂單號{}處理成功,進行后續處理", orderInfo.getOrderNumber());successOrder(orderInfo, notifyOrderResultBO.getTradeNo());}return success;} catch (Exception e) {log.error("doNotifyOrderHandle出現異常", e);throw new AppException(ErrorCode.SYS_OPERATOR_ERROR.code(), "doNotifyOrderHandle調用時出現異常");}}public boolean deliveryCallback(String orderNumber) {OrderInfo orderInfo = assertOrderInfo(orderNumber);GameApp gameApp = gameAppRepo.getByAppNumber(orderInfo.getAppNumber());if(!Objects.equals(channelOrderRel.getRequestStatus(), 0)) {log.info("AbstractChannelAccountStrategy-deliveryCallback訂單號為{}的請求狀態不為未處理,無須處理,此時狀態為{},來源為{}", orderNumber, channelOrderRel.getRequestStatus(), getLogSourceName());return true;}try {DeliveryCallBackResultBo deliveryCallBackResultBo = doDeliveryCallback(orderInfo, gameApp);boolean success = deliveryCallBackResultBo.isSuccess();//更新狀態和次數channelOrderRel.setHttpContent(deliveryCallBackResultBo.getHttpContent());channelOrderRel.setRequestStatus(success ? 1 : null);int update = channelOrderRelService.update(channelOrderRel);log.info("deliveryCallback-處理完成,更新的訂單號為{},關聯的channelOrderRel主鍵id為{},影響行數為{}", orderNumber, channelOrderRel.getId(), update);return success;} catch (Exception e) {log.error("AbstractChannelAccountStrategy-deliveryCallback訂單號為{}的請求處理出現異常,來源為{}", orderNumber, getLogSourceName(), e);return false;}}protected OrderInfo commonOrderCheck(String orderNumber) {OrderInfo orderInfo = assertOrderInfo(orderNumber);if(orderInfo.getPayWay() != null && !Objects.equals(getOrderPayWay().getCode(), orderInfo.getPayWay())) {throw new ZXCException(ZXCCode.OPERATOR_ERROR.code(), "AbstractChannelAccountStrategy-訂單號支付方式不對,此時訂單號為" + orderNumber);}return orderInfo;}private OrderInfo assertOrderInfo(String orderNumber) {OrderInfo orderInfo = orderInfoDao.getByOrderNumber(orderNumber);if(orderInfo == null) {throw new AppException(ErrorCode.NOT_FOUND_DATA.code(), "AbstractChannelAccountStrategy-找不到關聯的訂單號數據,此時訂單號為" + orderNumber);}return orderInfo;}private void successOrder(OrderInfo orderInfo, String tradeNo) {boolean updated = discountsService.updateOrderStatusAndDisCount(orderInfo, tradeNo);if(updated){// 發送事件applicationContext.publishEvent(new PaySuccessEvent(this, new PaySuccessEvent.PaySuccessEventData(orderInfo.getOrderNumber())));}}public String buildCallBackUrl() {//校驗及簡單處理一下數據String callBackUrlSuffix = getCallBackUrlSuffix();if(StringUtil.isBlank(callBackUrlSuffix)) {throw new AppException("未配置回調地址");}if(!Objects.equals("/", callBackUrlSuffix.substring(0, 1))) {callBackUrlSuffix = "/" + callBackUrlSuffix;}String callBackUrlPrefix = "https://test.cn/v1/pay/callback";if(isLine()) {callBackUrlPrefix = "https://prod.cn/v1/pay/callback";}return callBackUrlPrefix + callBackUrlSuffix;}
雖然上面那個看起來很復雜,但是主要是子類方便,這里提供其中一個實現類
OppoStrategyImpl
@Slf4j
@Component
public class OppoStrategyImpl extends AbstractChannelAccountStrategy {@Overridepublic UserTypeEnum getUserRegisterTypeEnum() {return UserTypeEnum.OPPO_USER;}@Overrideprotected String getCallBackUrlSuffix() {return "/oppo/callback";}@Overridepublic void doNotifyOrderHandle(ChannelNotifyBaseBo notifyBaseBo, ChannelNotifyOrderResultBO notifyOrderResultBO, OrderInfo orderInfo) throws Exception {OppoOrderNotifyBo oppoOrderNotifyBo = (OppoOrderNotifyBo) notifyBaseBo; //強制對象,幾乎是不可能報錯的,除非調用端出了問題//驗證簽名,這里是用oppo的公鑰驗簽,因為私鑰只有oppo有,所以別人無法偽造String baseString = getBaseString(oppoOrderNotifyBo);boolean check = OppoUtils.check(baseString, oppoOrderNotifyBo.getSign());if(!check) {log.info("OppoChannelAccountStrategyImpl-驗簽失敗,此時訂單號為{}", oppoOrderNotifyBo.getPartnerOrder());return;}//代表成功了,對數據進行填充notifyOrderResultBO.setSuccess(true);notifyOrderResultBO.setTradeNo(oppoOrderNotifyBo.getNotifyId()); //可能沒有}// 生成 baseStringprivate static String getBaseString(OppoOrderNotifyBo ne) {StringBuilder sb = new StringBuilder();sb.append("notifyId=").append(ne.getNotifyId());sb.append("&partnerOrder=").append(ne.getPartnerOrder());sb.append("&productName=").append(ne.getProductName());sb.append("&productDesc=").append(ne.getProductDesc());sb.append("&price=").append(ne.getPrice());sb.append("&count=").append(ne.getCount());sb.append("&attach=").append(ne.getAttach());return sb.toString();}@Overrideprotected OppoDeliveryResult doDeliveryCallback(OrderInfo orderInfo, GameApp gameApp) throws Exception {OppoDeliveryResult oppoDeliveryCallbackResult = OppoUtils.postDeliveryOppo(orderInfo, gameApp);DeliveryCallBackResultBo deliveryCallBackResultBo = new DeliveryCallBackResultBo();deliveryCallBackResultBo.setHttpContent(JsonUtils.Object2Json(oppoDeliveryCallbackResult));deliveryCallBackResultBo.setSuccess(oppoDeliveryCallbackResult.isSuccess());return deliveryCallBackResultBo;}
}
????????看起來是不是簡單多了,當然第一個意義是不大,主要是后面的vivo、小米、華為等只需要提供對應的實現類即可
? ? ? ? 而且其他的可能都不需要doDeliveryCallback這個接口的實現,因此其實還可以改進一下,在底級類上面直接提供個成功的回調實現,這里我就暫時不改了,可能改為在底層提供個propertect方法,然后直接調用也是可以的,就當保存一下所有的交互數據得了,而且可能有其他用途,就是用來主動查詢訂單的結果? ? ? ?
? ? ? ? 至于引用就更簡單了,通常都是有個類似于算門面的東西,如下
ChannelStrategyComponent
@Slf4j
@Component
public class ChannelStrategyComponent {@Resourceprivate List<AbstractChannelStrategy> channelStrategyList;@Resourceprivate ZXCUserParentDao userParentDao;@Resourceprivate ZXCOrderDao orderInfoDao;public AbstractChannelStrategy getChannelAccountStrategy(UserTypeEnum userTypeEnum) {AbstractChannelStrategy channelAccountStrategy = checkChannelAccountStrategy(userTypeEnum);if(channelAccountStrategy == null) {throw new AppException(ErrorCode.SYS_ERROR.code(), "找不到關聯的AbstractChannelAccountStrategy對象");}return channelAccountStrategy;}public AbstractChannelStrategy checkChannelAccountStrategyByOrderNumber(String orderNumber) {Order order = orderDao.getByOrderNumber(orderNumber);//用支付方式直接去找for (AbstractChannelStrategy channelStrategy : channelStrategyList) {if(Objects.equals(orderInfo.getPayWay(), channelStrategy.getOrderPayWay().getCode())) {log.info("channelStrategy-從訂單支付方式中找到處理器");return channelStrategy;}}//支付方式找不到再從用戶注冊類型去找,節省一部數據庫查詢if(orderInfo != null) {return checkChannelAccountStrategy(orderInfo.getUserName());}return null;}
}
? ? ? ? ? ?怎么樣,看起來是不是很簡單,順帶一提,上面的OppoUtils就是跟oppo對接的工具包,這個就不提供了,這部分肯定每個都不一樣,需要單獨寫
? ? ? ? ?這篇文章主要是想說明一種封裝思路,而不是要說代碼具體是怎么寫的這個事
總結
? ? ? ? 其實這個東西并不算很復雜,可能跟我設計多次也有關系,這種思路其實我是多少有點借助spring的設計,你去看就會發現里面有很多類似這樣的設計
后續補充
補充一
? ? ? ? 就像之前說的doDeliveryCallback方法并不是每個渠道都需要的,所以并不需要弄為抽血方法,可以提供默認實現,子類根據需要實現即可,以上是改動的代碼
改之前的結構protected abstract CallBackResultBo doDeliveryCallback() throws Exception每個子類都得強制實現改之后的結構protected CallBackResultBo doDeliveryCallback() throws Exception {return CallBackResultBo.buildDefaultSuccess();
}默認提供成功的實現這樣一來,子類就可以根據所需來選擇是否需要覆蓋了,減少了不少代碼
? ?補充二?
? ? ? ? 之前的登錄接口是設計為多個來給安卓調用的,比如以上兩個接口
oppo調用: https://zxc.com/oppo/login
vivo調用: https://zxc.com/vivo/login
但是安卓說不好區分,他想統一調一個接口,如果是以外就麻煩了,但是在設計模式的加持下,現在實現的功能就非常簡單了,只需要做幾個事
1.在抽象類?AbstractChannelStrategy添加 方法
2.在子類提供實現
3.在ChannelStrategyComponent提供獲取方式
最后在接收的通用參數定義 channelSource來源,然后子類跟它綁定起來就可以,代碼如下
抽象類添加//sdk端定義的渠道來源public abstract String getSdkChannelSource();子類實現@Overridepublic String getSdkChannelSource() {return "oppo";}上下文中添加獲取即可,省略了這里