Wechat.php 2.9 KB
<?php

namespace app\common\controller;

use think\Controller;
use think\Request;
use EasyWeChat\Factory;

class Wechat extends Controller
{
    // 错误信息
    protected $_error = '';
    /**
     * 小程序配置
     */
    public static function miniProgram(){
        $config = [
            'app_id' => config('site.app_id'),
            'secret' => config('site.secret'),

            // 下面为可选项
            // 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',

            'log' => [
                'level' => 'debug',
                'file' => __DIR__.'/wechat.log',
            ],
        ];

        return Factory::miniProgram($config);
    }

    /**
     * 微信支付配置
     */
    public static function payment(){
        $http = self::isHttps() ? 'https://' : 'http://';
        $config = [
            'app_id'             => config('site.app_id'),
            'mch_id'             => config('site.mch_id'),
            'key'                => config('site.key'),
            'notify_url'         => $http . $_SERVER['HTTP_HOST'] . url('cart/notify'),
        ];
        return Factory::payment($config);
    }

    /**
     * 微信支付
     */
    public function wxPay($order_no,$openid,$order_price)
    {
        $payment = self::payment();
        $result = $payment->order->unify([
            'body' => $order_no,
            'out_trade_no' => $order_no,
            'total_fee' => $order_price * 100,
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $openid,
        ]);

        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            return $payment->jssdk->bridgeConfig($result['prepay_id'], false); // 返回数组
        }
     
        if ($result['return_code'] == 'FAIL' && array_key_exists('return_msg', $result)) {
            $this->setError($result['return_msg']);
            return false;
        }
        $this->setError($result['err_code_des']);
        return false;
    }

    /**
     * 判断是否是https
     */
    public static function isHttps() {
        if ( !empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') {
            return true;
        } elseif ( isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ) {
            return true;
        } elseif ( !empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off') {
            return true;
        }
        return false;
    }

    /**
     * 设置错误信息
     */
    public function setError($error)
    {
        $this->_error = $error;
        return $this;
    }

    /**
     * 获取错误信息
     */
    public function getError()
    {
        return $this->_error ? __($this->_error) : '';
    }
}