|
|
@@ -0,0 +1,63 @@
|
|
|
+<?php
|
|
|
+
|
|
|
+namespace App\Service;
|
|
|
+
|
|
|
+use Illuminate\Support\Facades\Cache;
|
|
|
+
|
|
|
+class WxService extends Service
|
|
|
+{
|
|
|
+ private $appID = 'wx8c710e2210bee651';
|
|
|
+ private $appSecret = 'd98ec1fb5b9c9de648f12d1a38db227e';
|
|
|
+
|
|
|
+ public function getToken($cacheKey){
|
|
|
+ if(Cache::has($cacheKey)){
|
|
|
+ $accessToken = Cache::get($cacheKey);
|
|
|
+ }else{
|
|
|
+ // 获取访问令牌(Access Token)
|
|
|
+ $apiURL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appID}&secret={$this->appSecret}";
|
|
|
+ $response = file_get_contents($apiURL);
|
|
|
+ $result = json_decode($response, true);
|
|
|
+ if(isset($result['errcode'])){
|
|
|
+ return [false,"错误码:{$result['errcode']} 详细信息:{$result['errmsg']}"];
|
|
|
+ }
|
|
|
+ $accessToken = $result['access_token'];
|
|
|
+ }
|
|
|
+
|
|
|
+ return [true,$accessToken];
|
|
|
+ }
|
|
|
+
|
|
|
+ public function sendToWx($accessToken,$code){
|
|
|
+ // 发送模板消息
|
|
|
+ $sendURL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=$accessToken";
|
|
|
+
|
|
|
+ $userOpenID = '';
|
|
|
+ $template_id = '';
|
|
|
+ // 准备模板消息的数据
|
|
|
+ $templateData = array(
|
|
|
+ 'touser' => $userOpenID,
|
|
|
+ 'template_id' => $template_id,
|
|
|
+ 'data' => array(
|
|
|
+ 'code' => array(
|
|
|
+ 'value' => $code,
|
|
|
+ ),
|
|
|
+ ),
|
|
|
+ );
|
|
|
+
|
|
|
+ $sendData = json_encode($templateData);
|
|
|
+ $ch = curl_init();
|
|
|
+ curl_setopt($ch, CURLOPT_URL, $sendURL);
|
|
|
+ curl_setopt($ch, CURLOPT_POST, 1);
|
|
|
+ curl_setopt($ch, CURLOPT_POSTFIELDS, $sendData);
|
|
|
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
|
|
+ $response = curl_exec($ch);
|
|
|
+ curl_close($ch);
|
|
|
+
|
|
|
+ // 处理发送结果
|
|
|
+ $result = json_decode($response, true);
|
|
|
+ if ($result['errcode'] == 0) {
|
|
|
+ return [true,'验证码已成功发送到微信用户!'];
|
|
|
+ } else {
|
|
|
+ return [false, '发送验证码时出错:' . $result['errmsg']] ;
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|