使用 yansongda/pay 进行支付宝和微信支付

简介

现在很多项目都会用到微信或支付宝支付,然而官方文档以及混乱的签名会让很多人一脸懵逼, github 有很多第三方的包,已经封装好了支付,这里以 yansongda/pay 这个包为例。

  1. 安装
    composer require yansongda/pay -vvv
  1. 配置文件config/pay.php, 然后在.env 文件中填写对应配置。
<?php
return [
 'alipay' => [
     // 支付宝分配的 APPID
     'app_id' => env('ALI_APP_ID', ''),

     // 支付宝异步通知地址
     'notify_url' => '',

     // 支付成功后同步通知地址
     'return_url' => '',

     // 阿里公共密钥,验证签名时使用
     'ali_public_key' => env('ALI_PUBLIC_KEY', ''),

     // 自己的私钥,签名时使用
     'private_key' => env('ALI_PRIVATE_KEY', ''),

     // optional,默认 warning;日志路径为:sys_get_temp_dir().'/logs/yansongda.pay.log'
     'log' => [
         'file' => storage_path('logs/alipay.log'),
     //  'level' => 'debug'
     //  'type' => 'single', // optional, 可选 daily.
     //  'max_file' => 30,
     ],

     // optional,设置此参数,将进入沙箱模式
     // 'mode' => 'dev',
 ],

 'wechat' => [
     // 公众号 APPID
     'app_id' => env('WECHAT_APP_ID', ''),

     // 小程序 APPID
     'miniapp_id' => env('WECHAT_MINIAPP_ID', ''),

     // APP 引用的 appid
     'appid' => env('WECHAT_APPID', ''),

     // 微信支付分配的微信商户号
     'mch_id' => env('WECHAT_MCH_ID', ''),

     // 微信支付异步通知地址
     'notify_url' => '',

     // 微信支付签名秘钥
     'key' => env('WECHAT_KEY', ''),

     // 客户端证书路径,退款、红包等需要用到。请填写绝对路径,linux 请确保权限问题。pem 格式。
     'cert_client' => base_path('storage/app/cert/apiclient_cert.pem'),

     // 客户端秘钥路径,退款、红包等需要用到。请填写绝对路径,linux 请确保权限问题。pem 格式。
     'cert_key' =>  base_path('storage/app/cert/apiclient_key.pem'),

     // optional,默认 warning;日志路径为:sys_get_temp_dir().'/logs/yansongda.pay.log'
     'log' => [
         'file' => storage_path('logs/wechat.log'),
     //  'level' => 'debug'
     //  'type' => 'single', // optional, 可选 daily.
     //  'max_file' => 30,
     ],

     // optional
     // 'dev' 时为沙箱模式
     // 'hk' 时为东南亚节点
     // 'mode' => 'dev',
 ],
];
  1. 获取客户端用以调起支付的参数或二维码
  • 微信
/**
 * @param Request $request
 * @return IlluminateHttpJsonResponse
 * @throws IlluminateValidationValidationException
 * @des 微信下单获取支付参数
 */
public function wechatPay(Request $request)
{
    $this->validate(
        $request,
        [
            'order_id' => 'required|digits_between:1,9|integer',
        ]
    );
    $order_id = $request->get('order_id');
    $order = Order::find($order_id);
    if (!$order || $order->status != 0) {
        return returnApi(500,'订单状态异常');
    }
    //以上为获取订单信息 根据自己业务调整
    $data = [
        'out_trade_no' => $order->order_number,//订单号
        'body'          => $order->goods_name,//商品名称
        'total_fee'      => $order->total * 100//金额单位分
    ];
    $config = config('pay.wechat');获取配置参数
    $config['notify_url'] = env('APP_URL').'/notify';//加入回调url
    $result = Pay::wechat($config)->app($data);//统一下单
    $json = $result->getContent();
    $res = json_decode($json);
    return returnApi(200,'SUCCESS', $res);//返回支付参数
    /* 返回数据示例
    {
        "code":200,
        "msg":"SUCCESS",
        "data":{
            "appid":"wx1076a********",
            "partnerid":"1571*****",
            "prepayid":"wx091513315******",
            "timestamp":"15785*****",
            "noncestr":"pfCEOn*****",
            "package":"Sign=WXPay",
            "sign":"DCE5402CEA0****"
        }
    }
    */
}
  • 支付宝
    /**
     * @param Request $request
     * @return IlluminateHttpJsonResponse
     * @throws IlluminateValidationValidationException
     * @des 支付宝支付
     */
    public function aliPay(Request $request)
    {
        $this->validate(
            $request,
            [
                'order_id' =>  'required|digits_between:1,9|integer',
            ]
        );
        $order_id = $request->get('order_id');
        $order = Order::find($order_id);
        if (!$order || $order->status != 0) {
            return returnApi(500,'订单状态异常');
        }
        //以上为获取订单信息 根据自己业务调整
        $order = [
            'out_trade_no' => $order->order_number,//订单号
            'total_amount' => $order->total,//金额 单位元
            'subject'      => $order->name,//商品名称
        ];
        $config = config('pay.alipay');
        $config['notify_url'] = env('APP_URL').'/v1/notify';//加入回调url
        $alipay = Pay::alipay($config);
        $res = $alipay->app($order)->getContent();
        return returnApi(200,'SUCCESS',['orderInfo' => $res]);
            /* 返回数据示例
            {
                "code":200,
                "msg":"SUCCESS",
                "data":{
                    "orderInfo":"app_id=2021001*******&format=JSON&charset=utf-8&sign_type=RSA2&version=1.0&notify_url=https%3A%2F%2Fqiangyibo.enumen.com%2Fv1%2Flevel%2Falipay%2Fnotify&timestamp=2020-04-06+10%3A44%3A50&biz_content=%7B%22out_trade_no%22%3A%222020010914545331453%22%2C%22total_amount%22%3A%2259.70%22%2C%22subject%22%3Anull%2C%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%7D&method=alipay.trade.app.pay&sign=cX6uehDLpo8Lw8eat5X0XaoH09hbkZnb%2BNs4hfOokSXd2rhQBUuC45x6b%2FtfjDlNuFgukpPGzF1SlqP%2FFadiOBMYfir%2FZv3D3fEq8ec%2BHhsVk7lrUytyGhLyYgAEVjEA1uJyQAUKfTqDs9FeWgnpi3IiHk8hO4J8zwPjV2YG0RvZnJrEXTgavz6E2gMNkU%2BtaqhICCtVxyq1nbc%2BnYM4k8jT57dEEKC1fn7x1LTU60YPBxun7oKMsn%2BZNYPBycq4KGh9QKh9N7mRreFqT38PwiWFx4zOCwwMUM%2B%2BxxiqaJEg%2BcquTYptF1oxujwHvFB9O25dkxUeUvFUKhFD5MevZQ%3D%3D"
                }
            }
        */
    }
}
  1. 回调
  • 微信
public function wechatNotify(Request $request)
  {
      $config = config('pay.wechat');
      $pay = Pay::wechat($config);//实例化支付对象
      try{
          $data = $pay->verify(); // 是的,验签就这么简单!
          //以下根据自己业务进行支付校验
          $order = Order::where('order_no', $data->out_trade_no)->first();
          if (!$order || $order->state != 0)  {
              //如果订单状态异常直接退出
              return $pay->success();
          }
          if (($order->total) != $data->total_fee / 100) {
              //如果金额不匹配直接退出
              return $pay->success();
          }
          //进行订单状态变更等支付成功操作
          //....
          return $pay->success();
      } catch (Exception $e) {
      }
  }
  • 支付宝
public function aliPayNotify(Request $request)
  {
      $config = config('pay.alipay');
      $alipay = Pay::alipay($config);
      try{
          $data = $alipay->verify(); // 是的,验签就这么简单!
          //以下根据自己业务进行支付校验
          $order = Order::where('order_no', $data->out_trade_no)->first();
          if (!$order || $order->state != 0)  {
              //如果订单状态异常直接退出
              return $alipay->success();
          }
          if (($order->total) != $data->total_amount) {
              return $alipay->success();
          }
          //进行订单状态变更等支付成功操作
          //....
          return $alipay->success();
          Log::debug('Alipay notify', $data->all());
      } catch (Exception $e) {
//             $e->getMessage();
      }
      return $alipay->success();// laravel 框架中请直接 `return $alipay->success()`
  }

—— 原文作者:woann 转自链接:https://learnku.com/articles/41249 版权声明:著作权归作者所有。商业转载请联系作者获得授权,非商业转载请保留以上作者信息和原文链接。

zhaohao

大家好,欢迎来到赵豪博客!赵豪,94年生人,PHP程序员一枚,因为对PHP开发有着相对比较浓厚的兴趣,所以现在从事着PHP程序员的工作。 今天再次开通这个博客,这里将记录我的职业生涯的点点滴滴,感谢来访与关注!如果我的博客能给您带来一些帮助那真是一件非常荣幸的事情~

相关推荐

1 条评论

  1. Hygge

    不错不错 ,找的就是你

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

微信扫一扫

微信扫一扫

微信扫一扫,分享到朋友圈

使用 yansongda/pay 进行支付宝和微信支付
返回顶部

显示

忘记密码?

显示

显示

获取验证码

Close