hyperf 接入 EasyWechat 多商戶配置 (公眾號,小程式)

Komorebi_PHP發表於2020-04-19

hyperf接入EasyWechat

安裝 EasyWechat元件

1. composer require overtrue/easywechat
2.APP\Factory目錄新建立一個WechatFactory.php(見配置)
3. 在config/autoload裡新加一個wechat.php(見配置)

配置

###wechat.php 以小程式為例

多小程式配置把各自的小程式賬號分別存入進去

WechatFactory.php 程式碼貼圖有點長直接貼程式碼吧

<?php

declare(strict_types = 1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://doc.hyperf.io
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf-cloud/hyperf/blob/master/LICENSE
 */

namespace App\Factory;

use App\Exception\InputException;
use App\Exception\InvalidArgumentException;
use EasyWeChat\Factory;
use EasyWeChat\MiniProgram\Application;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use Hyperf\Contract\ConfigInterface;
use Hyperf\Guzzle\CoroutineHandler;
use Hyperf\Guzzle\HandlerStackFactory;
use Hyperf\HttpServer\Contract\RequestInterface;
use Overtrue\Socialite\Providers\AbstractProvider;
use Psr\Container\ContainerInterface;
use Psr\SimpleCache\CacheInterface;

/**
 * Class WechatFactory
 * @package App\Factory
 * @property \EasyWeChat\MiniProgram\Auth\AccessToken           $access_token
 * @property \EasyWeChat\MiniProgram\DataCube\Client            $data_cube
 * @property \EasyWeChat\MiniProgram\AppCode\Client             $app_code
 * @property \EasyWeChat\MiniProgram\Auth\Client                $auth
 * @property \EasyWeChat\OfficialAccount\Server\Guard           $server
 * @property \EasyWeChat\MiniProgram\Encryptor                  $encryptor
 * @property \EasyWeChat\MiniProgram\TemplateMessage\Client     $template_message
 * @property \EasyWeChat\OfficialAccount\CustomerService\Client $customer_service
 * @property \EasyWeChat\MiniProgram\Plugin\Client              $plugin
 * @property \EasyWeChat\MiniProgram\Plugin\DevClient           $plugin_dev
 * @property \EasyWeChat\MiniProgram\UniformMessage\Client      $uniform_message
 * @property \EasyWeChat\MiniProgram\ActivityMessage\Client     $activity_message
 * @property \EasyWeChat\MiniProgram\Express\Client             $logistics
 * @property \EasyWeChat\MiniProgram\NearbyPoi\Client           $nearby_poi
 * @property \EasyWeChat\MiniProgram\OCR\Client                 $ocr
 * @property \EasyWeChat\MiniProgram\Soter\Client               $soter
 * @property \EasyWeChat\BasicService\Media\Client              $media
 * @property \EasyWeChat\BasicService\ContentSecurity\Client    $content_security
 * @property \EasyWeChat\MiniProgram\Mall\ForwardsMall          $mall
 * @property \EasyWeChat\MiniProgram\SubscribeMessage\Client    $subscribe_message
 * @property \EasyWeChat\MiniProgram\RealtimeLog\Client         $realtime_log
 * @property \EasyWeChat\MiniProgram\Search\Client              $search
 * @property \EasyWeChat\MiniProgram\Live\Client                $live
 */
class WechatFactory
{
    private $container;
    /**
     * @var Application
     */
    private $app;

    /**
     * @param \Psr\Container\ContainerInterface $container
     */
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
        AbstractProvider::setGuzzleOptions([
            'http_errors' => false,
            'handler'     => HandlerStack::create(new CoroutineHandler()),
        ]);
    }

    /**
     * 註冊小程式APP
     */
    private function register()
    {
        //此引數主要是區別不同配置的小程式
        $channel = $this->container->get(RequestInterface::class)->input('channel','xxx');
        $key     = 'wechat.mini_program' . ".{$channel}";
        $config  = $this->container->get(ConfigInterface::class)->get($key);
        //自定義錯誤
        if (empty($config)) {
            throw new InputException('通道來源錯誤,暫無該配置!', 400);
        }
        $app = Factory::miniProgram($config);

        $config            = $app['config']->get('http', []);
        $config['handler'] = $this->container->get(HandlerStackFactory::class)->create();
        $app->rebind('http_client', new Client($config));
        $cache = $this->container->get(CacheInterface::class);
        $app->rebind('cache', $cache);
        $app['guzzle_handler'] = $this->container->get(HandlerStackFactory::class)->create();
        $this->app             = $app;
    }

   /**
     * @param $id
     *
     * @return mixed
     */
    public function __get($id)
    {
        $this->register();
        if ($this->app->shouldDelegate($id)) {
            return $this->app->delegateTo($id);
        }
        return $this->app->offsetGet($id);
    }
}

如何呼叫

<?php
declare(strict_types = 1);

namespace App\Controller;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;

/**
 * Class TestController
 * @Controller(prefix="wechat")
 */
class WechatController extends AbstractController
{
    /**
     * @\Hyperf\Di\Annotation\Inject()
     * @var \App\Factory\WechatFactory
     */
    protected $wechatFactory;
    /**
     * @RequestMapping(path="session", methods="get,post")
     */
    public function session()
    {
        $code    = $this->request->input('code');
        $session = $this->wechatFactory->auth->session($code);
        dump($session);
    }
}

效果

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章