微信包 EasyWechat
环境信息
框架: TP6
PHP: 7.4.3
Composer: 2.5.1
选择包版本
PHP >= 8.0 选择 6.x
PHP >= 7.4 选择 5.x
5.x 只能用V2接口
详见文档
安装使用
安装和配置
composer require overtrue/wechat:~5.0 -vvv
在 config
中创建配置文件 wechat.php
, 这里只用到了小程序登录和支付, 如需要其他的功能, 按需增加配置信息即可, 格式可以自己定
<?php
return [
'app_id' => '',
'secret' => '',
// 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名
'response_type' => 'array',
// V2 支付配置
'pay' => [
'mch_id' => '',
// V2 密钥
'key' => '',
// 绝对路径
'cert_path' => '',
// 绝对路径
'key_path' => '',
'notify_url' => ''
]
];
在 extend
目录创建 easyWechat/Wechat.php
<?php
namespace easyWechat;
use think\facade\Config;
use EasyWeChat\Factory;
use EasyWeChat\MiniProgram\Application;
/**
* easyWechat
* 文档 https://easywechat.com/5.x/mini-program/auth.html
* Class Wechat
* @package easyWechat
*/
class Wechat
{
public function getConfig(): array
{
$wechat = Config::get('wechat');
return [
'app_id' => $wechat['app_id'],
'secret' => $wechat['secret'],
'mch_id' => $wechat['pay']['mch_id'],
'key' => $wechat['pay']['key'],
'cert_path' => $wechat['pay']['cert_path'],
'key_path' => $wechat['pay']['key_path'],
'notify_url' => $wechat['pay']['notify_url'],
];
}
// 小程序登录
public function miniapp_login(string $code){
$wechat = Factory::miniProgram($this->getConfig());;
return $wechat->auth->session($code);
}
// 获取支付对象
public function payment(): \EasyWeChat\Payment\Application
{
return Factory::payment($this->getConfig());
}
}
使用
- 登录
use easyWechat\Wechat;
public function login(string $code): Json {
$wechat = new Wechat();
$res = $wechat->miniapp_login($code);
if (isset($res['errcode'])) {
// 报错 $res['errmsg']
}
$openId = $res['openid'];
// 业务处理
}
- 支付
$wechat = new Wechat();
$payment = $wechat->payment();
// ...