laravel安裝laravel-wechat 實現微信授權登入
一.下載laravel-wechat
https://packagist.org/packages/overtrue/laravel-wechat
二. 使用composer安裝laravel-wechat
composer require "overtrue/laravel-wechat:~4.0"
三.配置
在 config/app.php 註冊 ServiceProvider 和 Facade (Laravel 5.5 + 無需手動註冊)
'providers' => [
// ...
Overtrue\LaravelWeChat\ServiceProvider::class,
],
'aliases' => [
// ...
'EasyWeChat' => Overtrue\LaravelWeChat\Facade::class,
],
建立配置檔案:
php artisan vendor:publish --provider="Overtrue\LaravelWeChat\ServiceProvider
1.修改應用根目錄下的 config/wechat.php 中對應的引數即可。
WECHAT_LOG_LEVEL=info //日誌級別 最好和laravel同級
WECHAT_LOG_FILE=/var/log/coupon/report.log //日誌儲存檔案 最好和laravel 統一
WECHAT_OFFICIAL_ACCOUNT_APPID=申請的appid
WECHAT_OFFICIAL_ACCOUNT_SECRET=申請的appsecret
WECHAT_OFFICIAL_ACCOUNT_TOKEN=
WECHAT_OFFICIAL_ACCOUNT_AES_KEY=
<?php
namespace Modules\Easywechat\Http\Controllers;
use EasyWeChat\Factory;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
class EasywechatController extends Controller
{
/**
* 公眾號token驗證
*
* @return string
*/
public function serve()
{
$app = app('wechat.official_account');
$app->server->push(function ($message) {
return "歡迎關注 overtrue!";
});
return $app->server->serve();
}
/** 公眾號模板訊息傳送
* @param $data
* @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
* @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function confirm_receipt($data)
{
$config = config('wechat.official_account.default');
$app = Factory::officialAccount($config);
$app->template_message->send([
'touser' => $data['openid'], //使用者openid
'template_id' => env('CONFIRM_RECEIPT', '45445'), //傳送的模板id
'data' => [
'first' => '您已確認收貨,請知曉!',
'keyword1' => $data['order_no'],
'keyword4' => $data['name'],
],
]);
}
//公眾號授權
public function officialAccounts()
{
$app = app('wechat.official_account');
$oauth = $app->oauth;
// 指定回撥 URL,比如設定回撥 URL 為當前頁面
// $redirectUrl = $oauth->scopes(['snsapi_userinfo'])->redirect();
$redirectUrl = $oauth->scopes(['snsapi_userinfo'])->redirect();
return \redirect($redirectUrl);
// return $this->success(compact('redirectUrl'));
}
//公眾號授權回撥
public function officialAccountToNotify(Request $request)
{
$code = $request->code ? $request->code : null;
if (empty($code)) {
return $this->fail('請重新授權登入');
}
$app = app('wechat.official_account');
$oauth = $app->oauth;
// 獲取 OAuth 授權使用者資訊
$userinfo = $oauth->userFromCode($code);
$user = User::where('openid', $userinfo["openid"]);
$data = $userinfo['raw'];
if ($user->doesntExist()) {
$data['avatar'] = $data['headimgurl'];
$data['name'] = $data['nickname'];
$data['password'] = Hash::make('8888888');
$data['enable_status'] = 0;
unset($data['headimgurl']);
unset($data['privilege']);
$userinfo = User::create($data);
} else {
$userinfo = $user->first();
}
$access_token = $userinfo->createToken('user')->accessToken;
return $this->success(['access_token' => 'Bearer ' . $access_token]);
}
/**
*小程式 微信授權登入
* @param Request $request
* @return array
*/
public function wxappLogin(Request $request)
{
$app = app('wechat.mini_program');
$data = $app->auth->session($request->code);
if (isset($data['errcode'])) {
return $this->fail('code已過期或不正確');
}
$userInfo = $app->encryptor->decryptData($data['session_key'], $request->iv, $request->encryptedData);
$user = User::where('openid', $data["openid"]);
if ($user->doesntExist()) {
$userInfo['openid'] = $data["openid"];
$userInfo['avatar'] = $userInfo['avatarUrl'];
$userInfo['nickname'] = $userInfo['nickName'];
$userInfo['name'] = $userInfo['nickName'];
$userInfo['password'] = Hash::make('8888888');
$userInfo['enable_status'] = 0;
unset($userInfo['nickName']);
unset($userInfo['avatarUrl']);
unset($userInfo['watermark']);
// return $this->success($userInfo);
$userinfo = User::create($userInfo);
} else {
$userinfo = $user->first();
}
$access_token = $userinfo->createToken('user')->accessToken;
return $this->success(['access_token' => 'Bearer ' . $access_token]);
// return $this->success(['c' => $this->wxapp_config, 'b' => $app, 'f' => $data, 'userInfo' => ]);
}
}
laravel使用EasyWeChat 統一下單
use EasyWeChat\Factory;
private $app;
public function __construct()
{
$config = config('wechat.payment.default');
$this->app = Factory::payment($config);
}
public function payment(PayRequest $request){
$isContract = true;
$result = $this->app->order->unify([
'body' => '使用者下單',
'out_trade_no' => $order_no,
'total_fee' => 10,
// 'spbill_create_ip' => '123.12.12.123', // 可選,如不傳該引數,SDK 將會自動獲取相應 IP 地址
'notify_url' => config('wechat.payment.default.notify_url'), // 支付結果通知網址,如果不設定則會使用配置裡的預設地址
'trade_type' => 'JSAPI', // 請對應換成你的支付方式對應的值型別
'openid' => Auth::user()->openid,
], $isContract);
//注意
1、如果支付時出現報錯,timestame 引數問題。這是 easywechat 底層檔案出錯了。
if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
$config['timeStamp'] = $config['timestamp'];
unset($config['timestamp']);
return $this->success( $config);
}else{
return $this->fail('支付失敗');
}
2、如果簽名失敗
if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
$prepayId = $result['prepay_id'];
$jssdk =$this->app->jssdk;
$config = $jssdk->sdkConfig($prepayId);
$config['timeStamp'] = $config['timestamp'];
unset($config['timestamp']);
return $this->success( $config);
}else{
return $this->fail('支付失敗');
}
}
申請退款
退款方式 分為兩種
第一種:根據微信訂單號退款
// 引數分別為:微信訂單號、商戶退款單號、訂單金額、退款金額、其他引數
$app->refund->byTransactionId(string $transactionId, string $refundNumber, int $totalFee, int $refundFee, array $config = []);
// Example:
$result = $app->refund->byTransactionId('transaction-id-xxx', 'refund-no-xxx', 10000, 10000, [
// 可在此處傳入其他引數,詳細引數見微信支付文件
'refund_desc' => '商品已售完',
]);
使用
第二種:根據商戶訂單號退款
// 引數分別為:商戶訂單號、商戶退款單號、訂單金額、退款金額、其他引數
$app->refund->byOutTradeNumber(string $number, string $refundNumber, int $totalFee, int $refundFee, array $config = []);
// Example:
$result = $app->refund->byOutTradeNumber('out-trade-no-xxx', 'refund-no-xxx', 20000, 1000, [
// 可在此處傳入其他引數,詳細引數見微信支付文件
'refund_desc' => '退運費',
]);
本作品採用《CC 協議》,轉載必須註明作者和本文連結