EasySwoole微信公众号支付

简介EasySwoole微信公众号支付

1. composer require easyswoole/wechat

2. composer require easyswoole/pay


3.EasySwooleEvent.php代码

<?php

namespace EasySwoole\EasySwoole;


use App\WebSocket\WebSocketEvent;
use EasySwoole\EasySwoole\Swoole\EventRegister;
use EasySwoole\EasySwoole\AbstractInterface\Event;
use EasySwoole\Http\Request;
use EasySwoole\Http\Response;
use EasySwoole\Socket\Dispatcher;
use App\WebSocket\WebSocketParser;
use Swoole\Coroutine\Scheduler;
use EasySwoole\Template\Render;
use App\ThinkTemplate\Template;
use EasySwoole\WeChat\WeChat;
use App\WeChat\WeChatManager;
use EasySwoole\Session\Session;
use EasySwoole\Session\SessionFileHandler;

class EasySwooleEvent implements Event
{

   public static function initialize()
   {
       date_default_timezone_set('Asia/Shanghai');

   }

   public static function mainServerCreate(EventRegister $register)
   {
       //以下为热重启
       $hotReloadOptions = new \EasySwoole\HotReload\HotReloadOptions;
       $hotReload = new \EasySwoole\HotReload\HotReload($hotReloadOptions);
       $hotReloadOptions->setMonitorFolder([EASYSWOOLE_ROOT . '/App']);
       $server = ServerManager::getInstance()->getSwooleServer();
       $hotReload->attachToServer($server);

       //可以自己实现一个标准的session handler
       $handler = new SessionFileHandler(EASYSWOOLE_TEMP_DIR);
       //表示cookie name   还有save path
       Session::getInstance($handler,'easy_session','session_dir');

       //以下为公众号配置信息
       $weChatConfig = new \EasySwoole\WeChat\Config(); // 获取WeChat配置实例
       $weChatConfig->setTempDir(Config::getInstance()->getConf('TEMP_DIR')); // 设置全局缓存目录
       $configArray = [
           'appId'     => 'wx763ee4xxxxxxxxxx',
           'appSecret' => 'a161c979394fxxxxxxxxxxxx',
           //'token'     => 'you token',
           //'AesKey'    => 'you AesKey',
       ];
       $weChatConfig->officialAccount($configArray);
       // 注册WeChat对象到全局List
       WeChatManager::getInstance()->register('default', new WeChat($weChatConfig));

       //以下为引入tp框架模板引擎
       Render::getInstance()->getConfig()->setRender(new Template());//thinkphp模板引擎
       Render::getInstance()->attachServer(ServerManager::getInstance()->getSwooleServer());
       
       //以下为websocket配置
       $conf = new \EasySwoole\Socket\Config(); // 创建一个 Dispatcher 配置
       // 设置 Dispatcher WebSocket 模式
       $conf->setType(\EasySwoole\Socket\Config::WEB_SOCKET);
       // 设置解析器对象
       $conf->setParser(new WebSocketParser());
       // 创建 Dispatcher 对象 并注入 config 对象
       $dispatch = new Dispatcher($conf);
       // server 注册相关事件 在 WebSocket 模式下  on message 事件必须注册 并且交给 Dispatcher 对象处理
       $register->set(EventRegister::onMessage, function (\swoole_websocket_server $server, \swoole_websocket_frame $frame) use ($dispatch) {
           $dispatch->dispatch($server, $frame->data, $frame);
       });
       $websocketEvent = new WebSocketEvent();
       //自定义WebSocket连接打开事件
       $register->set(EventRegister::onOpen, function (\swoole_server $server, $req) use ($websocketEvent) {
           $websocketEvent->onOpen($server, $req);
       });
       //自定义WebSocket连接关闭事件
       $register->set(EventRegister::onClose, function (\swoole_server $server, int $fd, int $reactorId) use ($websocketEvent) {
           $websocketEvent->onClose($server, $fd, $reactorId);
       });


   }

   public static function onRequest(Request $request, Response $response): bool
   {
       $cookie = $request->getCookieParams('easy_session');
       if(empty($cookie)){
           $sid = Session::getInstance()->sessionId();
           $response->setCookie('easy_session',$sid);
       }else{
           Session::getInstance()->sessionId($cookie);
       }
       return true;
       // TODO: Implement onRequest() method.
   }

   public static function afterRequest(Request $request, Response $response): void
   {
       // TODO: Implement afterAction() method.
   }
}

2.Index控制器代码

<?php


namespace App\HttpController\WeChat;

use App\WeChat\WeChatManager;
use EasySwoole\Pay\Pay;
use EasySwoole\Pay\WeChat\Config;
use EasySwoole\Pay\WeChat\WeChatPay\OfficialAccount;
use EasySwoole\Template\Render;
use EasySwoole\WeChat\WeChat;
use EasySwoole\WeChat\Bean\OfficialAccount\JsAuthRequest;
use EasySwoole\Http\AbstractInterface\Controller;
use EasySwoole\Session\Session;

class Index extends Controller
{
   protected $weChat;

   protected function onRequest(?string $action): ?bool
   {
//        $this->weChat = WeChatManager::getInstance()->weChat('default')->officialAccount()->server();
       $this->weChat = WeChatManager::getInstance()->weChat('default');
       //return parent::onRequest($action); // TODO: Change the autogenerated stub
       return true;
   }

   public function getCode()
   {

       // 获取JsApi对象
       $jsApi = $this->weChat->officialAccount()->jsApi();

       // 创建微信授权跳转连接
       $jsAuthRequest = new JsAuthRequest();
       // 设置授权后回调地址
       $jsAuthRequest->setRedirectUri('http://pay.beambitious.cn/WeChat/Index/getAccessTokenByCode');
       // 设置 state
       $jsAuthRequest->setState('test');
       // 设置授权类型
       $jsAuthRequest->setType($jsAuthRequest::TYPE_USER_INFO);
       // 返回生成地址 需要开发者自行重定向用户
       $link = $jsApi->auth()->generateURL($jsAuthRequest);
       var_dump($link);
       $this->response()->redirect($link);

   }

   public function getAccessTokenByCode()
   {
       // 获取JsApi对象
       $jsApi = $this->weChat->officialAccount()->jsApi();
       $code = $this->request()->getRequestParam('code');
       // code换去授权
       $snsAuthBean = $jsApi->auth()->codeToToken($code);
       // 用户授权的作用域,使用逗号(,)分隔
       $snsAuthBean->getScope();
       // 用户唯一标识,请注意,在未关注公众号时,用户访问公众号的网页,也会产生一个用户和公众号唯一的OpenID
       //$openid = $snsAuthBean->getOpenid();
       //return $this->writeJson('200',['openid'=>$openid],'success');
       $user = $jsApi->auth()->tokenToUser($snsAuthBean);
       //将用户信息保存至session
       Session::getInstance()->set('user_openid', $user->getOpenid());
       Session::getInstance()->set('user_img', $user->getHeadimgurl());
       Session::getInstance()->set('user_name', $user->getNickname());
       var_dump($user->getOpenid());
       var_dump($user->getHeadimgurl());
       var_dump($user->getNickname());
       //授权成功后跳转页面
       $this->response()->redirect('/hello');
       // 网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同
//        $snsAuthBean->getAccessToken();
       // 用户刷新access_token用的
//        $snsAuthBean->getRefreshToken();
       // 用户刷新access_token
//        $snsAuthBean->getExpiresIn();

   }

   public function pay()
   {
       $wechatConfig = new Config();
       $wechatConfig->setAppId('wx763eexxxxxxxxxxx');      // 除了小程序以外使用该APPID
//        $wechatConfig->setMiniAppId('xxxxxx');  // 小程序使用该APPID
       $wechatConfig->setMchId('16xxxxx04');
       $wechatConfig->setKey('qxxxxxxxxxiopxxxxxx');
       $wechatConfig->setNotifyUrl('/WeChat/Index/notify');
//        $wechatConfig->setApiClientCert('xxxxxxx');//客户端证书
//        $wechatConfig->setApiClientKey('xxxxxxx'); //客户端证书秘钥

       $officialAccount = new \EasySwoole\Pay\WeChat\RequestBean\OfficialAccount();
       $officialAccount->setOpenid(Session::getInstance()->get('user_openid'));
       $officialAccount->setOutTradeNo('CN' . date('YmdHis') . rand(1000, 9999));
       $officialAccount->setBody('测试' . time());
       $officialAccount->setTotalFee(1);
       $officialAccount->setSpbillCreateIp('47.107.246.32');
       $pay = new \EasySwoole\Pay\Pay();
       $params = $pay->weChat($wechatConfig)->officialAccount($officialAccount);
       $params = $params->toArray();
       $this->response()->withHeader('Content-type','charset=utf-8')
           ->write(Render::getInstance()->render('admin/pay',['rows'=>$params]));


   }
   public function notify(){
           //        \EasySwoole\Pay\WeChat\WeChat::success();
   }

   protected function actionNotFound(?string $action)
   {
       parent::actionNotFound($action); // TODO: Change the autogenerated stub
   }

}


 

文章评论

共有0条评论来说两句吧...

用户名:

验证码:

Top