Commit ea59b59c authored by 黄英浩's avatar 黄英浩

微信发送模板消息

parent 66f24bac
<?php
namespace App\Exceptions;
class AuthenticateException extends \Exception
{
}
\ No newline at end of file
<?php
namespace App\Exceptions;
class BusinessException extends \Exception
{
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: fffff
* Date: 2018/12/10
* Time: 17:30
*/
namespace App\Exceptions;
class SystemException extends \Exception
{
}
<?php
/**
* Created by PhpStorm.
* User: fffff
* Date: 2018/12/7
* Time: 17:05
*/
namespace App\Http\Controllers\Controller\WeChat;
use App\Http\Controllers\Controller;
use EasyWeChat\Factory;
use EasyWeChatComposer\EasyWeChat;
class ServerPushController extends Controller
{
public function test()
{
Factory::
$easyWeChat->
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: fffff
* Date: 2018/12/7
* Time: 17:05
*/
namespace App\Http\Controllers\Welfare\WeChat;
use App\Http\Controllers\Controller;
use App\Repositories\Common\TemplateConfigRepositories;
use App\Services\Welfare\WeChat\TemplatePushService;
use Illuminate\Http\Request;
class TemplatePushController extends Controller
{
public function __construct()
{
defined('COMPANY_SOURCE') ?: define('COMPANY_SOURCE', 'welfare');
}
/**
* @param Request $request
* @param TemplateConfigRepositories $templateConfigRepositories
* @param TemplatePushService $templatePushService
* @return bool
* @throws \App\Exceptions\SystemException
* @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
* @throws \Psr\SimpleCache\InvalidArgumentException
*/
public function sendTemplateMsg(Request $request, TemplateConfigRepositories $templateConfigRepositories, TemplatePushService $templatePushService)
{
$templateId = $templatePushService->getTemplateId($templateConfigRepositories, COMPANY_SOURCE, $request->get('type'));
$templatePushService->push($request->get('user-openid'), $templateId );
return true;
}
}
\ No newline at end of file
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
namespace App\Http; namespace App\Http;
use App\Http\Middleware\AuthCheck;
use Illuminate\Foundation\Http\Kernel as HttpKernel; use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel class Kernel extends HttpKernel
...@@ -60,6 +61,7 @@ class Kernel extends HttpKernel ...@@ -60,6 +61,7 @@ class Kernel extends HttpKernel
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class, 'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class, 'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'auth.check' => AuthCheck::class,
]; ];
/** /**
......
<?php
namespace App\Http\Middleware;
use App\Exceptions\AuthenticateException;
use App\Services\Common\LoginUser;
use App\Services\Common\UserInfo;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
class AuthCheck
{
/**
* @param Request $request
* @param Closure $next
* @return mixed
* @throws AuthenticateException
*/
public function handle(Request $request, Closure $next)
{
// $tokenName = 'token';
//
// if (!$request->hasHeader($tokenName)
// || ($token = $request->header($tokenName) && empty($token))
// ) {
// throw new AuthenticateException('请登录');
// }
//
// try {
// $userInfo = $this->getUserInfo($token);
// LoginUser::getInstance()->setUserInfo($userInfo);
// } catch (\Exception $e) {
// throw new AuthenticateException('请登录');
// }
return $next($request);
}
/**
* @param $token
* @return mixed
* @throws AuthenticateException
*/
private function getUserInfo($token)
{
$userInfo = Cache::store('redis')->get($token);
if (empty($userInfo)) {
throw new AuthenticateException();
}
return $userInfo;
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class TemplateConfigModel extends Model
{
protected $table = 'template_config';
protected $primaryKey = 'id';
public $timestamps = false;
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class UserFormIdModel extends Model
{
protected $table = 'user_formid';
protected $primaryKey = 'id';
public $timestamps = false;
}
<?php
/**
* Date: 2018/11/19
* Time: 16:59
* Author: 罗马
* Description:
*/
namespace App\Repositories\Common;
use App\Models\TemplateConfigModel;
use Prettus\Repository\Eloquent\BaseRepository;
class TemplateConfigRepositories extends BaseRepository
{
/**
* Specify Model class name
*
* @return string
*/
public function model()
{
return TemplateConfigModel::class;
}
}
\ No newline at end of file
<?php
/**
* Date: 2018/11/19
* Time: 16:59
* Author: 罗马
* Description:
*/
namespace App\Repositories\Common;
use App\Models\UserFormIdModel;
use Prettus\Repository\Eloquent\BaseRepository;
class UserFormidRepository extends BaseRepository
{
/**
* Specify Model class name
*
* @return string
*/
public function model()
{
return UserFormIdModel::class;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: wyung
* Date: 2018/11/21
* Time: 下午3:35
*/
namespace App\Services;
class BaseService
{
/**
* @param $url
* @param $params
* @param null $headers
* @param string $request_method
* @param bool $post_file
* @return mixed
*/
public function http_request($url, $params, $headers = NULL, $request_method = 'post', $post_file = false)
{
$oCurl = curl_init();
if (stripos($url, "https://") !== FALSE) {
curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
}
if (PHP_VERSION_ID >= 50500 && class_exists('\CURLFile')) {
$is_curlFile = true;
} else {
$is_curlFile = false;
if (defined('CURLOPT_SAFE_UPLOAD')) {
curl_setopt($oCurl, CURLOPT_SAFE_UPLOAD, false);
}
}
//Log::info('请求报文:' . $strPOST);
curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
if ($request_method == 'post') {
$strPOST = json_encode($params);
curl_setopt($oCurl, CURLOPT_POST, true);
curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);
} else {
$param_str = '?';
foreach ($params as $key => $value) {
$param_str .= $key . '=' . $value . '&';
}
$param_str = substr($param_str, 0, strlen($param_str) - 1);
$url = $url . $param_str;
}
curl_setopt($oCurl, CURLOPT_URL, $url);
if ($headers) {
curl_setopt($oCurl, CURLOPT_HTTPHEADER, $headers);
}
$sContent = curl_exec($oCurl);
$aStatus = curl_getinfo($oCurl);
curl_close($oCurl);
return json_decode($sContent, true);
}
/**
* 获取session_key
* @param $appid
* @param $secret
* @param $code
* @param string $grant_type
* @return string
*/
public function get_session_key($appid,$secret,$code,$grant_type = 'authorization_code')
{
$url = 'https://api.weixin.qq.com/sns/jscode2session';
$params = array(
'appid' => $appid,
'secret' => $secret,
'js_code' => $code,
'grant_type' => $grant_type,
);
$return_data = $this->http_request($url,$params,null,'get');
return $return_data;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: fffff
* Date: 2018/11/20
* Time: 14:48
*/
namespace App\Services\Common;
use App\Constants\CommonRespCode;
use App\Exceptions\AuthenticateException;
use App\Exceptions\BusinessException;
use App\Exceptions\CurlException;
use App\Libraries\Helper\Request;
use Illuminate\Support\Facades\Log;
class UserInfo
{
private static $instance = null;
private $userId;
private $token;
private $platform;//1福利小程序 2福利后台
private $userInfo;
public static function getInstance()
{
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
public function setUserInfo(array $userInfo)
{
$this->userInfo = $userInfo;
}
public function getUserInfo()
{
return $this->userInfo;
}
public function setPlatform($platform)
{
$this->platform = $platform;
return $this;
}
public function setUserId($userId)
{
$this->userId = $userId;
return $this;
}
public function getUserId()
{
return $this->userId;
}
public function setToken($token)
{
$this->token = $token;
return $this;
}
/**
* 从财务系统获取用户积分情况
* @return array
* @throws CurlException
*/
public function getUserFromFinance()
{
$url = config('api.FXQF_FINANCE') . config('api.FXQF_FINANCE_GET_USER_INFO');
$result = Request::get($url, ['user_id' => $this->userId]);
Log::channel('userinfo')->info(
vsprintf('【用户积分信息获取】请求url:[%s],响应结果:[%s]', [
$url, var_export($result, true)
])
);
$result = json_decode($result, true);
if (0 !== $result['code']) {
return ['balance' => 0, 'total_income_amount' => 0];
}
$result = $result['data'];
$result['balance'] = $result['balance'] ?? 0;
$result['total_income_amount'] = $result['total_income_amount'] ?? 0;
return [
'balance' => round($result['balance'], 2),
'total_income_amount' => round($result['total_income_amount'], 2)
];
}
/**
* 获取用户信息
* @return array|mixed|string
* @throws AuthenticateException
* @throws BusinessException
*/
public function getUserFromUserCenterWithToken()
{
$url = config('api.USER_CENTER') . config('api.USER_CENTER_GET_USER_INFO');
$data = [
'fx-token' => $this->token,
'get_type' => UserCenter::USER_CENTER_GET_WITH_TOKEN_TYPE,
'method' => UserCenter::USER_CENTER_GET_ONE_USER_METHOD,
'platform' => 1, //TODO 临时
];
try {
$result = Request::get($url, $data);
} catch (CurlException $e) {
throw new BusinessException(CommonRespCode::CURL_ERROR);
}
Log::channel('userinfo')->info(
vsprintf('【用户基础信息获取】请求url:[%s],响应结果:[%s]', [
$url, var_export($result, true)
])
);
$result = json_decode($result, true);
if (0 !== $result['code']) {
throw new AuthenticateException();
}
$result = [
'nick_name' => $result['data']['nick_name'] ?? '',
'avatar' => $result['data']['avatar'] ?? '',
'section_name' => $result['data']['section_name'] ?? '',
'cover' => $result['data']['cover'] ?? '',
'company_name' => $result['data']['company_name'] ?? '',
'company_id' => $result['data']['company_id'] ?? '',
'phone' => $result['data']['phone'] ?? '',
'uid' => $result['data']['uid'] ?? '',
'name' => $result['data']['staff_name'] ?? '',
'staff_id' => $result['data']['staff_id'] ?? '',
];
return $result;
}
/**
* 获取用户信息
* @return array|mixed|string
*/
public function getUserFromUserCenterWithUserId()
{
$url = config('api.USER_CENTER') . config('api.USER_CENTER_GET_USER_INFO');
$data = [
'uid' => $this->userId,
'get_type' => UserCenter::USER_CENTER_GET_WITH_UID_TYPE,
'method' => UserCenter::USER_CENTER_GET_ONE_USER_METHOD,
'platform' => 1,//TODO 临时
];
try {
$result = Request::get($url, $data);
Log::channel('userinfo')->info(
vsprintf('【用户基础信息获取】请求url:[%s],响应结果:[%s]', [
$url, var_export($result, true)
])
);
$result = json_decode($result, true);
} catch (CurlException $e) {
return [
'nick_name' => '',
'avatar' => '',
'section_name' => '',
'cover' => '',
'company_name' => '',
'company_id' => '',
'phone' => '',
'uid' => '',
'name' => '',
'staff_id' => ''
];
}
$result = [
'nick_name' => $result['data']['nick_name'] ?? '',
'avatar' => $result['data']['avatar'] ?? '',
'section_name' => $result['data']['section_name'] ?? '',
'cover' => $result['data']['cover'] ?? '',
'company_name' => $result['data']['company_name'] ?? '',
'company_id' => $result['data']['company_id'] ?? '',
'phone' => $result['data']['phone'] ?? '',
'uid' => $result['data']['uid'] ?? '',
'name' => $result['data']['staff_name'] ?? '',
'staff_id' => $result['data']['staff_id'] ?? '',
];
return $result;
}
/**
* 获取多个用户的信息
* @param array $user_ids
* @return array
*/
public function getUsersFromUserCenter(array $user_ids)
{
if (empty($user_ids)) {
return [];
}
$url = config('api.USER_CENTER') . config('api.USER_CENTER_GET_USERS_INFO');
$data = [
'uid' => implode(',',$user_ids)
];
try
{
$result = Request::get($url, $data);
Log::channel('userinfo')->info(
vsprintf('【用户基础信息获取】请求url:[%s], 响应结果:[%s]', [
$url, var_export($result, true)
])
);
$result = json_decode($result, true);
if (0 !== $result['code']) {
return [];
}
$result = $result['data']['list'];
$users = [];
if (!empty($result) && is_array($result)) {
foreach ($result as $key => $val) {
$users[$val['uid']] = $val;
}
}
return $users;
}catch (CurlException $e) {
return [];
}
}
/**
* 根据条件筛选用户
* @param $company_id
* @param $condition
* @param $keyword
* @return array|mixed|string
*/
public function getUsersByKeywordFromUserCenter($company_id, $condition, $keyword)
{
$url = config('api.USER_CENTER') . config('api.USER_CENTER_GET_USER_INFO_BY_KEYWORD');
$data = [
'company_id' => $company_id,
'condition' => $condition,
'keyword' => $keyword,
];
try {
$result = Request::get($url, $data);
Log::channel('userinfo')->info(
vsprintf('【用户基础信息获取】请求url:[%s], data:%s 响应结果:[%s]', [
$url, json_encode($data), var_export($result, true)
])
);
$result = json_decode($result, true);
if (0 !== $result['code']) {
return [];
}
$result = $result['data']['list'];
return $result;
} catch (CurlException $e) {
return [];
}
}
/**
* 获取所有公司
* @author yujie
* @date 2018-11-22
* @param $condition
* @param $keyword
* @return mixed|string
* @throws BusinessException
*/
public function getCompanies()
{
$url = config('api.USER_CENTER') . config('api.USER_CENTER_GET_COMPANIES');
try
{
$result = Request::get($url);
Log::channel('userinfo')->info(
vsprintf('【用户基础信息获取】请求url:[%s], 响应结果:[%s]', [
$url, var_export($result, true)
])
);
$result = json_decode($result, true);
if (0 !== $result['code']) {
return [];
}
$result = $result['data'];
return $result;
}catch (CurlException $e) {
return [];
}
}
}
<?php
/**
* Created by PhpStorm.
* User: fffff
* Date: 2018/12/10
* Time: 15:43
*/
namespace App\Services\Common;
use App\Exceptions\BusinessException;
use App\Exceptions\SystemException;
use EasyWeChat\Factory;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
class WeChat
{
protected static $instance;
protected $cache;
protected $token;
protected $easyWeChat;
/**
* 获得句柄
* @return WeChat
*/
public static function getInstance()
{
if (is_null(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
public function getEasyWeChatInstance()
{
return $this->easyWeChat;
}
public function __construct()
{
$this->cache = Cache::store('redis');
$this->easyWeChat = Factory::officialAccount(config('weChat'));
}
/**
* @return mixed
* @throws SystemException
* @throws \Psr\SimpleCache\InvalidArgumentException
*/
public function getToken()
{
$keys = $this->cache->keys(COMPANY_SOURCE . '-TOKEN-*');
if (empty($keys)) {
$this->setToken();
} else {
$key = array_pop($keys);
$expire = $this->cache->ttl($key);
if ($expire <= 7200) {
$this->setToken();
} else {
$this->token = $this->cache->get($key);
$this->easyWeChat->access_token->setToken($this->token, $expire);
}
}
return $this->token;
}
/**
* 设置token
* @throws SystemException
* @throws \Psr\SimpleCache\InvalidArgumentException
*/
protected function setToken()
{
$keyName = COMPANY_SOURCE . '-TOKEN-' . time();
try {
$token = $this->easyWeChat->access_token->getToken();
$this->cache->set($keyName, $token, 7200);
} catch (\Exception $e) {
Log::channel('syslog')->info('缓存连接失败');
throw new SystemException('系统繁忙');
}
$this->token;
}
}
<?php
/**
* Created by PhpStorm.
* User: fffff
* Date: 2018/12/10
* Time: 17:55
*/
namespace App\Services\Welfare\WeChat;
use App\Repositories\Common\TemplateConfigRepositories;
use App\Services\Common\WeChat;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
class TemplatePushService
{
protected $easyWeChat;
public function __construct()
{
$this->easyWeChat = WeChat::getInstance()->getEasyWeChatInstance();
}
/**
* @param Request $request
* @return bool
* @throws \App\Exceptions\SystemException
* @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
* @throws \Psr\SimpleCache\InvalidArgumentException
*/
public function push($userOpenid, $templateId)
{
WeChat::getInstance()->getToken();
$template_message = $this->easyWeChat->template_message;
$requestData = [
'touser' => $userOpenid,
'template_id' => $templateId,
'url' => '' , //小程序跳转的连接
'data' => [
'key1' => 'VALUE',
'key2' => 'VALUE2',
]
];
$response = $template_message->send($requestData);
return true;
}
public function getTemplateId(TemplateConfigRepositories $templateConfigRepositories, $companyName, $type)
{
$templateId = $templateConfigRepositories->model()
->where(['company_name' => $companyName, 'type' => $type])
->fields('template_id')
->first();
return $templateId;
}
}
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
...@@ -9,10 +9,14 @@ ...@@ -9,10 +9,14 @@
"license": "MIT", "license": "MIT",
"require": { "require": {
"php": "^7.1.3", "php": "^7.1.3",
"barryvdh/laravel-ide-helper": "^2.5",
"doctrine/dbal": "^2.9",
"fideloper/proxy": "^4.0", "fideloper/proxy": "^4.0",
"laravel/framework": "5.7.*", "laravel/framework": "5.7.*",
"laravel/tinker": "^1.0", "laravel/tinker": "^1.0",
"overtrue/wechat": "~4.0" "overtrue/wechat": "~4.0",
"predis/predis": "^1.1",
"prettus/l5-repository": "^2.6"
}, },
"require-dev": { "require-dev": {
"beyondcode/laravel-dump-server": "^1.0", "beyondcode/laravel-dump-server": "^1.0",
......
<?php
/**
* Created by PhpStorm.
* User: fffff
* Date: 2018/12/10
* Time: 10:20
*/
return [
];
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: fffff
* Date: 2018/12/10
* Time: 17:35
*/
return [
'app_id' => env('WECHAT_APP_ID', 'your-app-id'), // AppID
'secret' => env('WECHAT_SECRET', 'your-app-secret'), // AppSecret
'response_type' => 'array',
'log' => [
'default' => 'dev', // 默认使用的 channel,生产环境可以改为下面的 prod
'channels' => [
// 测试环境
'dev' => [
'driver' => 'daily',
'path' => '/easywechat.log',
'level' => 'debug',
],
// 生产环境
'prod' => [
'driver' => 'daily',
'path' => '/easywechat.log',
'level' => 'info',
],
],
],
];
\ No newline at end of file
...@@ -12,5 +12,11 @@ ...@@ -12,5 +12,11 @@
*/ */
Route::get('/', function () { Route::get('/', function () {
return view('welcome'); echo 1;
});
Route::group(['prefix' => 'welfare'], function () {
Route::group(['middleware' => 'auth.check'], function () {
Route::get('/we-chat/template-push', 'Welfare\\WeChat\\TemplatePushController@sendTemplateMsg');
});
}); });
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment