WechatMsg.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. declare(strict_types=1);
  3. namespace app\api\service\msg;
  4. use app\common\model\MpSubscribe;
  5. use app\common\model\Third;
  6. use app\common\service\MsgService;
  7. use app\common\model\Msg;
  8. class WechatMsg extends MsgService{
  9. protected $msg_type='wechat';
  10. //模板列表
  11. const 模拟模板='111111111111111111111111111111111111';
  12. protected function sendEvent(Msg $msg): bool
  13. {
  14. $config=[
  15. 'appid'=>site_config("weichat.mp_appid"),
  16. 'appsecret'=>site_config("weichat.mp_secret"),
  17. ];
  18. // 实例接口
  19. $wechat = new \WeChat\Template($config);
  20. // 执行操作
  21. try{
  22. $wechat->send(json_decode($msg->content,true));
  23. return true;
  24. }catch (\Exception $e){
  25. $this->error=$e->getMessage();
  26. return false;
  27. }
  28. }
  29. public static function testMsg($user_id)
  30. {
  31. $openid=self::getUserMpOpenid($user_id);
  32. if(!$openid){
  33. return;
  34. }
  35. $postdata=[
  36. 'touser'=>$openid,
  37. 'template_id'=>self::模拟模板,
  38. //跳转到h5首页
  39. //'url'=>request()->domain().'/h5/#/pages/index/index',
  40. //跳转到小程序
  41. 'miniprogram'=>[
  42. 'appid'=>site_config("uniapp.miniapp_id"),
  43. 'pagepath'=>'/pages/index/index',
  44. ],
  45. 'data'=>[
  46. 'thing1'=>['value'=>'测试1'],
  47. 'thing2'=>['value'=>'测试2'],
  48. ]
  49. ];
  50. $postdata=json_encode($postdata,JSON_UNESCAPED_UNICODE);
  51. $service=self::newInstance();
  52. $service->create($postdata,$user_id);
  53. }
  54. private static function getUserMpOpenid($user_id)
  55. {
  56. $unionid=Third::where(['user_id'=>$user_id])->value('unionid');
  57. $openid=MpSubscribe::where(['unionid'=>$unionid])->value('openid');
  58. return $openid;
  59. }
  60. }