微信公众号支付

This commit is contained in:
liu
2026-09-04 21:22:46 +08:00
parent 52e339cdd3
commit cf1d3a6229
13 changed files with 494 additions and 24 deletions
+72
View File
@@ -0,0 +1,72 @@
<?php
namespace App\Services;
use App\Exceptions\RepositoryException;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
/**
* 微信公众号服务(网页授权 code 换 openid,公众号 JSAPI 支付前置)
*
* H5 页面在微信内置浏览器打开 → 网页授权(snsapi_base)回调带回 code
* → 本服务以 code 换付款人 openid(公众号维度,与小程序 openid 不同,不可混用)
*/
class WechatMpService
{
/**
* 网页授权 code 换 openidsns/oauth2/access_token
*
* @return string 用户公众号维度 openid
* @throws RepositoryException 未配置公众号或授权失败
*/
public function code2openid(string $code): string
{
$appid = $this->appid();
$secret = $this->config('mp_secret');
if ($appid === '' || $secret === '') {
throw new RepositoryException('微信公众号未配置 AppID/Secret,请联系管理员');
}
$result = Http::timeout(10)->withOptions([
'verify' => false, // 禁用 SSL 证书验证
])->get('https://api.weixin.qq.com/sns/oauth2/access_token', [
'appid' => $appid,
'secret' => $secret,
'code' => $code,
'grant_type' => 'authorization_code',
])->json();
$openid = is_array($result) ? (string) ($result['openid'] ?? '') : '';
if ($openid === '') {
Log::warning('微信网页授权失败', ['response' => $result]);
throw new RepositoryException('微信网页授权失败:' . ($result['errmsg'] ?? '请重新授权'));
}
return $openid;
}
/**
* 公众号 AppID(公众号 JSAPI 下单 appid、H5 拼网页授权链接使用)
*/
public function appid(): string
{
return $this->config('mp_appid');
}
/**
* 读取应用配置:后台站点配置(微信应用配置分组)优先,为空回退 config/services.phpenv
*/
protected function config(string $key): string
{
$value = site_config('wechat.' . $key, '');
if ($value === null || $value === '') {
$value = match ($key) {
'mp_appid' => config('services.wechat.mp.appid', ''),
'mp_secret' => config('services.wechat.mp.secret', ''),
default => '',
};
}
return trim((string) $value);
}
}