Tenim.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <?php
  2. namespace app\common\library;
  3. use getusersig\getusersig;
  4. use tencentim\tencentim;
  5. class Tenim
  6. {
  7. /**
  8. * 发送消息给某人-接口调用
  9. */
  10. public function sendToUser() {
  11. $from_user = '2';// 发送者
  12. $to_user = '294';// 接收者
  13. $message = 'hello许犇';// 接收者
  14. if(!$from_user || !$to_user || !$message) $this->error("参数缺失!");
  15. $this->sendMessageToUser($from_user,$to_user,$message);
  16. }
  17. /**
  18. * 发送消息给某人
  19. */
  20. //https://console.tim.qq.com/v4/openim/sendmsg?sdkappid=88888888&identifier=admin&usersig=xxx&random=99999999&contenttype=json
  21. public function sendMessageToUser($from_user,$to_user,$message) {
  22. $random = rand(10000000,99999999);
  23. $usersig = $this->usersig("administrator");
  24. // 获取配置信息
  25. $config = config("tencent_im");
  26. $url = "https://console.tim.qq.com/v4/openim/sendmsg";
  27. $url .= "?sdkappid=".$config["sdkappid"];
  28. $url .= "&identifier=administrator";
  29. $url .= "&usersig=".$usersig;
  30. $url .= "&random=".$random;
  31. $url .= "&contenttype=json";
  32. $tencentObj = new tencentim($url);
  33. $data = [];
  34. $data["SyncOtherMachine"] = 1;
  35. $data["From_Account"] = (string)$from_user;
  36. $data["To_Account"] = (string)$to_user;
  37. $data["MsgRandom"] = rand(1000000,9999999);
  38. $data["MsgTimeStamp"] = time();
  39. $data["MsgBody"][] = [
  40. "MsgType" => "TIMTextElem",
  41. "MsgContent" => [
  42. "Text"=> $message
  43. ],
  44. ];
  45. $tencentObj->toSend($data);
  46. }
  47. //注册用户到im
  48. public function register($userid,$nickname,$avatar) {
  49. $random = rand(10000000,99999999);
  50. $usersig = $this->usersig("administrator");
  51. //dump($usersig);
  52. // 获取配置信息
  53. $config = config("tencent_im");
  54. $url = "https://console.tim.qq.com/v4/im_open_login_svc/account_import";
  55. $url .= "?sdkappid=".$config["sdkappid"];
  56. $url .= "&identifier=administrator";
  57. $url .= "&usersig=".$usersig;
  58. $url .= "&random=".$random;
  59. $url .= "&contenttype=json";
  60. $tencentObj = new tencentim($url);
  61. $data = [
  62. 'UserID' => $userid,
  63. 'Nick' => $nickname,
  64. 'FaceUrl' => $avatar,
  65. ];
  66. $res = $tencentObj->toSend($data);
  67. if (empty($res['ActionStatus']) || $res['ActionStatus'] != 'OK') {
  68. $error = !empty($res['ErrorInfo']) ? 'im error:'.$res['ErrorInfo'] : 'im error';
  69. return $error;
  70. }
  71. return true;
  72. }
  73. /**
  74. * 获取usersig签名-具体操作
  75. */
  76. public function usersig($user_id) {
  77. // 获取配置信息
  78. $config = config("tencent_im");
  79. $usersigObj = new getusersig($config["sdkappid"],$config["key"]);
  80. $usersig = $usersigObj->genUserSig($user_id);
  81. return $usersig;
  82. }
  83. }