WechatMessageHandler.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. namespace App\Handlers;
  3. use GuzzleHttp\Client;
  4. use Illuminate\Support\Facades\Cache;
  5. class WechatMessageHandler {
  6. public function new(){
  7. $client=new Client();
  8. $client_id = config('config.appid');
  9. $secret = config('config.appsecret');
  10. $url = 'https://api.weixin.qq.com/cgi-bin/token';
  11. $array = [
  12. 'query' => [
  13. 'appid' => $client_id,
  14. 'secret' => $secret,
  15. 'grant_type' => 'client_credential',
  16. ],
  17. ];
  18. $response = $client->request('GET', $url, $array);
  19. $ad = json_decode($response->getBody()->getContents());
  20. $token=$ad->access_token;
  21. Cache::put('wechattoken',$token);
  22. }
  23. public function news($openid,$template_id,$data,$k=0){
  24. $client=new Client();
  25. $url='https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send';
  26. $token=Cache::get('wechattoken');
  27. if (!$token){
  28. $this->new();
  29. $token=Cache::get('wechattoken');
  30. }
  31. $array = [
  32. 'query'=>[
  33. 'access_token' => $token,
  34. ],
  35. 'json' => [
  36. 'touser' => $openid,
  37. 'mp_template_msg'=>[
  38. 'appid'=>env('APPID'),
  39. 'template_id' => $template_id,
  40. 'url'=>'',
  41. "miniprogram"=>[
  42. "appid"=>config('config.appid'),
  43. "pagepath"=>"/pages/index/index"
  44. ],
  45. 'data'=>$data
  46. ]
  47. ],
  48. ];
  49. $response = $client->request('POST', $url, $array);
  50. $ad = json_decode($response->getBody()->getContents());
  51. if ($ad->errcode==0){
  52. return 200;
  53. }else{
  54. Cache::forget('wechattoken');
  55. $this->new();
  56. $k=$k+1;
  57. if ($k==2){
  58. return 300;
  59. }
  60. $code=$this->news($openid,$template_id,$data,$k);
  61. if ($code==200){
  62. return 200;
  63. }
  64. return 300;
  65. }
  66. }
  67. }