laravel使用EasyWeChat 使用

Laravel框架
851
0
0
2022-04-19

laravel安装laravel-wechat 实现微信授权登录

一.下载laravel-wechat

https://packagist.org/packages/overtrue/laravel-wechat

二. 使用composer安装laravel-wechat

composer require "overtrue/laravel-wechat:~4.0"

三.配置

在 config/app.php 注册 ServiceProvider 和 Facade (Laravel 5.5 + 无需手动注册)

'providers' => [
    // ...
    Overtrue\LaravelWeChat\ServiceProvider::class,
],
'aliases' => [ 
    // ... 
    'EasyWeChat' => Overtrue\LaravelWeChat\Facade::class,
],

创建配置文件:

php artisan vendor:publish --provider="Overtrue\LaravelWeChat\ServiceProvider

1.修改应用根目录下的 config/wechat.php 中对应的参数即可。

WECHAT_LOG_LEVEL=info  //日志级别 最好和laravel同级
WECHAT_LOG_FILE=/var/log/coupon/report.log  //日志保存文件 最好和laravel 统一
WECHAT_OFFICIAL_ACCOUNT_APPID=申请的appid
WECHAT_OFFICIAL_ACCOUNT_SECRET=申请的appsecret
WECHAT_OFFICIAL_ACCOUNT_TOKEN=
WECHAT_OFFICIAL_ACCOUNT_AES_KEY=

easyWeChat 微信公众号验证 token

<?php

namespace Modules\Easywechat\Http\Controllers;

use EasyWeChat\Factory;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

class EasywechatController extends Controller
{
     /**
     * 公众号token验证
     *
     * @return string
     */ 
    public function serve()
    {
        $app = app('wechat.official_account');
        $app->server->push(function ($message) {
            return "欢迎关注 overtrue!";
        });
        return $app->server->serve();
    }

 /** 公众号模板消息发送

* @param $data

* @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException

* @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException

* @throws \GuzzleHttp\Exception\GuzzleException

     */

 public  function  confirm_receipt($data)
    {
         $config =  config('wechat.official_account.default');
         $app =  Factory::officialAccount($config);
         $app->template_message->send([
         'touser'  => $data['openid'], //用户openid

         'template_id'  =>  env('CONFIRM_RECEIPT', '45445'), //发送的模板id

         'data'  => [
             'first'  =>  '您已确认收货,请知晓!',
             'keyword1'  => $data['order_no'],
             'keyword4'  => $data['name'],
        ],

        ]);

    }
    //公众号授权 
    public  function  officialAccounts()

    {

        $app =  app('wechat.official_account');

        $oauth = $app->oauth;

         // 指定回调 URL,比如设置回调 URL 为当前页面

         // $redirectUrl = $oauth->scopes(['snsapi_userinfo'])->redirect();

        $redirectUrl = $oauth->scopes(['snsapi_userinfo'])->redirect();

         return \redirect($redirectUrl);

         // return $this->success(compact('redirectUrl'));

    }
    //公众号授权回调 
     public  function  officialAccountToNotify(Request $request)

    {

        $code = $request->code ? $request->code :  null;

         if (empty($code)) {

         return  $this->fail('请重新授权登录');

        }

        $app =  app('wechat.official_account');

        $oauth = $app->oauth;

         // 获取 OAuth 授权用户信息

        $userinfo = $oauth->userFromCode($code);

        $user =  User::where('openid', $userinfo["openid"]);

        $data = $userinfo['raw'];

         if ($user->doesntExist()) {

            $data['avatar'] = $data['headimgurl'];

            $data['name'] = $data['nickname'];

            $data['password'] =  Hash::make('8888888');

            $data['enable_status'] =  0;

            unset($data['headimgurl']);

            unset($data['privilege']);

            $userinfo =  User::create($data);

        } else {

        $userinfo = $user->first();

        }

    $access_token = $userinfo->createToken('user')->accessToken;

     return  $this->success(['access_token'  =>  'Bearer '  . $access_token]);

    }

 /**

     *小程序 微信授权登录

* @param  Request $request

* @return  array

     */

 public  function  wxappLogin(Request $request)

    {

        $app =  app('wechat.mini_program');

        $data = $app->auth->session($request->code);

         if (isset($data['errcode'])) {

         return  $this->fail('code已过期或不正确');

        }

        $userInfo = $app->encryptor->decryptData($data['session_key'], $request->iv, $request->encryptedData);

        $user =  User::where('openid', $data["openid"]);

             if ($user->doesntExist()) {

                $userInfo['openid'] = $data["openid"];

                $userInfo['avatar'] = $userInfo['avatarUrl'];

                $userInfo['nickname'] = $userInfo['nickName'];

                $userInfo['name'] = $userInfo['nickName'];

                $userInfo['password'] =  Hash::make('8888888');

                $userInfo['enable_status'] =  0;

                unset($userInfo['nickName']);

                unset($userInfo['avatarUrl']);

                unset($userInfo['watermark']);

                // return $this->success($userInfo);

                $userinfo =  User::create($userInfo);

            } else {

            $userinfo = $user->first();

        }

    $access_token = $userinfo->createToken('user')->accessToken;

     return  $this->success(['access_token'  =>  'Bearer '  . $access_token]);

     // return $this->success(['c' => $this->wxapp_config, 'b' => $app, 'f' => $data, 'userInfo' => ]);

    }
}

laravel使用EasyWeChat 统一下单

use EasyWeChat\Factory;
private $app;
public function __construct()
{

  $config = config('wechat.payment.default');
  $this->app = Factory::payment($config);
}
public function payment(PayRequest $request){
  $isContract = true;
  $result = $this->app->order->unify([
  'body' => '用户下单',
  'out_trade_no' => $order_no,
  'total_fee' => 10,
//           'spbill_create_ip' => '123.12.12.123', // 可选,如不传该参数,SDK 将会自动获取相应 IP 地址
  'notify_url' =>  config('wechat.payment.default.notify_url'), // 支付结果通知网址,如果不设置则会使用配置里的默认地址
  'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
  'openid' => Auth::user()->openid,
  ], $isContract);
  //注意 
  1、如果支付时出现报错,timestame 参数问题。这是 easywechat 底层文件出错了。

  if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
      $config['timeStamp'] = $config['timestamp'];
     unset($config['timestamp']);
     return $this->success( $config);
}else{
      return $this->fail('支付失败');
}
2、如果签名失败
if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
      $prepayId = $result['prepay_id'];
      $jssdk =$this->app->jssdk;
      $config = $jssdk->sdkConfig($prepayId);
      $config['timeStamp'] = $config['timestamp'];
     unset($config['timestamp']);
     return $this->success( $config);
}else{
      return $this->fail('支付失败');
}

}

申请退款

退款方式 分为两种

第一种:根据微信订单号退款

// 参数分别为:微信订单号、商户退款单号、订单金额、退款金额、其他参数
$app->refund->byTransactionId(string $transactionId, string $refundNumber, int $totalFee, int $refundFee, array $config = []);

// Example:
$result = $app->refund->byTransactionId('transaction-id-xxx', 'refund-no-xxx', 10000, 10000, [
    // 可在此处传入其他参数,详细参数见微信支付文档
    'refund_desc' => '商品已售完',
]);

使用

laravel使用EasyWeChat 使用

第二种:根据商户订单号退款

// 参数分别为:商户订单号、商户退款单号、订单金额、退款金额、其他参数
$app->refund->byOutTradeNumber(string $number, string $refundNumber, int $totalFee, int $refundFee, array $config = []);

// Example:
$result = $app->refund->byOutTradeNumber('out-trade-no-xxx', 'refund-no-xxx', 20000, 1000, [
    // 可在此处传入其他参数,详细参数见微信支付文档
    'refund_desc' => '退运费',
]);

laravel使用EasyWeChat 使用