WxService.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. namespace App\Service;
  3. use Illuminate\Support\Facades\Cache;
  4. class WxService extends Service
  5. {
  6. private $appID = 'wx8c710e2210bee651';
  7. private $appSecret = 'd98ec1fb5b9c9de648f12d1a38db227e';
  8. public function getToken(){
  9. if(Cache::has($this->appID)){
  10. $accessToken = Cache::get($this->appID);
  11. }else{
  12. // 获取访问令牌(Access Token)
  13. $apiURL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appID}&secret={$this->appSecret}";
  14. $response = file_get_contents($apiURL);
  15. $result = json_decode($response, true);
  16. if(isset($result['errcode'])){
  17. return [false,"错误码:{$result['errcode']} 详细信息:{$result['errmsg']}"];
  18. }
  19. $accessToken = $result['access_token'];
  20. $expiresIn = ($result['expires_in']-60)/60;
  21. Cache::add($this->appID,$accessToken,$expiresIn);
  22. }
  23. return [true,$accessToken];
  24. }
  25. //发送普通消息
  26. public function sendToWx($accessToken,$code){
  27. // 发送消息
  28. $sendURL = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=$accessToken";
  29. $userOpenID = 'oBmsr5W_l_8nqQQfIMNP5sBzg8ME';
  30. // 准备普通文本消息的数据
  31. $messageData = array(
  32. 'touser' => $userOpenID,
  33. 'msgtype' => 'text',
  34. 'text' => array(
  35. 'content' => '您的验证码是: '.$code, // 替换为您要发送的验证码
  36. ),
  37. );
  38. $sendData = json_encode($messageData);
  39. $ch = curl_init();
  40. curl_setopt($ch, CURLOPT_URL, $sendURL);
  41. curl_setopt($ch, CURLOPT_POST, 1);
  42. curl_setopt($ch, CURLOPT_POSTFIELDS, $sendData);
  43. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  44. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  45. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  46. $response = curl_exec($ch);
  47. // 处理发送结果
  48. $result = json_decode($response, true);
  49. if ($response === false) {
  50. $error = curl_error($ch);
  51. curl_close($ch);
  52. return [false,$error];
  53. } else {
  54. curl_close($ch);
  55. if ($result['errcode'] == 0) {
  56. return [true,'验证码已成功发送到微信用户!'];
  57. } else {
  58. return [false, '发送验证码时出错:' . $result['errmsg']] ;
  59. }
  60. }
  61. }
  62. }