PHP code example of lilocon / wechat-bundle

1. Go to this page and download the library: Download lilocon/wechat-bundle library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

lilocon / wechat-bundle example snippets


// app/AppKernel.php

// ...
class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            // ...
            // 在这里添加一行
            new Lilocon\WechatBundle\LiloconWechatBundle(),
            // ...
        );
        // ...
    }
    // ...
}

$wechat = $this->get('wechat_sdk');

class WechatController extends Controller
{
    /**
     * 处理微信的请求消息
     *
     * @return string
     * @throws \EasyWeChat\Core\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Server\BadRequestException
     */
    public function serve()
    {
        $wechat = $this->get('wechat_sdk');
        $wechat->server->setMessageHandler(function($message){
            return "欢迎关注 overtrue!";
        });

        return $wechat->server->serve();
    }
}

    # sdk缓存配置
    cache:
      overwrite: true # false => true
      cache_id: wechat_cache # 自定义缓存service_id


// src/AppBundle/Entity/User.php
namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * User
 *
 * @ORM\Table(name="user")
 * @ORM\Entity(repositoryClass="Doctrine\ORM\EntityRepository")
 */
class User
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="openid", type="string", length=255)
     */
    private $openid;

    /**
     * @var string
     *
     * @ORM\Column(name="nickname", type="string", length=255)
     */
    private $nickname;


    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set openid
     *
     * @param string $openid
     *
     * @return User
     */
    public function setOpenid($openid)
    {
        $this->openid = $openid;

        return $this;
    }

    /**
     * Get openid
     *
     * @return string
     */
    public function getOpenid()
    {
        return $this->openid;
    }

    /**
     * Set nickname
     *
     * @param string $nickname
     *
     * @return User
     */
    public function setNickname($nickname)
    {
        $this->nickname = $nickname;

        return $this;
    }

    /**
     * Get nickname
     *
     * @return string
     */
    public function getNickname()
    {
        return $this->nickname;
    }

    public function __toString()
    {
        return $this->nickname;
    }
}



// src/AppBundle/Events/WechatEventSubscriber.php

namespace AppBundle\Events;

use AppBundle\Entity\User;
use Lilocon\WechatBundle\Event\AuthorizeEvent;
use Lilocon\WechatBundle\Event\Events;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class WechatEventSubscriber implements EventSubscriberInterface
{
    /**
     * @var ContainerInterface
     */
    private $container;

    /**
     * AuthenticationHandler constructor.
     * @param ContainerInterface $container
     */
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public static function getSubscribedEvents()
    {
        return [
            Events::AUTHORIZE => 'authorize',
        ];
    }

    /**
     * 处理微信用户授权
     * @param AuthorizeEvent $event
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function authorize(AuthorizeEvent $event)
    {
        $wx_user = $event->getUser();

        $manager = $this->container->get('doctrine.orm.default_entity_manager');
        $repository = $manager->getRepository('AppBundle:User');

        $user = $repository->findOneBy(['openid' => $wx_user['openid']]);

        // 若无此用户则写入数据库
        if (!$user) {
            $user = new User();
            $user->setOpenid($wx_user['openid']);
            $user->setNickname($wx_user['nickname']);
            $manager->persist($user);
            $manager->flush();
        }
    }
}


// src/AppBundle/Providers/UserProvider.php

namespace AppBundle\Providers;

use Symfony\Component\DependencyInjection\ContainerInterface;

class UserProvider implements \Lilocon\WechatBundle\Contracts\UserProvider
{

    /**
     * @var ContainerInterface
     */
    private $container;

    /**
     * AuthenticationHandler constructor.
     * @param ContainerInterface $container
     */
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    /**
     * 根据openid获取用户
     * @param $openid
     * @return \AppBundle\Entity\User|null|object
     */
    public function find($openid)
    {
        return $this->container->get('doctrine.orm.default_entity_manager')
            ->getRepository('AppBundle:User')
            ->findOneBy(['openid' => $openid]);
    }
}

    /**
     * @Route("/wechat/test")
     */
    public function testAction()
    {
        return new \Symfony\Component\HttpFoundation\Response($this->getUser());
    }