<?php
/**
 * Created by PhpStorm
 * DateTime: 2022/10/28 22:50.
 *
 * @description
 */

namespace App\Helper;

use App\Helper\UniPlatform\BaseUniPlatform;
use EasyWeChat\Factory;
use EasyWeChat\MiniProgram\Application;

class Wechat extends BaseUniPlatform
{
    public function mini(): Application
    {
        return Factory::miniProgram([
            'app_id'        => $this->appId,
            'secret'        => $this->secret,
            'response_type' => 'array',
        ]);
    }

    public function payment(): \EasyWeChat\Payment\Application
    {
        return Factory::payment([
            'sandbox'    => false,
            'app_id'     => $this->appId,
            'mch_id'     => $this->mchId,
            'key'        => $this->mchKey,
            'cert_path'  => env('WECHAT_PAYMENT_CERT_PATH', 'path/to/cert/apiclient_cert.pem'),    // XXX: 绝对路径！！！！
            'key_path'   => env('WECHAT_PAYMENT_KEY_PATH', 'path/to/cert/apiclient_key.pem'),      // XXX: 绝对路径！！！！
            'notify_url' => $this->noticeUrl,
        ]);
    }

    /**
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \Exception
     */
    public function createOrder($outOrderNo, $totalAmount, $openId): array
    {
        $app     = $this->payment();
        $payment = $app->order->unify([
            'body'         => '订单号：' . $outOrderNo,
            'out_trade_no' => $outOrderNo,
            'total_fee'    => $totalAmount * 100, // 分
            'notify_url'   => $this->noticeUrl, // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type'   => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid'       => $openId,
        ]);
        if ('SUCCESS' != $payment['return_code'] || 'SUCCESS' != $payment['result_code']) {
            throw new \Exception($payment['return_msg']);
        }

        return [
            'order_id'    => $payment['prepay_id'],
            'order_token' => '',
        ];
    }

    protected function setNoticeUrl(): void
    {
        $this->noticeUrl = env('APP_URL') . '/api/pay/wechat/notify';
    }

    protected function login($code): array
    {
    }

    protected function post($uri = '', $data = []): array
    {
    }

    protected function getAccessToken(): string
    {
    }

    protected function setAccessFileDir(): void
    {
    }

    protected function setAccessFilePath(): void
    {
    }
}
