<?php

namespace app\common\server;

use EasyWeChat\Factory;

/**
 * @notes 小程序 发货信息录入
 * @notes https://developers.weixin.qq.com/miniprogram/dev/platform-capabilities/business-capabilities/order-shipping/order-shipping.html
 * author lbzy
 * @datetime 2023-07-14 14:51:23
 * @class WechatMiniExpressSendSyncService
 * @package app\common\service
 */
class WechatMiniExpressSendSyncServer
{
    static private $miniApp;
    
    private static function getMiniApp()
    {
        static::$miniApp = static::$miniApp ? : Factory::miniProgram(WeChatServer::getMnpConfig());
        
        return static::$miniApp;
    }
    

    
    private static function getToken($app)
    {
        return $app->access_token->getToken()['access_token'];
    }
    
    static function wechatSyncCheck($order)
    {
        $app    = static::getMiniApp();
    
        $data = [
            'transaction_id' => $order['pay_transaction_id'] ?? '',
        ];
    
        $token = static::getToken($app);
    
        $result_content = $app->http_client->post("/wxa/sec/order/get_order?access_token={$token}", [
            'body'   => json_encode($data, JSON_UNESCAPED_UNICODE),
        ])->getBody()->getContents();
    
        $result = json_decode($result_content, true);
    
        if (! isset($result['errcode']) || $result['errcode'] != 0) {
            // token失效 不标记失败 等下次执行
            if (isset($result['errcode']) && $result['errcode'] == 40001) {
//                Log::write("等待下次执行" . ($result_content ? : "发货录入发生错误"), 'wechat_mini_express_sync_check');
                return false;
            }
//            Log::write($result_content ? : "发货录入发生错误", 'wechat_mini_express_sync_check');
            return [];
        }
        
        return $result;
        
    }
}