Files
heping-api/app/controller/Wechat.php
2022-09-09 14:31:35 +08:00

113 lines
2.9 KiB
PHP

<?php
namespace app\controller;
use app\model\AppUser;
use EasyWeChat\Factory;
use EasyWeChat\OfficialAccount\Application;
use think\facade\Config;
use think\facade\Db;
use think\facade\Request;
use think\facade\Route;
use think\facade\View;
use think\response\Json;
class Wechat
{
private Application $app;
/**
* Notes : 初始化微信
*
* @Date : 2022/9/9 11:30
* @Author : <Jason.C>
*/
private function initWechat()
{
$this->app = Factory::officialAccount(Config::get('wechat'));
}
/**
* Notes : 获取微信授权的地址并跳转
*
* @Date : 2022/9/9 11:29
* @Author : <Jason.C>
*/
public function url(): Json
{
$url = $GLOBALS['data']['data']['url'];
$redirect = Route::buildUrl('wechat/code', ['callback' => $url])
->suffix(false)
->domain(true);
$this->initWechat();
return show(SUCCESS_MESSAGE, SUCCESS_CODE, $this->app->oauth->scopes(['snsapi_userinfo'])->redirect($redirect));
}
/**
* Notes : 微信授权回调地址,获取到用户信息后,自行保存
*
* @Date : 2022/9/9 11:29
* @Author : <Jason.C>
*/
public function code()
{
$this->initWechat();
$user = $this->app->oauth->user();
$callback = Request::get('callback');
$user = AppUser::where('openid', $user->getId())->find();
if (!$user) {
$user = AppUser::create([
'nickname' => $user->getNickname(),
'avatar' => $user->getAvatar(),
'identity' => 1,
'openid' => $user->getId(),
]);
}
$tokenData = ['userid' => $user->id, 'loginTime' => time(), 'rankStr' => strRand(5)];
$token = authcode(json_encode($tokenData), 'ENCODE');
return redirect($callback.'?token='.$token);
}
/**
* Notes : 显示支付的页面,支付逻辑
*
* @Date : 2022/9/9 11:32
* @Author : <Jason.C>
*/
public function payment()
{
$notifyUrl = Route::buildUrl('wechat/paid')
->suffix(false)
->domain(true);
$config = Config::get('wechat.payment');
$payment = Factory::payment($config);
$unify = $payment->order->unify([
'body' => '商品订单',
'out_trade_no' => time(),
'total_fee' => 100,
'notify_url' => $notifyUrl,
'trade_type' => 'JSAPI',
'openid' => '$openid',
]);
dump($unify);
// $prepayId = $unify->prepay_id;
// $jssdk = $payment->jssdk->bridgeConfig($prepayId);
// return View::fetch('', ['jssdk' => $jssdk]);
}
/**
* Notes : 支付完成回调
*
* @Date : 2022/9/9 11:33
* @Author : <Jason.C>
*/
public function paid()
{
}
}