站三界导航
首页 TP代码一个基本的微信支付的TP5.0方法代码

一个基本的微信支付的TP5.0方法代码

  • TP代码
  • 来源:站三界导航
  • 40阅读
  • 2023-05-20

<?php
namespace app\index\controller;

use think\Controller;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order;
use EasyWeChat\Payment\Payment;

class Pay extends Controller {
    private $app;
    private $payment;

    public function _initialize() {
        $config = config('wechat');
        $this->app = new Application($config);
        $this->payment = $this->app->payment;
    }

    /*
     * 发起微信支付
     */
    public function wxpay() {
        $openid = session('openid');
        $order = new Order([
            'body' => '商品描述',
            'out_trade_no' => '商户订单号',
            'total_fee' => 1, // 单位:分
            'trade_type' => 'JSAPI',
            'openid' => $openid,
            'notify_url' => 'http://example.com/notify', // 支付结果通知网址,如果不设置则会使用配置里的默认地址
        ]);
        $result = $this->payment->prepare($order);
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS') {
            $prepayId = $result->prepay_id;
            $jssdk = $this->app->jssdk;
            $config = $jssdk->sdkConfig($prepayId);
            $this->assign('config', $config);
            return $this->fetch();
        } else {
            $this->error('支付失败');
        }
    }

    /*
     * 微信支付异步通知
     */
    public function notify() {
        $payment = $this->payment;
        $response = $payment->handleNotify(function($notify, $successful) {
            $outTradeNo = $notify->out_trade_no;
            if ($successful) {
                // 支付成功
                
            } else {
                // 支付失败
                
            }
            return true;
        });
        return $response;
    }
}
以上代码使用EasyWeChat封装的微信支付SDK,具体实现需要在config目录下创建wechat.php配置文件并在其中配置微信支付相关参数。同时需要注意,以上代码仅为一个示例,具体实现需要根据实际业务需求进行调整和完善。 本文结束
本文来自投稿,不代表站三界导航立场,如若转载,请注明出处:https://www.zhansanjie.com/article/details/43437.html

版权声明:

1、本文系转载,版权归原作者所有,旨在传递信息,不代表看本站的观点和立场。

2、本站仅提供信息发布平台,不承担相关法律责任。

3、若侵犯您的版权或隐私,请联系本站管理员删除。

4、本文由会员转载自互联网,如果您是文章原创作者,请联系本站注明您的版权信息。

分享
站三界导航
本站声明:本站严格遵守国家相关法律规定,非正规网站一概不予收录。本站所有资料取之于互联网,任何公司或个人参考使用本资料请自辨真伪、后果自负,站三界导航不承担任何责任。在此特别感谢您对站三界导航的支持与厚爱。