Home  >  Article  >  Backend Development  >  调用微信企业号接口发送通报信息的PHP代码

调用微信企业号接口发送通报信息的PHP代码

WBOY
WBOYOriginal
2016-06-13 12:18:151187browse

调用微信企业号接口发送通知信息的PHP代码

我在研究用PHP调用微信企业号接口发送通知信息时,遇到了一个问题,就是汉字编码的问题。在用POST提交的数据如果是用数组型时,要先用json_encode将数组型数据转成josn字串,但数据中如果有汉字就会出现问题:json_encode不能序列化GB2312编码的汉字,若是UTF-8编码的汉字在用json_encode转换后也成了无法识别的乱码,微信企业号的接口也无法接收这些乱码。该怎么办呢?经过反复研究、反复调试终于找出了两种方法:

第一种方法(数组型数据):

1、将页面代码转存成UTF-8编码;

2、用urlencode将汉字编码;

?

3、用json_encode将数组型数据转成josn字串

4、用urldecode将josn字串型数据解码;

5、再将解码后的josn字串型数据发送给微信企业号接口即可。

?

第二种方法(字串型数据):

1、将页面代码转存成UTF-8编码;

2、将要传递的POST数据用字串拼接的型连接起来;

3、再将拼接好的字串型数据发送给微信企业号接口即可。

?

为了代码简单,我用了第二种方法,代码如下:

?

<?phpfunction curlPost($url,$data=""){       $ch = curl_init();    $opt = array(			CURLOPT_URL     => $url,                        CURLOPT_HEADER  => 0,			CURLOPT_POST    => 1,            CURLOPT_POSTFIELDS      => $data,            CURLOPT_RETURNTRANSFER  => 1,            CURLOPT_TIMEOUT         => 20    );    $ssl = substr($url,0,8) == "https://" ? TRUE : FALSE;    if ($ssl){        $opt[CURLOPT_SSL_VERIFYHOST] = 1;        $opt[CURLOPT_SSL_VERIFYPEER] = FALSE;    }    curl_setopt_array($ch,$opt);    $data = curl_exec($ch);    curl_close($ch);    return $data;}$corpid="请修改为你企业号的corpid";$corpsecret="请修改为你企业号的corpsecret";$Url="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$corpid&corpsecret=$corpsecret";$res = curlPost($Url);$ACCESS_TOKEN=json_decode($res)->access_token;$Url="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=$ACCESS_TOKEN";$msg='要发送的文字信息';$data="{\"touser\":\"要发给的用户ID\",\"msgtype\":\"text\",\"agentid\":你的应用ID,\"text\":{\"content\":\"$msg\"},\"safe\":0}";$res = curlPost($Url,$data);$errmsg=json_decode($res)->errmsg;if($errmsg==="ok"){	echo "发送成功!";}else{	echo "发送失败,".$errmsg;}?>

?

?

更多介绍:http://www.cnblogs.com/jisheng/archive/2012/02/13/2350040.html

?

?

Statement:
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
Previous article:PHP调用WCF总结Next article:数组函数小结