73 lines
1.6 KiB
PHP
73 lines
1.6 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Wechat;
|
|
|
|
use EasyWeChat\Kernel\Exceptions\HttpException;
|
|
use EasyWeChat\MiniApp\Application;
|
|
use EasyWeChat\MiniApp\Utils;
|
|
|
|
/**
|
|
* 微信小程序服务基类
|
|
*
|
|
* 封装 EasyWeChat MiniApp Application,提供单例访问和小程序常用方法。
|
|
* 业务模块可继承此类或通过依赖注入使用。
|
|
*/
|
|
class MiniProgramService
|
|
{
|
|
protected ?Application $app = null;
|
|
|
|
/**
|
|
* 获取 EasyWeChat MiniApp Application 实例
|
|
*/
|
|
public function app(): Application
|
|
{
|
|
if (! $this->app) {
|
|
$this->app = new Application(config('wechat.mini_program'));
|
|
}
|
|
|
|
return $this->app;
|
|
}
|
|
|
|
/**
|
|
* 获取 Utils 实例(code2Session、解密等)
|
|
*/
|
|
public function utils(): Utils
|
|
{
|
|
return $this->app()->getUtils();
|
|
}
|
|
|
|
/**
|
|
* 通过 code 换取 session
|
|
*
|
|
* @return array{openid: string, session_key: string, unionid?: string}
|
|
*
|
|
* @throws HttpException
|
|
*/
|
|
public function codeToSession(string $code): array
|
|
{
|
|
return $this->utils()->codeToSession($code);
|
|
}
|
|
|
|
/**
|
|
* 解密加密数据(如用户信息、手机号)
|
|
*
|
|
* @return array<string, mixed>
|
|
*/
|
|
public function decryptData(string $sessionKey, string $iv, string $ciphertext): array
|
|
{
|
|
return $this->utils()->decryptSession($sessionKey, $iv, $ciphertext);
|
|
}
|
|
|
|
/**
|
|
* 获取用户手机号
|
|
*
|
|
* @return array<string, mixed>
|
|
*
|
|
* @throws HttpException
|
|
*/
|
|
public function getPhoneNumber(string $code): array
|
|
{
|
|
return $this->utils()->getPhoneNumber($code);
|
|
}
|
|
}
|