<?php
/**
 * Created by PhpStorm.
 * User: phperstar
 * Date: 2020/6/22
 * Time: 2:30 PM
 */
namespace Util\ByteDance;

use Mall\Framework\Core\ResultWrapper;
use Mall\Framework\Core\ErrorCode;

class Pay
{
    /**
     *  开发者后台支付设置页的appId
     * @var string $appid
     */
    private $appid;

    /**
     * 开发者后台支付设置页的商户号
     * @var string $merchant_id
     */
    private $merchant_id;

    /**
     * 开发者后台支付设置页的支付secret
     * @var string $app_secret
     */
    private $app_secret;


    public function __construct($appid, $merchant_id, $app_secret)
    {
        $this->appid = $appid;
        $this->merchant_id = $merchant_id;
        $this->app_secret = $app_secret;
    }

    /**
     * 官方文档地址:https://microapp.bytedance.com/dev/cn/mini-app/develop/api/open-interface/payment/tt.pay
     * @param $orderNo
     */
    public function pay($orderNo, $total_fee, $shopName, $ip, $wx_url)
    {
        $orderInfo = [
            'app_id' => $this->appid,
            'sign_type' => 'MD5',
            'out_order_no' => $orderNo,
            'merchant_id'  => $this->merchant_id,  // 开发者后台支付设置页的商户号
            'timestamp'    => (string)time(),
            'product_code' => 'pay',
            'payment_type' => 'direct',
            'total_amount' => yuanToFen($total_fee), // 金额
            'trade_type'   => 'H5',
            'uid'          => $this->appid,
            'version'      => '2.0',
            'currency'     => 'CNY',
            'subject'      => $shopName.'-'.'线上商城', // 商户订单名称
            'body'         => $shopName.'-'.'线上商城', // 商户订单详情
            'trade_time'   => (string)time(),
            'valid_time'   => (string)3600, // 订单有效时间
            'notify_url'   => 'https://tp-pay.snssdk.com/paycallback',
            'wx_url'       => $wx_url,
            'risk_info'    => json_encode(['ip'=>$ip]),
        ];

        if(!empty($orderInfo['wx_url'])){
            $orderInfo['wx_type'] = 'MWEB';
        }

        $orderInfo['sign'] = self::getSign($orderInfo);

        return ResultWrapper::success($orderInfo);

    }

    /**
     * 生成签名方法
     * 官方接口地址: https://microapp.bytedance.com/dev/cn/mini-app/develop/api/open-interface/payment/mini-app-pay-plugin-reference/server-sign
     * 官方签名测试地址: https://pay-doc.toutiao.com/tools/sign
     * @param $parm
     * @return string
     */
    public function getSign($parm)
    {
        // 剔除risk_info
        unset($parm['risk_info']);

        //非空参数值的参数按照参数名ASCII码从小到大排序（字典序）
        if(ksort($parm)){
            $stringA = '';

            //使用URL键值对的格式拼接成字符串stringA
            $i = 1;
            foreach($parm as $key => $value){
                if($value === 0 || !empty($value)){
                    $stringA .=$key.'='.$value;
                    if($i != count($parm)){
                        $stringA .= '&';
                    }
                }

                $i++;
            }
        }else{
            return ResultWrapper::fail('对参数排序出错', ErrorCode::$paramError);
        }


        //在stringA最后拼接上key=商户支付密钥
        $stringSignTemp = $stringA.$this->app_secret;

        $signValue = md5($stringSignTemp);
        return $signValue;
    }
}