Home Backend Development PHP Tutorial How to send mass messages on WeChat? PHP WeChat advanced interface mass message multi-customer service

How to send mass messages on WeChat? PHP WeChat advanced interface mass message multi-customer service

Jul 28, 2016 am 08:29 AM

The examples in this article share the PHP WeChat advanced interface group messaging and multi-customer service source code for your reference. The specific content is as follows

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

486

487

488

489

490

491

492

493

494

495

496

497

498

499

500

501

502

503

504

505

506

507

508

509

510

511

512

513

514

515

516

517

518

519

520

521

522

523

524

525

526

527

528

529

530

531

532

533

534

535

536

537

538

539

540

541

542

543

544

545

546

547

548

549

550

551

552

553

554

555

556

557

558

559

560

561

562

563

564

565

566

567

568

569

570

571

572

573

574

575

576

577

578

579

580

581

582

583

584

585

586

587

588

589

590

591

592

593

594

595

596

597

598

599

600

601

602

603

604

605

606

607

608

609

610

611

612

613

614

615

616

617

618

619

620

621

622

623

624

625

626

627

628

629

630

631

632

633

634

635

636

637

638

639

640

641

642

643

644

645

646

647

648

649

650

651

652

653

654

655

656

657

658

659

660

661

662

663

664

665

666

667

668

669

670

671

672

673

674

675

676

677

678

679

680

681

682

683

684

685

686

687

688

689

690

691

692

693

694

695

696

697

698

699

700

701

702

703

704

705

706

707

708

709

710

711

712

713

714

715

716

717

718

719

720

721

722

723

724

725

726

727

728

729

730

731

732

733

734

735

736

737

738

739

740

/**

 * 微信接口调用

 * 依赖

 * 全局变量

 * global $uid 公众号用户id, $wid 公众号id, $wechatid 粉丝唯一id;

 * 参数

 * $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

 * $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);

 * 缓存类 自定义

 * Cache:set

 * Cache:get

 * 具体业务修改

 * 1.上传图文信息至微信素材库

 * function uploadArticlesToWeiXinServer()

 * 2.关键字匹配图文回复

 * function getArticleData()

 *

 * usage:

 *  $options = array(

 *  'token'=>'tokenaccesskey', //填写你设定的key

 *  'appid'=>'wxdk1234567890', //填写高级调用功能的app id

 *  'appsecret'=>'xxxxxxxxxxxxxxxxxxx', //填写高级调用功能的密钥

 *  );

 */

class WeiXinTool {

 

  private $appid;

  private $appsecret;

  private $access_token;

  private $mediaType = array('image' => array("jpg"), 'voice' => array('amr', 'MP3'), 'video' => array('mp4'), 'thumb' => array("jpg"));

  private $mediaMaxSize = array('image' => 131072, 'voice' => 262144, 'video' => 1048576, 'thumb' => 65536);

  private $tem_file_path = "";

 

//  授权地址

  const AUTH_URL = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s';

//  素材上传

  const UPLOAD_MEDIA_URL = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=%s&type=%s";

  const GET_MEDIA_URL = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=%s&media_id=%s";

  const UPLOAD_NEWS_URL = "https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=%s";

 

  public function __construct($options) {

    $this->appid = isset($options['appid']) ? $options['appid'] : '';

    $this->appsecret = isset($options['appsecret']) ? $options['appsecret'] : '';

    //需修改

    //上传图片临时文件目录自定义

    $this->tem_file_path = YYUC_FRAME_PATH . YYUC_PUB . '/' . Session::get('upath');

  }

 

  /**

   * 需修改

   * 具体业务需求,图文信息上传至素材库

   * 微站文章上传至微信素材

   * @param type $wid

   * @param type $aid

   * @return int

   */

  public function uploadArticlesToWeiXinServer($wid, $aid) {

 

    //具体图文组装过程,需修改

    $m = new Model('website_article');

    $m_pubs = new Model('pubs');

    $m_pubs->find(array("id" => $wid));

    $m->find(array("wid" => $wid, 'id' => $aid));

    $res = array();

    if ($m->has_id() && $m_pubs->has_id()) {

      $res[] = $m->get_model_array();

//      var_dump($res);

      $m->votetouser = json_decode($m->votetouser, TRUE);

      $articles = $m->votetouser[0];

      $m_article = new Model('website_article');

      $ress = $m_article->where(array('wid' => $wid, 'id' => $articles))->list_all_array();

      $res = array_merge($res, $ress);

    } else {

      $errarr = array();

      $errarr['errcode'] = 44003;

      $errarr['errmsg'] = self::$errorno[$errarr['errcode']];

      return $errarr;

    }

    $items = array();

    foreach ($res as $k => $v) {

      $mediaid = $this->uploadMedia($v['picurl']);

      if ($mediaid['media_id']) {

        $thumb_media_id = $mediaid['media_id'];

      } else {

        return $mediaid;

      }

      $item = array(

        "thumb_media_id" => $thumb_media_id,

        "author" => $m_pubs->pubun,

        "title" => $v['title'],

        "content_source_url" => WeiXinTool::complateUrl(WeiSite::parseArticleLinkData($v)),

        "content" => $v['reply_content'], //内容 富文本

        "digest" => $v['description']//描述

      );

      $items[] = $item;

    }

    //以上具体图文组装过程,需修改

 

    $postData['articles'] = $items;

    $error = $this->uploadNews($postData);

    return $error;

  }

 

  /**

   * 需修改

   * 微站文章关键字匹配数据解析

   */

  public static function getArticleData($keyword) {

    global $wid;

    $m = new Model('website_article');

    $m->find(array('wid' => $wid, 'keyword@~' => " " . $keyword . " "));

    $res = array();

    if ($m->has_id()) {

      $res[] = array("tit" => $m->title, "pic" => $m->picurl, "dec" => $m->description, "url" => WeiSite::parseArticleLinkData($m->get_model_array()));

      $m->votetouser = json_decode($m->votetouser, TRUE);

      $articles = $m->votetouser[0];

      if (!empty($articles)) {

        foreach ($articles as $v) {

          $m_article = new Model('website_article');

          $m_article->find(array('wid' => $wid, 'id' => $v));

          $res[] = array("tit" => $m_article->title, "pic" => $m_article->picurl, "dec" => $m_article->description, "url" => WeiSite::parseArticleLinkData($m_article->get_model_array()));

        }

      }

      return $res;

    }

  }

 

  /**

   * 获取accesstoken

   * @param type $flag 强制刷新accesstoken 开关

   * @return type

   */

  public function getAccessToken($flag = FALSE) {

    $url = sprintf(self::AUTH_URL, $this->appid, $this->appsecret);

    $result = Cache::get(md5($url));

    if ($flag || empty($result)) {

      $result = $this->http_get($url);

      $result = json_decode($result, TRUE);

      if ($result['errcode']) {

        return $result['errcode'];

      }

      Cache::set(md5($url), $result, 1);

    }

    $this->access_token = $result['access_token'];

    return true;

  }

 

  /**

   * 上传媒体

   * @param type $file 媒体文件 $url或者物理路径地址

   * @param type $type 类型

   * @return int

   * return

   array (size=3)

   'type' => string 'image' (length=5)

   'media_id' => string '-0Lr3rX9mDYBB7i5bDydvwFHHm3zW2Uxt0OoDFBPmGRfYiwckiALqHH_DlP9jCm_' (length=64)

   'created_at' => int 1400477181

   */

  public function uploadMedia($file, $type = "image") {

    $file = self::complateUrl($file);

    $urlarr = parse_url($file);

    $filetype = explode(".", $urlarr['path']);

    $filetype = strtolower($filetype[count($filetype) - 1]);

    $resizeSize = 100; //图片处理后另存质量

    if (!key_exists($type, $this->mediaType) || !in_array($filetype, $this->mediaType[$type])) {

//      return 40005; //格式错误

      $errarr = array();

      $errarr['errcode'] = 40005;

      $errarr['errmsg'] = self::$errorno[$errarr['errcode']];

      return $errarr;

    }

 

    $temp_file = $this->tem_file_path . 'uploadMedia.' . $filetype;

    $temp_file_resize = $this->tem_file_path . 'uploadMediaResize.' . $filetype;

    file_put_contents($temp_file, self::http_get($file));

    $handle = fopen($temp_file, "r");

    $fstat = fstat($handle);

 

    if ($fstat['size'] > $this->mediaMaxSize[$type]) {

      $resizeSize = intval($this->mediaMaxSize[$type] / $fstat['size'] * 100);

      ImageTool::resizeImage($temp_file_resize, $temp_file, 400, 400, $resizeSize); //图片太大再处理压缩

      $temp_file = $temp_file_resize;

//      return 40006; //大小错误

    }

    $filePath = realpath($temp_file);

    $uploadUrl = sprintf(self::UPLOAD_MEDIA_URL, $this->access_token, $type);

    $postData = array("r" => time(), 'media' => "@{$filePath}");

    $result = self::http_post($uploadUrl, $postData);

    $result = json_decode($result, TRUE);

    return $result;

  }

 

  /**

   * 群发图文信息

   * @param type $touser 粉丝数组/粉丝组id

   * @param type $media_id

   * @return type

   */

  public function sendArticles($touser, $media_id) {

    $errarr = array();

    $postData = array();

    $postData['mpnews'] = array("media_id" => $media_id);

    $postData['msgtype'] = "mpnews";

    if (is_array($touser)) {

      //用户列表群发

      $postData['touser'] = $touser;

      $url = 'https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=%s';

    } else {

      $group = intval($touser);

      $groups = $this->getGroups(true);

      if (key_exists($group, $groups['list'])) {

        $postData['filter'] = array("group_id" => $group);

      } else {

        $errarr['errcode'] = 40050; //无效分组id

        $errarr['errmsg'] = self::$errorno[$errarr['errcode']];

        return $errarr;

      }

      $url = 'https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=%s';

    }

    $url = sprintf($url, $this->access_token);

    $result = self::http_post($url, self::json_encode($postData));

    $result = json_decode($result, TRUE);

    return $result;

  }

 

  /**

   * 删除群发信息

   * @param type $msgid

   * @return type

   */

  public function delSend($msgid) {

    $url = 'https://api.weixin.qq.com/cgi-bin/message/mass/delete?access_token=%s';

    $url = sprintf($url, $this->access_token);

    $postData = array('msgid' => $msgid, 'r' => time());

    $result = self::http_post($url, self::json_encode($postData));

    $result = json_decode($result, TRUE);

    return $result;

  }

 

  /**

   * 群发图文素材上传

   $postData = array('articles' => array($item, $item,...));

   $item = array(

   "thumb_media_id" => "WMQubqCECMQwAjqh8CI500LfhyoG0vmTTlKKJM5oP-of0uLML1_2s26j8XeIorDL",

   "author" => "xxx",

   "title" => "Happy Day",

   "content_source_url" => "www.qq.com",

   "content" => "content",

   "digest" => "digest"

   );

   * return

   array (size=3)

   'type' => string 'news' (length=4)

   'media_id' => string 'OuXqv2dgZzxAmK4z-tvStgr6InG18oIllWkD6Tj1qJZVRg-2f64FDU2D3J7dptHs' (length=64)

   'created_at' => int 1400477183

   */

  public function uploadNews($postData) {

    $uploadUrl = sprintf(self::UPLOAD_NEWS_URL, $this->access_token);

    $result = self::http_post($uploadUrl, self::json_encode($postData));

    $result = json_decode($result, TRUE);

    return $result;

  }

 

  /**

   * 获取粉丝列表

   * @param type $nextOpenId

   * @return type

   */

  public function getAllConnects($nextOpenId = "") {

    $url = 'https://api.weixin.qq.com/cgi-bin/user/get?access_token=%s&next_openid=%s';

    $url = sprintf($url, $this->access_token, $nextOpenId);

    $result = self::http_get($url);

    $result = json_decode($result, TRUE);

    $count = count($result['data']['openid']);

    $list = $result['data']['openid'];

    if ($result['data']['openid'][$count - 1] == $result['next_openid']) {

      return $result['data']['openid'];

    } else {

      $templist = $this->getAllConnects($result['next_openid']);

      $list = array_merge($list, $templist);

      return $list;

    }

  }

 

  /**

   * 根据粉丝唯一id获取微信信息

   * @param type $openid

   * @return type

   */

  public function getFansInfo($openid) {

    $url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s&lang=zh_CN';

    $url = sprintf($url, $this->access_token, $openid);

    $result = self::http_get($url);

    $result = json_decode($result, TRUE);

    return $result;

  }

 

  /**

   * 更新粉丝组信息

   * @param type $openid

   * @param type $groupid

   * @return type

   */

  public function updateFansGroups($openid, $groupid) {

    $url = 'https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token=%s';

    $url = sprintf($url, $this->access_token);

    $postData = array("to_groupid" => $groupid, 'openid' => $openid);

    $result = self::http_post($url, self::json_encode($postData));

    $result = json_decode($result, TRUE);

    $this->getGroups(true);

    return $result;

  }

 

  /**

   * 获取粉丝组信息

   * @param type $openid

   * @return type

   */

  public function getFansGroupInfo($openid) {

    $url = 'https://api.weixin.qq.com/cgi-bin/groups/getid?access_token=%s';

    $url = sprintf($url, $this->access_token);

    $postData = array("r" => time(), 'openid' => $openid);

    $result = self::http_post($url, self::json_encode($postData));

    $result = json_decode($result, TRUE);

    return $result['groupid'];

  }

 

  /**

   * 获取唯一key

   * @param type $key

   * @return type

   */

  public function getKey($key) {

    return md5($this->appid . $this->appsecret . $key);

  }

 

  /**

   * 获取媒体图片到本地

   * @param type $mediaid

   * @return string

   */

  public function getMedia($mediaid) {

    $url = sprintf(self::GET_MEDIA_URL, $this->access_token, $mediaid);

    $result = self::http_get($url);

    $temp_file = $this->tem_file_path . 'getMedia.jpg';

    file_put_contents($temp_file, $result);

    return $temp_file;

  }

 

  /**

   * 用户组

   * @param type $flag 强制刷新用户组

   * @return type

   */

  public function getGroups($flag = false) {

    $key = $this->appid . 'gasdfev' . $this->appsecret;

    $result = Cache::get($key);

    if (empty($result) || $flag) {

      $url = 'https://api.weixin.qq.com/cgi-bin/groups/get?access_token=%s';

      $url = sprintf($url, $this->access_token);

      $result = self::http_get($url);

      $result = json_decode($result, TRUE);

      $temg = array();

      $temlist = array();

      foreach ($result['groups'] as $k => $v) {

        $temg[$v['id']] = $v;

        $temlist[$v['id']] = $v['name'];

      }

      $result['map'] = $temg;

      $result['list'] = $temlist;

      Cache::set($key, $result);

    }

    return $result;

  }

 

  /**

   * 新增用户组

   * @param type $name

   * @return type

   */

  public function createGroup($name) {

    $url = 'https://api.weixin.qq.com/cgi-bin/groups/create?access_token=%s';

    $url = sprintf($url, $this->access_token);

    $result = self::http_post($url, self::json_encode(array('group' => array('name' => $name))));

    $result = json_decode($result, TRUE);

    return $result;

  }

 

  /**

   * 修改用户组

   * @param type $id

   * @param type $name

   * @return type

   */

  public function modifyGroup($id, $name) {

    $url = 'https://api.weixin.qq.com/cgi-bin/groups/update?access_token=%s';

    $url = sprintf($url, $this->access_token);

    $result = self::http_post($url, self::json_encode(array('group' => array('id' => $id, 'name' => $name))));

    $result = json_decode($result, TRUE);

    return $result;

  }

 

  /**

   * 多客服接入

   * @global type $wid

   * @param type $postObj

   */

  public static function responseService($postObj) {

    global $wid;

    $fromUsername = $postObj->FromUserName;

    $toUsername = $postObj->ToUserName;

    $textTpl = "<xml>

<ToUserName><![CDATA[%s]]></ToUserName>

<FromUserName><![CDATA[%s]]></FromUserName>

<CreateTime>%s</CreateTime>

<MsgType><![CDATA[transfer_customer_service]]></MsgType>

</xml>";

    $resstr = sprintf($textTpl, $fromUsername, $toUsername, time());

    echo $resstr;

  }

 

  /**

   * 微信回复多图文

   * @global type $wid

   * @param type $res

   * array(array(),array()

   * );

   * @param type $rid

   * @param type $postObj

   */

  public static function response_morearts($res, $postObj) {

    global $wid;

    $fromUsername = $postObj->FromUserName;

    $toUsername = $postObj->ToUserName;

    $textTpl = "<xml>

 <ToUserName><![CDATA[%s]]></ToUserName>

 <FromUserName><![CDATA[%s]]></FromUserName>

 <CreateTime>%s</CreateTime>

 <MsgType><![CDATA[%s]]></MsgType>

 <ArticleCount>%s</ArticleCount>

 <Articles>

 ITEM

 </Articles>

 </xml>";

    $resstr = sprintf($textTpl, $fromUsername, $toUsername, time(), "news", count($res));

    $item = '';

    $subitem = "<item>

 <Title><![CDATA[%s]]></Title>

 <Description><![CDATA[%s]]></Description>

 <PicUrl><![CDATA[%s]]></PicUrl>

 <Url><![CDATA[%s]]></Url>

 </item>";

    foreach ($res as $r) {

      $r['url'] = self::parseUrl($r['url']);

      $item .= sprintf($subitem, $r['tit'], $r['des'], self::complateUrl($r['pic']), self::replaceToWXUrl(self::complateUrl($r['url']), $postObj));

    }

    $resstr = str_replace('ITEM', $item, $resstr);

    echo $resstr;

  }

 

  /**

   * url解析

   * @param type $url

   * @return string

   */

  public static function complateUrl($url) {

    if (false === stristr($url, "http://")) {//查找http:// 如果不存在

      if (0 === strpos($url, '/')) {//查找首字母 如果存在

        $url = substr($url, 1); //去除/

      }

      $url = "http://" . $_SERVER['HTTP_HOST'] . '/' . $url; //拼接完整路径

    }

    return $url;

  }

 

  /**

   * 微信url固定参数替换

   * @param type $url

   * @param type $postObj

   * @return type

   */

  public static function replaceToWXUrl($url, $postObj) {

    global $wechatid;

    return str_ireplace('fromUsername', $wechatid, $url);

  }

 

  /**

   * 完成以下行为

   * parseUrlParam

   * setUrlPublicParam

   * buildUrlParam

   * @param type $url

   * @param type $other 附加参数 基础参数wid wxid wechatid

   */

  public static function parseUrl($url, $other = array()) {

    $url = self::parseUrlParam($url);

    $url = self::setUrlPublicParam($url);

    if (is_array($other) && !empty($other)) {

      $url['param'] = array_merge($url['param'], $other);

    }

    $url = self::buildUrlParam($url);

    return $url;

  }

 

  /**

   * 分析url

   * @param type $url

   * @return type

   */

  public static function parseUrlParam($url) {

    $temp = explode("?", $url);

    $url0 = $temp[0];

    $url1 = $temp[1];

    $p = explode("&", $url1);

    $param = array();

    foreach ($p as $v) {

      $tempp = explode("=", $v);

      $param[$tempp[0]] = $tempp[1];

    }

    return array("url" => $url0, "param" => $param);

  }

 

  /**

   * 组装url

   * @param type $arr

   * @return type

   */

  public static function buildUrlParam($arr) {

    $url = $arr['url'];

    $param = $arr['param'];

    $param_arr = array();

    foreach ($param as $k => $v) {

      if ($k == "") continue;

      $param_arr[] = $k . "=" . $v;

    }

    return $url . "?" . implode("&", $param_arr) . "#mp.weixin.qq.com";

  }

 

  /**

   * 设置微信保留参数信息

   * @global type $uid

   * @global type $wid

   * @global type $wechatid

   * @param type $url

   * @return type

   */

  public static function setUrlPublicParam($url) {

    global $uid, $wid, $wechatid;

    $url['param']['wid'] = $wid;

    $url['param']['wxid'] = $wechatid;

    $url['param']['wechatid'] = $wechatid;

    return $url;

  }

 

  public static $errorno = array(

    '-1' => '系统繁忙',

    '0' => '请求成功',

    '40001' => '获取access_token时AppSecret错误,或者access_token无效',

    '40002' => '不合法的凭证类型',

    '40003' => '不合法的OpenID',

    '40004' => '不合法的媒体文件类型',

    '40005' => '不合法的文件类型',

    '40006' => '不合法的文件大小',

    '40007' => '不合法的媒体文件id',

    '40008' => '不合法的消息类型',

    '40009' => '不合法的图片文件大小',

    '40010' => '不合法的语音文件大小',

    '40011' => '不合法的视频文件大小',

    '40012' => '不合法的缩略图文件大小',

    '40013' => '不合法的APPID',

    '40014' => '不合法的access_token',

    '40015' => '不合法的菜单类型',

    '40016' => '不合法的按钮个数',

    '40017' => '不合法的按钮个数',

    '40018' => '不合法的按钮名字长度',

    '40019' => '不合法的按钮KEY长度',

    '40020' => '不合法的按钮URL长度',

    '40021' => '不合法的菜单版本号',

    '40022' => '不合法的子菜单级数',

    '40023' => '不合法的子菜单按钮个数',

    '40024' => '不合法的子菜单按钮类型',

    '40025' => '不合法的子菜单按钮名字长度',

    '40026' => '不合法的子菜单按钮KEY长度',

    '40027' => '不合法的子菜单按钮URL长度',

    '40028' => '不合法的自定义菜单使用用户',

    '40029' => '不合法的oauth_code',

    '40030' => '不合法的refresh_token',

    '40031' => '不合法的openid列表',

    '40032' => '不合法的openid列表长度',

    '40033' => '不合法的请求字符,不能包含\uxxxx格式的字符',

    '40035' => '不合法的参数',

    '40038' => '不合法的请求格式',

    '40039' => '不合法的URL长度',

    '40050' => '不合法的分组id',

    '40051' => '分组名字不合法',

    '40059' => '不合法的消息id',

    '41001' => '缺少access_token参数',

    '41002' => '缺少appid参数',

    '41003' => '缺少refresh_token参数',

    '41004' => '缺少secret参数',

    '41005' => '缺少多媒体文件数据',

    '41006' => '缺少media_id参数',

    '41007' => '缺少子菜单数据',

    '41008' => '缺少oauth code',

    '41009' => '缺少openid',

    '42001' => 'access_token超时',

    '42002' => 'refresh_token超时',

    '42003' => 'oauth_code超时',

    '43001' => '需要GET请求',

    '43002' => '需要POST请求',

    '43003' => '需要HTTPS请求',

    '43004' => '需要接收者关注',

    '43005' => '需要好友关系',

    '44001' => '多媒体文件为空',

    '44002' => 'POST的数据包为空',

    '44003' => '图文消息内容为空',

    '44004' => '文本消息内容为空',

    '45001' => '多媒体文件大小超过限制',

    '45002' => '消息内容超过限制',

    '45003' => '标题字段超过限制',

    '45004' => '描述字段超过限制',

    '45005' => '链接字段超过限制',

    '45006' => '图片链接字段超过限制',

    '45007' => '语音播放时间超过限制',

    '45008' => '图文消息超过限制',

    '45009' => '接口调用超过限制',

    '45010' => '创建菜单个数超过限制',

    '45015' => '回复时间超过限制',

    '45016' => '系统分组,不允许修改',

    '45017' => '分组名字过长',

    '45018' => '分组数量超过上限',

    '46001' => '不存在媒体数据',

    '46002' => '不存在的菜单版本',

    '46003' => '不存在的菜单数据',

    '46004' => '不存在的用户',

    '47001' => '解析JSON/XML内容错误',

    '48001' => 'api功能未授权',

    '50001' => '用户未授权该api'

  );

 

  /**

   * GET 请求

   * @param string $url

   */

  public static function http_get($url) {

    if (!function_exists('curl_init')) {

      die('curl 未开启');

    };

    $oCurl = curl_init();

    if (stripos($url, "https://") !== FALSE) {

      curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);

      curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);

    }

    curl_setopt($oCurl, CURLOPT_URL, $url);

    curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);

    $sContent = curl_exec($oCurl);

    $aStatus = curl_getinfo($oCurl);

    curl_close($oCurl);

    if (intval($aStatus["http_code"]) == 200) {

      return $sContent;

    } else {

      return false;

    }

  }

 

  /**

   * POST 请求

   * @param string $url

   * @param array $param

   * @return string content

   */

  public static function http_post($url, $param, $httpBuildQuery = false) {

    if (!function_exists('curl_init')) {

      die('curl 未开启');

    };

    $oCurl = curl_init();

    if (stripos($url, "https://") !== FALSE) {

      curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);

      curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);

    }

    curl_setopt($oCurl, CURLOPT_URL, $url);

    curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);

//    curl_setopt($oCurl, CURLOPT_HTTPHEADER, $header);//设置HTTP头

    curl_setopt($oCurl, CURLOPT_POST, 1);

    if ($httpBuildQuery) {

      $param = http_build_query($param);

    }

    curl_setopt($oCurl, CURLOPT_POSTFIELDS, $param);

    $sContent = curl_exec($oCurl);

    $aStatus = curl_getinfo($oCurl);

    curl_close($oCurl);

    if (intval($aStatus["http_code"]) == 200) {

      return $sContent;

    } else {

      return false;

    }

  }

 

  /**

   * 微信api不支持中文转义的json结构

   * @param array $arr

   */

  static function json_encode($arr) {

    $parts = array();

    $is_list = false;

    //Find out if the given array is a numerical array

    $keys = array_keys($arr);

    $max_length = count($arr) - 1;

    if (($keys [0] === 0) && ($keys [$max_length] === $max_length )) { //See if the first key is 0 and last key is length - 1

      $is_list = true;

      for ($i = 0; $i < count($keys); $i ++) { //See if each key correspondes to its position

        if ($i != $keys [$i]) { //A key fails at position check.

          $is_list = false; //It is an associative array.

          break;

        }

      }

    }

    foreach ($arr as $key => $value) {

      if (is_array($value)) { //Custom handling for arrays

        if ($is_list) $parts [] = self::json_encode($value); /* :RECURSION: */

        else $parts [] = '"' . $key . '":' . self::json_encode($value); /* :RECURSION: */

      } else {

        $str = '';

        if (!$is_list) $str = '"' . $key . '":';

        //Custom handling for multiple data types

        if (is_numeric($value) && $value < 2000000000) $str .= $value; //Numbers

        elseif ($value === false) $str .= 'false'; //The booleans

        elseif ($value === true) $str .= 'true';

        else $str .= '"' . addslashes($value) . '"';

//All other things

// :TODO: Is there any more datatype we should be in the lookout for? (Object?)

        $parts [] = $str;

      }

    }

    $json = implode(',', $parts);

    if ($is_list) return '[' . $json . ']'; //Return numerical JSON

    return '{' . $json . '}'; //Return associative JSON

  }

 

}

Copy after login

The above is the entire content of this article. I hope it will be helpful to everyone in learning PHP programming.

The above has introduced how to send mass messages on WeChat, php WeChat advanced interface mass messages and multiple customer service, including how to send mass messages on WeChat. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1252
29
C# Tutorial
1226
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

What is REST API design principles? What is REST API design principles? Apr 04, 2025 am 12:01 AM

RESTAPI design principles include resource definition, URI design, HTTP method usage, status code usage, version control, and HATEOAS. 1. Resources should be represented by nouns and maintained at a hierarchy. 2. HTTP methods should conform to their semantics, such as GET is used to obtain resources. 3. The status code should be used correctly, such as 404 means that the resource does not exist. 4. Version control can be implemented through URI or header. 5. HATEOAS boots client operations through links in response.

How do you handle exceptions effectively in PHP (try, catch, finally, throw)? How do you handle exceptions effectively in PHP (try, catch, finally, throw)? Apr 05, 2025 am 12:03 AM

In PHP, exception handling is achieved through the try, catch, finally, and throw keywords. 1) The try block surrounds the code that may throw exceptions; 2) The catch block handles exceptions; 3) Finally block ensures that the code is always executed; 4) throw is used to manually throw exceptions. These mechanisms help improve the robustness and maintainability of your code.

What are anonymous classes in PHP and when might you use them? What are anonymous classes in PHP and when might you use them? Apr 04, 2025 am 12:02 AM

The main function of anonymous classes in PHP is to create one-time objects. 1. Anonymous classes allow classes without names to be directly defined in the code, which is suitable for temporary requirements. 2. They can inherit classes or implement interfaces to increase flexibility. 3. Pay attention to performance and code readability when using it, and avoid repeatedly defining the same anonymous classes.

What is the difference between include, require, include_once, require_once? What is the difference between include, require, include_once, require_once? Apr 05, 2025 am 12:07 AM

In PHP, the difference between include, require, include_once, require_once is: 1) include generates a warning and continues to execute, 2) require generates a fatal error and stops execution, 3) include_once and require_once prevent repeated inclusions. The choice of these functions depends on the importance of the file and whether it is necessary to prevent duplicate inclusion. Rational use can improve the readability and maintainability of the code.

Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Apr 08, 2025 am 12:03 AM

There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

See all articles