How to use PHP to develop the menu management function of public accounts
With the popularity of WeChat public accounts, many companies choose to use public accounts for publicity and promotion. The menu management function of public accounts is very important for improving user experience and increasing interactivity. In this article, I will introduce how to use PHP to develop the menu management function of the official account and provide specific code examples.
$appid = 'your_app_id'; // 替换为你的AppId $appsecret = 'your_app_secret'; // 替换为你的AppSecret $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($ch); curl_close($ch); $result = json_decode($output, true); $access_token = $result['access_token'];
$menu = array( 'button' => array( array( 'type' => 'click', 'name' => '菜单1', 'key' => 'menu1', ), array( 'type' => 'view', 'name' => '菜单2', 'url' => 'http://www.example.com/menu2', ), array( 'name' => '菜单3', 'sub_button' => array( array( 'type' => 'click', 'name' => '子菜单1', 'key' => 'sub_menu1', ), array( 'type' => 'view', 'name' => '子菜单2', 'url' => 'http://www.example.com/sub_menu2', ), ), ), ), ); $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=$access_token"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($menu, JSON_UNESCAPED_UNICODE)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($ch); curl_close($ch); $result = json_decode($output, true); if ($result['errcode'] == 0) { echo '菜单创建成功!'; } else { echo '菜单创建失败:' . $result['errmsg']; }
The above code example defines a menu array containing multiple menu items. The menu array is converted into JSON by calling the interface provided by the WeChat public platform. format and send it to the WeChat public platform. If the menu is created successfully, theerrcode
field in the returned result will be 0, otherwise it will be an error message.
Summary:
This article introduces how to use PHP to develop the menu management function of public accounts and provides specific code examples. By obtaining the access_token and using it to create the menu, we can easily manage the menu of the official account and provide a better user experience. Hope this article is helpful to you!
The above is the detailed content of How to use PHP to develop the menu management function of public accounts. For more information, please follow other related articles on the PHP Chinese website!