Provides various official and user-released code examples and code reference. You are welcome to exchange and learn how to use the wechat class to teach you how to implement most common functions, including checking weather, bus routes, automatic robot reply... Remember to give me a thumbs up!
If you do not have a public number, you can use your own number to apply for a test number. The function is quite complete.
Namespace Home \ Controller;
Use Think \ Controller;
Class IndexController extends Controller {
Public function index (){
$ Options = array (
'Token' => 'ruanqin', // enter the token you set
'Appid '=> '123', // enter the appid of the Advanced Call function.
'Appsecret' => '000000' // enter the key of the Advanced Call function.
);
// These two classes have been added to the attachment and can be downloaded as needed
Vendor ('weixin. wechat ');
Vendor ('weixin. snoopy ');
$ WeObj = new \ Wechat ($ options );
$ WeObj-> valid (); // verify the key
// Obtain menu operations:
$ Menu = $ weObj-> getMenu ();
// Set the menu
$ Newmenu = array (
'Button '=> array (
0 => array (
'Name' => 'Scan Code ',
'Sub _ click' => array (
0 => array (
'Type' => 'scancode _ waitmsg ',
'Name' => 'Scan the QR code with the hint ',
'Key' => 'rselfmenu _ 0_0 ',
),
1 => array (
'Type' => 'scancode _ push ',
'Name' => 'Code scanning event ',
'Key' => 'rselfmenu _ 0_1 ',
),
),
),
1 => array (
'Name' => 'output ',
'Sub _ click' => array (
0 => array (
'Type' => 'pic _ sysphoto ',
'Name' => 'System photo and output ',
'Key' => 'rselfmenu _ defaults 0 ',
),
1 => array (
'Type' => 'pic _ photo_or_album ',
'Name' => 'photo taking or photo album output ',
'Key' => 'rselfmenu _ 1_1 ',
),
2 => array (
'Type' => 'view ',
'Name' => 'baidu ',
'Url' => 'HTTP: // www.baidu.com ',
'Key' => 'rselfmenu _ 1_2 ',
),
),
),
2 => array (
'Type' => 'location _ select ',
'Name' => 'sending location ',
'Key' => 'rselfmenu _ 2_0'
),
),
);
$ Result = $ weObj-> createMenu ($ newmenu );
// Obtain the types of messages sent by the user, including text, music, and image.
$ Type = $ weObj-> getRev ()-> getRevType ();
Switch ($ type ){
Case \ Wechat: MSGTYPE_TEXT:
// Obtain the text message content sent by the user
$ Content = $ weObj-> getRev ()-> getRevContent ();
// Start with the second word at the end of the message and intercept two words
$ Str = mb_substr ($ content,-, "UTF-8 ");
// Start with the beginning of the message and cut off the two words at the end to obtain the keyword.
$ Str_key = mb_substr ($ content, 0,-2, "UTF-8 ");
// Then judge whether it is a keyword or not. If it meets the requirements, call the function to query the translation data.
If ($ str = 'translation '&&! Empty ($ str_key )){
$ Url1 = "http://openapi.baidu.com/public/2.0/bmt/translate? Client_id = 9peNkh97N6B9GGj9zBke9tGQ & q ={$ str_key} & from = auto & to = auto "; // Baidu translation address
// Instantiate the collection class
$ Spy = new \ Snoopy;
// Obtain the collected data
$ Spy-> fetch ($ url1 );
// Assign the result to $ con_json
$ Con_json = $ spy-> results;
// Json parsing, converted to object type
$ Transon = json_decode ($ con_json );
// Read the translation content
$ Con_str = $ transon-> trans_result [0]-> dst;
// Output the result in text format
$ WeObj-> text ("{$ con_str}")-> reply ();
}
// Determines whether it is a keyword or not. If yes, call the function to query book data.
If ($ str = 'book '&&! Empty ($ str_key )){
$ Url = "http: // 222.206.65.12/opac/search_rss.php? Dept = ALL & title = {$ str_key} & doctype = ALL & lang_code = ALL & match_flag = forward & displaypg = 20 & showmode = list & orderby = DESC & sort = CATA_DATE & onlylendable = no ";
$ Spp = new \ Snoopy;
$ Spp-> fetch ($ url );
$ Fa = $ spp-> results;
// Convert the collected XML data to the object type
$ F = simplexml_load_string ($ fa );
$ Da1 = $ f-> channel-> item [0]-> title;
$ Da2 = $ f-> channel-> item [1]-> title;
$ Da3 = $ f-> channel-> item [2]-> title;
$ WeObj-> text ("{$ da1} \ n {$ da2} \ n {$ da3}")-> reply ();
}
// Determine the bus route
If ($ str = 'bus '&&! Empty ($ str_key )){
$ Strbus = explode (',', $ str_key );
$ Ch = curl_init ();
$ Url = "http://apis.baidu.com/apistore/bustransport/buslines? City = {$ strbus [0]} & busNo = {$ strbus [1]} ";
$ Header = array (
'Apikey: The apikey here is registered with Baidu APIstore for free! '
);
// Add the apikey to the header
Curl_setopt ($ ch, CURLOPT_HTTPHEADER, $ header );
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 );
// Execute the HTTP request
Curl_setopt ($ ch, CURLOPT_URL, $ url );
$ Res = curl_exec ($ ch );
$ B = json_decode ($ res );
$ A = $ B-> retData-> result;
$ C = simplexml_load_string ($ );
$ D = $ c-> lines-> line [1]-> stats;
$ Rq = explode (';', $ d );
$ Ww = implode ('->', $ rq );
$ WeObj-> text ("{$ ww}")-> reply ();
}
// Query scenic spots
If ($ str = 'scenic spots '&&! Empty ($ str_key )){
$ Ch = curl_init ();
$ Url = "http://apis.baidu.com/apistore/attractions/spot? Id = {$ str_key} & output = json ";
$ Header = array (
'Apikey:Same as above',
);
// Add the apikey to the header
Curl_setopt ($ ch, CURLOPT_HTTPHEADER, $ header );
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 );
// Execute the HTTP request
Curl_setopt ($ ch, CURLOPT_URL, $ url );
$ Res = curl_exec ($ ch );
$ A = json_decode ($ res );
$ Name = $ a-> result-> name;
$ Phone = $ a-> result-> telephone;
$ Abstract = $ a-> result-> abstract;
$ Description = $ a-> result-> description;
$ Price = $ a-> result-> ticket_info-> price;
$ Open_time = $ a-> result-> ticket_info-> open_time;
$ B = "attraction name: {$ name} \ n contact number: {$ phone} \ n price: {$ price} \ n opening time: {$ open_time} \ n Scenic Spot details: {$ abstract} {$ description }";
$ WeObj-> text ("{$ B}")-> reply ();
}
// A healthy information query is made here. It is very important for programmers to be healthy.
If ($ str = 'health '&&! Empty ($ str_key )){
$ Url = 'HTTP: // apis.baidu.com/yi18/lore/loreclass? Id = 1 ';
$ Header = array (
'Apikey :... Apply by yourself ..... ',
);
$ Thisres = $ this-> curl ($ url, $ header );
$ A = $ this-> curl ($ url, $ header );
$ Thisres = $ a-> yi18;
For ($ I = 0; $ I <13; $ I ++ ){
$ Q = $ thisres [$ I]-> id;
$ W = $ thisres [$ I]-> name;
$ Qq. = '';
$ Qq. = "No.: {$ q} -- Title: {$ w} \ n ";
}
$ WeObj-> text ("{$ qq} \ n Please select the serial number of the information you want to know, such as: 1 title")-> reply ();
}
If ($ str = 'title '&&! Empty ($ str_key )){
$ Ch = curl_init ();
$ Url = "http://apis.baidu.com/yi18/lore/list? Page = 1 & limit = 10 & type = id & id = {$ str_key }";
$ Header = array (
'Apikey: Same as above ',
);
Curl_setopt ($ ch, CURLOPT_HTTPHEADER, $ header );
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 );
// Execute the HTTP request
Curl_setopt ($ ch, CURLOPT_URL, $ url );
$ Res = curl_exec ($ ch );
$ B = json_decode ($ res );
$ Thisres2 = $ B-> yi18;
Foreach ($ thisres2 as $ key => $ value ){
$ Q = $ thisres2 [$ key]-> id;
$ W = $ thisres2 [$ key]-> title;
$ Qq. = '';
$ Qq. = "id: {$ q} -- info: {$ w} \ n ";
}
$ WeObj-> text ("{$ qq} \ n Please select the id of the information you want to know, such as: 18069 information")-> reply ();
}
If ($ str = 'info '&&! Empty ($ str_key )){
$ Url = "http://apis.baidu.com/yi18/lore/detail? Id = {$ str_key }";
$ Header = array (
'Apikey :',
);
$ A = $ this-> curl ($ url, $ header );
$ Thisres = $ a-> yi18;
$ Q = $ thisres-> message;
$ W = $ thisres-> title;
// $ Qq = 'title. $ w. Body. $ Q ';
$ Qq = "title: {$ w} \ n body: {$ q }";
$ Str = str_replace (""," ", $ Qq );
$ Ww = strip_tags ($ str );
$ WeObj-> text ("{$ ww}")-> reply ();
}
// Weather Query
If ($ str = 'Weather '&&! Empty ($ str_key )){
$ Url = "http://api.map.baidu.com/telematics/v2/weather? Location = {$ str_key} & ak = same as above ";
$ Sp = new \ Snoopy;
$ Sp-> fetch ($ url );
$ L_xml = $ sp-> results;
$ F = simplexml_load_string ($ l_xml );
$ City = $ f-> currentCity;
$ Da1 = $ f-> results-> result [0]-> date;
$ Da2 = $ f-> results-> result [1]-> date;
$ Da3 = $ f-> results-> result [2]-> date;
$ W1 = $ f-> results-> result [0]-> weather;
$ W2 = $ f-> results-> result [1]-> weather;
$ W3 = $ f-> results-> result [2]-> weather;
$ P1 = $ f-> results-> result [0]-> wind;
$ P2 = $ f-> results-> result [1]-> wind;
$ P3 = $ f-> results-> result [2]-> wind;
$ Q1 = $ f-> results-> result [0]-> temperature;
$ Q2 = $ f-> results-> result [1]-> temperature;
$ Q3 = $ f-> results-> result [2]-> temperature;
$ K1 = $ f-> results-> result [0]-> dayPictureUrl;
$ K2 = $ f-> results-> result [1]-> dayPictureUrl;
$ K3 = $ f-> results-> result [2]-> dayPictureUrl;
$ D1 = $ city. $ da1. $ w1. $ p1. $ q1;
$ D2 = $ city. $ da2. $ w2. $ p2. $ q2;
$ D3 = $ city. $ da3. $ w3. $ p3. $ q3;
$ WeObj-> text ("{$ d1} \ n {$ d2} \ n {$ d3}")-> reply ();
}
// Complete the remaining tasks by the robot !;
// Here I am using a Turing robot. My girlfriend and robot chat experiment show that paid robots are relatively smart and free, so local tyrants can choose to pay, charged by the number of items
Else {
$ Strurl = "http://www.tuling123.com/openapi/api? Key = Apply for a key by yourself & info = {$ content }";
$ Xhy = new \ Snoopy;
$ Xhy-> fetch ($ strurl );
$ X_json = $ xhy-> results;
$ Strjson = json_decode ($ x_json );
// $ A = var_dump ($ strjson );
$ ContentStr = $ strjson-> text;
// $ WeObj-> text ("{$ contentStr}")-> reply ();
$ WeObj-> text ("{$ contentStr}")-> reply ();
}
Break;
Case \ Wechat: MSGTYPE_LOCATION:
// Geographic location of the received message
$ Arr1 = $ weObj-> getRev ()-> getRevGeo ();
$ Snoopy = new \ Snoopy;
$ Url = "http://api.map.baidu.com/telematics/v2/distance? Waypoints = enter the longitude and latitude of your location; {$ arr1 ['X']}, {$ arr1 ['y']} & ak = same as above ";
$ Snoopy-> fetch ($ url );
$ Lines_string = $ snoopy-> results;
$ Fk = simplexml_load_string ($ lines_string );
$ Juli = $ fk-> results-> distance;
$ Contentstring = "You and I are between {$ juli} meters away ";
$ WeObj-> text ("{$ contentstring}")-> reply ();
Break;
// Accept the image reply text or reply to the image.
Case \ Wechat: MSGTYPE_IMAGE:
$ B = "";
$ A = rand (1, 3 );
Switch ($)
{Case 1;
$ B = "you are stupid, send such two pictures ";
Break;
Case 2;
$ B = "as ugly as you ";
Break;
Default;
$ B = "Ah, my God ";
}
$ WeObj-> text ("haha I know this is an image \ n: {$ B}")-> reply ();
// Exit;
Break;
// Implement the first-time follow-up reply function
Case \ Wechat: MSGTYPE_EVENT:
$ MsgEvent = $ weObj-> getRev ()-> getRevEvent ();
$ WeObj-> text ("Thank you for your attention to the public account \ n weather query: City + weather, for example, Guangzhou weather \ n Translation: Word + translation, for example, good translation \ n ranging: sending location \ n checking book: Title + book, such as php book \ n listening Song: reply music \ n checking bus route, such as Hangzhou, 151 bus \ n Health Knowledge: Any word + health, for example, health \ n scenic spots query: Scenic Spots name (Please use Pinyin) + for scenic spots such as xihu scenic spots \ n, you can also choose to send pictures and chat with others! \ N more content, please wait ...")
-> Reply ();
Break;
Default:
$ WeObj-> text ("query weather: City + weather, such as Guangzhou weather \ n Translation: Word + translation, such as good translation \ n ranging: sending location \ n query: title + book, such as php book \ n listen to songs: reply to music \ n can also choose to send pictures, thank you for your attention, more content, so stay tuned... ")-> reply ();
}
}
}
Weixin.zip (20.27 KB download: 203 times)
AD: truly free, domain name + VM + enterprise mailbox = 0 RMB