PHP version WeChat public platform red envelope API, php public red envelope api

Source: Internet
Author: User
Tags oauth openid

PHP public platform red envelope API, php public red envelope api

I have rewritten the API interfaces in PHP,

Support for red packets and support for dynamic parameter interfaces of JSAPI

Http://git.oschina.net/youkuiyuan/yky_test/blob/master/class/wxapi.class.php

API-added support for Red Packets

<? Php /************************************** * ****************** @ author Kyler You <QQ: 2444756311> * @ link http://mp.weixin.qq.com/wiki/home/index.html * @ version 2.0.1 * @ uses $ wxApi = new WxApi (); * @ package the API interface will be updated one after another ****************************** * ***********************/class WxApi {const appId = ""; const appSecret = ""; const mchid = ""; // merchant ID const privatekey = ""; // Private Key public $ para Meters = array (); public function _ construct () {}/************************************* ***************** submit the API method, returns the specified JSON ************************************* * *************/public function wxHttpsRequest ($ url, $ data = null) {$ curl = curl_init (); curl_setopt ($ curl, CURLOPT_URL, $ url); curl_setopt ($ curl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt ($ curl, CURLOPT_SSL_VERIFYHOST, FALSE); if (! Empty ($ data) {curl_setopt ($ curl, CURLOPT_POST, 1); curl_setopt ($ curl, CURLOPT_POSTFIELDS, $ data);} curl_setopt ($ curl, expires, 1 ); $ output = curl_exec ($ curl); curl_close ($ curl); return $ output ;} /*************************************** ******************** * *****************************/public function wxHttpsRequestPem ($ url, $ vars, $ second = 30, $ aHea Der = array () {$ ch = curl_init (); // timeout curl_setopt ($ ch, CURLOPT_TIMEOUT, $ second); curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 ); // set the proxy here. If so, // curl_setopt ($ ch, CURLOPT_PROXY, '10. 206.30.98 '); // curl_setopt ($ ch, CURLOPT_PROXYPORT, 8080); curl_setopt ($ ch, CURLOPT_URL, $ url); curl_setopt ($ ch, CURLOPT_SSL_VERIFYPEER, false ); curl_setopt ($ ch, CURLOPT_SSL_VERIFYHOST, false); // select one of the following two methods // The first method, cert and key are respectively In two. pem file // The default format is PEM. you can comment curl_setopt ($ ch, CURLOPT_SSLCERTTYPE, 'pem'); curl_setopt ($ ch, CURLOPT_SSLCERT, getcwd (). '/apiclient_cert.pem'); // The default format is PEM. you can comment curl_setopt ($ ch, CURLOPT_SSLKEYTYPE, 'pem'); curl_setopt ($ ch, CURLOPT_SSLKEY, getcwd (). '/apiclient_key.pem'); curl_setopt ($ ch, CURLOPT_CAINFO, 'pem'); curl_setopt ($ ch, CURLOPT_CAINFO, getcwd (). '/rootca. pem '); // Method 2: merge two files into one. pem file // curl_setopt ($ ch, CURLOPT _ SSLCERT, getcwd (). '/all. pem'); if (count ($ aHeader)> = 1) {curl_setopt ($ ch, CURLOPT_HTTPHEADER, $ aHeader);} curl_setopt ($ ch, CURLOPT_POST, 1 ); curl_setopt ($ ch, CURLOPT_POSTFIELDS, $ vars); $ data = curl_exec ($ ch); if ($ data) {curl_close ($ ch); return $ data ;} else {$ error = curl_errno ($ ch); echo "call faild, errorCode: $ error \ n"; curl_close ($ ch); return false ;}} /************************************** * ************* Obtain the AccessToken and return the at information of the specified public account **************** * *********************************/public function wxAccessToken ($ appId = NULL, $ appSecret = NULL) {$ appId = is_null ($ appId )? Self: appId: $ appId; $ appSecret = is_null ($ appSecret )? Self: appSecret: $ appSecret; // echo $ appId, $ appSecret; $ url = "https://api.weixin.qq.com/cgi-bin/token? Grant_type = client_credential & appid = ". $ appId. "& secret = ". $ appSecret; $ result = $ this-> wxHttpsRequest ($ url); // print_r ($ result); $ jsoninfo = json_decode ($ result, true ); $ access_token = $ jsoninfo ["access_token"]; return $ access_token ;} /*************************************** * ************* use OPENID to obtain user information, returns an array ************************************** * *************/public function wxGetUser ($ openId) {$ w XAccessToken = $ this-> wxAccessToken (); $ url = "https://api.weixin.qq.com/cgi-bin/user/info? Access_token = ". $ wxAccessToken. "& openid = ". $ openId. "& lang = zh_CN"; $ result = $ this-> wxHttpsRequest ($ url); $ jsoninfo = json_decode ($ result, true); return $ jsoninfo ;} /*************************************** * ************** send the specified template information to the specified user, after sending the data, return the specified JSON data ********************************* * *****************/public function wxSendTemplate ($ jsonData) {$ wxAccessToken = $ this-> wxAccessToken (); $ url = "http S: // api.weixin.qq.com/cgi-bin/message/template/send? Access_token = ". $ wxAccessToken; $ result = $ this-> wxHttpsRequest ($ url, $ jsonData); return $ result ;} /*************************************** ******************** * *****************************/public function wxSetSend ($ touser, $ template_id, $ url, $ data, $ topcolor = '# 7B68EE') {$ template = array ('touser' => $ touser, 'template _ id' => $ template_id, 'url' => $ url, 'topcolor' ==>$ Topcolor, 'data' =>$ data); $ jsonData = json_encode ($ template); $ result = $ this-> wxSendTemplate ($ jsonData ); return $ result ;} /*************************************** * ************* set the OAUTH jump URL, returns string information-SCOPE = snsapi_base // The confirmation page is not returned during verification, only the OPENID ************************************* * *************/public function wxOauthBase ($ redirectUrl, $ state = "", $ appId = NULL) {$ appId = is_null ($ appI D )? Self: appId: $ appId; $ url = "https://open.weixin.qq.com/connect/oauth2/authorize? Appid = ". $ appId. "& redirect_uri = ". $ redirectUrl. "& response_type = code & scope = snsapi_base & state = ". $ state. "# wechat_redirect"; return $ url ;} /*************************************** * ************* set the OAUTH jump URL, returns the string information-SCOPE = snsapi_userinfo // obtain the complete user information *************************** * **********************/public function wxOauthUserinfo ($ redirectUrl, $ state = "", $ appId = NULL) {$ appId = is_null ($ appId )? Self: appId: $ appId; $ url = "https://open.weixin.qq.com/connect/oauth2/authorize? Appid = ". $ appId. "& redirect_uri = ". $ redirectUrl. "& response_type = code & scope = snsapi_userinfo & state = ". $ state. "# wechat_redirect"; return $ url ;} /*************************************** ********************** * ****************************/public function wxHeader ($ url) {header ("location :". $ url );} /*************************************** * ************ get AT information through the OAUTH return page ***** **************************************** * *****/Public function wxOauthAccessToken ($ code, $ appId = NULL, $ appSecret = NULL) {$ appId = is_null ($ appId )? Self: appId: $ appId; $ appSecret = is_null ($ appSecret )? Self: appSecret: $ appSecret; $ url = "https://api.weixin.qq.com/sns/oauth2/access_token? Appid = ". $ appId. "& secret = ". $ appSecret. "& code = ". $ code. "& grant_type = authorization_code"; $ result = $ this-> wxHttpsRequest ($ url); // print_r ($ result); $ jsoninfo = json_decode ($ result, true ); // $ access_token = $ jsoninfo ["access_token"]; return $ jsoninfo ;} /*************************************** * ************ get the current user information through the OAUTH Access_Token information. // only run in snsapi_userinfo mode ******** **************************** * *************/Public function wxOauthUser ($ OauthAT, $ openId) {$ url = "https://api.weixin.qq.com/sns/userinfo? Access_token = ". $ OauthAT. "& openid = ". $ openId. "& lang = zh_CN"; $ result = $ this-> wxHttpsRequest ($ url); $ jsoninfo = json_decode ($ result, true); return $ jsoninfo ;} /*************************************** * ************* generate a random string-a string of up to 32 characters **************** * ***********************************/public function wxNonceStr ($ length = 16, $ type = FALSE) {$ chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQR STUVWXYZ0123456789 "; $ str =" "; for ($ I = 0; $ I <$ length; $ I ++) {$ str. = substr ($ chars, mt_rand (0, strlen ($ chars)-1), 1);} if ($ type = TRUE) {return strtoupper (md5 (time (). $ str);} else {return $ str ;}} /*************************************** **************** Merchant Order Number-a maximum of 28 character strings **************** ***************************************/ public function wxMchBillno ($ mchid = NULL) {if (is_null ($ Mchid) {if (self: mchid = "" | is_null (self: mchid) {$ mchid = time ();} else {$ mchid = self: mchid ;}} else {$ mchid = substr (addslashes ($ mchid),);} return date ("Ymd ", time ()). time (). $ mchid ;} /*************************************** * *************** format the array into a parameter format-supports url encryption ************** **************************************** */public function wxSetParam ($ parameters) {if (is_array ($ parame Ters )&&! Empty ($ parameters) {$ this-> parameters = $ parameters; return $ this-> parameters;} else {return array ();}} /*************************************** * *************** format the array into a parameter format-supports url encryption ************** **************************************** */public function wxFormatArray ($ parameters = NULL, $ urlencode = FALSE) {if (is_null ($ parameters) {$ parameters = $ this-> parameters;} $ restr = ""; // Initialize an empty ksor T ($ parameters); // The sorting parameter foreach ($ parameters as $ k => $ v) {// The parameter if (null! = $ V & "null "! = $ V & "sign "! = $ K) {if ($ urlencode) {// Add URL encryption if the parameter is required. $ v = urlencode ($ v) is not required if no URL encryption is required.} $ restr. = $ k. "= ". $ v. "&"; // returns the complete string} if (strlen ($ restr)> 0) {// If data exists, the last "&" will be deleted $ restr = substr ($ restr, 0, strlen ($ restr)-1);} return $ restr; // return string }/********************************** * ******************* MD5 Signature generator-the parameter array needs to be converted into a string [wxFormatArray method] **** **************************************** * ***********/public func Tion wxMd5Sign ($ content, $ privatekey) {try {if (is_null ($ key) {throw new Exception ("caifutong signature key cannot be blank! ");} If (is_null ($ content) {throw new Exception (" caifu signature content cannot be blank ");} $ signStr = $ content. "& key = ". $ key; return strtoupper (md5 ($ signStr);} catch (Exception $ e) {die ($ e-> getMessage ());}} /*************************************** * *************** Sha1 signature generator-the parameter array needs to be converted into a string [wxFormatArray method] ********* **************************************** * *****/public function wxSha1Sign ($ content, $ privatekey) {Try {if (is_null ($ key) {throw new Exception ("The caifu signature key cannot be blank! ");} If (is_null ($ content) {throw new Exception (" caifu signature content cannot be blank ");} $ signStr = $ content. "& key = ". $ key; return strtoupper (sha1 ($ signStr);} catch (Exception $ e) {die ($ e-> getMessage ());}} /*************************************** **************** parse the array into XML-red envelope interface **************** ***************************************/ public function wxArrayToXml ($ parameters = NULL) {if (is_null ($ parameters )){ $ Parameters = $ this-> parameters;} if (! Is_array ($ parameters) | empty ($ parameters) {die ("the parameter is not an array and cannot be parsed");} $ xml = "<xml> "; foreach ($ arr as $ key => $ val) {if (is_numeric ($ val) {$ xml. = "<". $ key. "> ". $ val. "</". $ key. ">";} else $ xml. = "<". $ key. "> <! [CDATA [". $ val. "]> </". $ key. ">" ;}$ xml. = "</xml>"; return $ xml ;}}

This CLASS will be added together in the future. There are a lot of resources on the Internet, but there is a certain foundation for people to look at it and change it, support is still required for new users who are not new to Alibaba Cloud. It helps users to develop their own ideas.

The above is all the content of this article. I hope you will like it.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.