<?php

namespace app\extra\weMini;

use app\extra\tools\CodeExtend;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use WeChat\Contracts\DataArray;
use WeChat\Contracts\Tools;
use WeChat\Exceptions\InvalidArgumentException;

class PayExtra
{


    /**
     * 商户配置
     */
    protected $config = [];


    public function setConfig(array $options)
    {
        $options['nonce_str'] = CodeExtend::createNoncestr();
        $this->config = $options;
        return $this;
    }

    public function createOrder(array $options): array
    {
        $options = array_merge($this->config,$options);
        $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
        $options['sign_type'] = "MD5";
        $options['sign'] = $this->getPaySign($options);
        $client = new Client();
        try {
            $resp = $client->post($url, [
                "header" => $client,
                'body' => CodeExtend::arr2xml($options)
            ]);
        } catch (GuzzleException $e) {
            return [];
        }
        return CodeExtend::xml2arr($resp->getBody());
    }

    /**
     * 创建JsApi及H5支付参数
     * @param string $prepayId 统一下单预支付码
     * @return array
     */
    public function createParamsForJsApi($prepayId)
    {
        $option = [];
        $option["appId"] = $this->config['appid'];
        $option["timeStamp"] = (string)time();
        $option["nonceStr"] = CodeExtend::createNoncestr();
        $option["package"] = "prepay_id={$prepayId}";
        $option["signType"] = "MD5";
        $option["paySign"] = $this->getPaySign($option, 'MD5');
        $option['timestamp'] = $option['timeStamp'];
        return $option;
    }

    /**
     * 生成支付签名
     * @param array $data 参与签名的数据
     * @param string $signType 参与签名的类型
     * @param string $buff 参与签名字符串前缀
     * @return string
     */
    public function getPaySign(array $data, $signType = 'MD5', $buff = '')
    {
        ksort($data);
        if (isset($data['sign'])) unset($data['sign']);
        foreach ($data as $k => $v) {
            if ('' === $v || null === $v) continue;
            $buff .= "{$k}={$v}&";
        }
        $buff .= ("key=" . $this->config['mch_key']);
        if (strtoupper($signType) === 'MD5') {
            return strtoupper(md5($buff));
        }
        return strtoupper(hash_hmac('SHA256', $buff, $this->config['mch_key']));
    }


}