<?php

namespace App\Libs\Pay\Merchants;

use GuzzleHttp\Client;
use Log;
use Mockery\Exception;

/**
 *
 */
class Palmpay {

    function __construct($config)
    {
        $this->appId = $config['appId'];
        $this->mchId = $config['mchId'];
        $this->appkey = $config['appKey'];
        $this->subAppid = $config['subAppid'];
        $this->PayClient = new client(['base_uri'=>'https://pay.palmpay.cn/','timeout'=>5]);
    }

    //生成订单
    function send($data)
    {
        $data = [
            'mchId'=>$this->mchId,
            'appid'=>$this->appId,
            'version'=>'3.0',
            'productName'=>$data['body'],
            'productDesc'=>'小说充值',
            'openid'=>$data['openid'],
            'subAppid'=>$this->subAppid,
            'money'=>$data['price'],
            'outTradeNo'=>$data['trade_no'],
            'notifyUrl'=>env('PALMPAY_NOFITY_URL'),
        ];
        $data['sign'] = $this->sign($data);
        $pay_url = "sdkServer/thirdpays/pay/WECHAT_SUB?".http_build_query($data);

        $response = $this->PayClient->request('GET',$pay_url)->getBody()->getContents();
        return $this->getPayInfo($response);
    }

    function sign($params)
    {
        return md5($params['appid'].'WECHAT_SUB'.$params['money'].$params['outTradeNo'].$this->appkey);
    }

    function getPayInfo($response)
    {
        try{
            $return_info = json_decode($response,1);
            //dd($return_info);
            if($return_info['errcode'] == 0)
            {
                return json_decode($return_info['result']['pay_info'],1);
            }
        }catch (\Exception $e)
        {
            return null;
        }

    }



}