PHP public number is developed to give users a micro message reminder function.

Keywords: Programming JSON

A recent project needs to send a wechat message prompt to users when they have funds received or members changed. In view of this, we started to use template messages, but the newly registered public numbers applied for message templates took several days to apply. In the absence of time, we chose to use customer service message interface, WeChat document address: https://mp.weixin.qq.com/wiki.

Here we skip the steps of web page authorization and user information acquisition, requesting interface, mainly looking at obtaining access_token, issuing customer service messages, checking whether to pay attention to public numbers and other interfaces.

 

1. Get access_token.

// Get access_token
public function getAccessToken($weid) {
        $appID = "wxfaddfdfdfd6cf6fc3569";                                      // Service number appID
        $appSecret = "071bebfdfdofdfd23687bf53d63a";                            // Service number appserve

        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appID&secret=$appSecret";
        $content = ihttp_get($url);                                             // Custom request function
        if(is_error($content)) {
            return error('-1', 'Access to WeChat public number authorization failed, Please try again later! Error details: ' . $content['message']);
        }
        if (empty($content['content'])) {
            return error('-1', 'AccessToken Failed to get, please check appid and appsecret Is the value consistent with wechat public platform?');
        }
        $token = @json_decode($content['content'], true);

        if ($token['errcode'] == '40164') {
            return error(-1, $this->errorCode($token['errcode'], $token['errmsg']));
        }
        if(empty($token) || !is_array($token) || empty($token['access_token']) || empty($token['expires_in'])) {
            $errorinfo = substr($content['meta'], strpos($content['meta'], '{'));
            $errorinfo = @json_decode($errorinfo, true);
            return error('-1', 'Access to WeChat public number authorization failed, Please try again later! The original data returned by the public platform is: error code-' . $errorinfo['errcode'] . ',error message-' . $errorinfo['errmsg']);
        }
        $record = array();
        $record['token'] = $token['access_token'];
        $record['expire'] = TIMESTAMP + $token['expires_in'] - 200;
        $cachekey = cache_system_key('accesstoken', array('acid' => $weid));
        cache_write($cachekey, $record);
        return $record['token'];
    }

 

2. decide whether to pay attention to the public number.

// Determine whether the current user is concerned about the public number.
public public function isSubscribe($weid,$userid) {
        // Get current user information
        $userinfo = pdo_get('hcface_users',array('uid'=>$userid));
		
		//return $userinfo;
        if(empty($userinfo)) {
            return false;
        }
        // Get access_token
        $accessToken = $this->getAccessToken($weid);

        // Whether to pay attention to the interface
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$accessToken."&openid=".$userinfo['openid']."&lang=zh_CN";
        $res = ihttp_request($url);
        
        if(is_error($res)) {
            return false;
        }
        if($res['code'] != '200') {
            return false;
        }
        
        $result = @json_decode($res['content'],true);

        if($result['subscribe'] == 1) {
            $updateData = [];
            // Determine whether the current user's Avatar and nickname are changed
            if($userinfo['avatar'] != $result['headimgurl']) {
                $updateData['avatar'] = $result['headimgurl'];
            }
            if($userinfo['nickname'] != $result['nickname']) {
                $updateData['avatar'] = $result['nickname'];
            }

            if(!empty($updateData)) {
                pdo_update('hcface_users',$updateData,array('uid'=>$userid));
            }
        }

        $userInfoData = [
            "subscribe" => $result['subscribe'],
            "user_openid" => $userinfo['openid'],
			"nickname" => $userinfo['nickname'],
        ];
        return $userInfoData;
    }

 

3. Send customer service message.

public function solPushMsg($openid, $content, $wid) {
        // Get access_token
        $accessToken = $this->getAccessToken($wid);

        $data = array(
          'touser' => $openid,              // User openID
          'msgtype' => 'text',
          'text' => [
                'content' => $content,     // content
            ],
        );
        $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$accessToken; 
        $res = ihttp_request($url,json_encode($data,JSON_UNESCAPED_UNICODE)); // The second parameter of JSON encode must be brought, otherwise the message sent may be unicode encoded.

        if(is_error($res)) {
            return false;
        }
        if($res['code'] != '200') {
            return false;
        }

        return @json_decode($res['content'],true);
    }

 

4. The wechat interface returns an array.

 

5. Achieve the effect.

 

official account

Posted by wiggly81 on Fri, 01 Nov 2019 14:39:12 -0700