ThinkPHP6(TP6) 微信接口 EasyWechat

微信包 EasyWechat

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();
// ...

需要什么就在 Wechat 里定义吧, 或者是直接使用

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值